cirq-core 1.5.0.dev20250102012912__py3-none-any.whl → 1.5.0.dev20250102032600__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of cirq-core might be problematic. Click here for more details.

cirq/_version.py CHANGED
@@ -28,4 +28,4 @@ if sys.version_info < (3, 10, 0): # pragma: no cover
28
28
  'of cirq (e.g. "python -m pip install cirq==1.1.*")'
29
29
  )
30
30
 
31
- __version__ = "1.5.0.dev20250102012912"
31
+ __version__ = "1.5.0.dev20250102032600"
cirq/_version_test.py CHANGED
@@ -3,4 +3,4 @@ import cirq
3
3
 
4
4
 
5
5
  def test_version():
6
- assert cirq.__version__ == "1.5.0.dev20250102012912"
6
+ assert cirq.__version__ == "1.5.0.dev20250102032600"
@@ -197,13 +197,14 @@ class QasmOutput:
197
197
  meas_key_id_map, meas_comments = self._generate_measurement_ids()
198
198
  self.meas_comments = meas_comments
199
199
  qubit_id_map = self._generate_qubit_ids()
200
+ self.cregs = self._generate_cregs(meas_key_id_map)
200
201
  self.args = protocols.QasmArgs(
201
202
  precision=precision,
202
203
  version=version,
203
204
  qubit_id_map=qubit_id_map,
204
205
  meas_key_id_map=meas_key_id_map,
206
+ meas_key_bitcount={k: v[0] for k, v in self.cregs.items()},
205
207
  )
206
- self.cregs = self._generate_cregs()
207
208
 
208
209
  def _generate_measurement_ids(self) -> Tuple[Dict[str, str], Dict[str, Optional[str]]]:
209
210
  # Pick an id for the creg that will store each measurement
@@ -227,7 +228,7 @@ class QasmOutput:
227
228
  def _generate_qubit_ids(self) -> Dict['cirq.Qid', str]:
228
229
  return {qubit: f'q[{i}]' for i, qubit in enumerate(self.qubits)}
229
230
 
230
- def _generate_cregs(self) -> Dict[str, tuple[int, str]]:
231
+ def _generate_cregs(self, meas_key_id_map: Dict[str, str]) -> Dict[str, tuple[int, str]]:
231
232
  """Pick an id for the creg that will store each measurement
232
233
 
233
234
  This function finds the largest measurement using each key.
@@ -239,7 +240,7 @@ class QasmOutput:
239
240
  cregs: Dict[str, tuple[int, str]] = {}
240
241
  for meas in self.measurements:
241
242
  key = protocols.measurement_key_name(meas)
242
- meas_id = self.args.meas_key_id_map[key]
243
+ meas_id = meas_key_id_map[key]
243
244
 
244
245
  if self.meas_comments[key] is not None:
245
246
  comment = f' // Measurement: {self.meas_comments[key]}'
@@ -219,4 +219,4 @@ class ClassicallyControlledOperation(raw_types.Operation):
219
219
  subop_qasm = protocols.qasm(self._sub_operation, args=args)
220
220
  if not self._conditions:
221
221
  return subop_qasm
222
- return f'if ({self._conditions[0].qasm}) {subop_qasm}'
222
+ return f'if ({protocols.qasm(self._conditions[0], args=args)}) {subop_qasm}'
@@ -196,7 +196,7 @@ a: ═══@═══╩══════════════════
196
196
  )
197
197
 
198
198
 
199
- def test_qasm():
199
+ def test_qasm_sympy_condition():
200
200
  q0, q1 = cirq.LineQubit.range(2)
201
201
  circuit = cirq.Circuit(
202
202
  cirq.measure(q0, key='a'),
@@ -222,6 +222,29 @@ if (m_a==0) x q[1];
222
222
  )
223
223
 
224
224
 
225
+ def test_qasm_key_condition():
226
+ q0, q1 = cirq.LineQubit.range(2)
227
+ circuit = cirq.Circuit(cirq.measure(q0, key='a'), cirq.X(q1).with_classical_controls('a'))
228
+ qasm = cirq.qasm(circuit)
229
+ assert (
230
+ qasm
231
+ == f"""// Generated from Cirq v{cirq.__version__}
232
+
233
+ OPENQASM 2.0;
234
+ include "qelib1.inc";
235
+
236
+
237
+ // Qubits: [q(0), q(1)]
238
+ qreg q[2];
239
+ creg m_a[1];
240
+
241
+
242
+ measure q[0] -> m_a[0];
243
+ if (m_a==1) x q[1];
244
+ """
245
+ )
246
+
247
+
225
248
  def test_qasm_no_conditions():
226
249
  q0, q1 = cirq.LineQubit.range(2)
227
250
  circuit = cirq.Circuit(
cirq/protocols/qasm.py CHANGED
@@ -38,6 +38,7 @@ class QasmArgs(string.Formatter):
38
38
  version: str = '2.0',
39
39
  qubit_id_map: Optional[Dict['cirq.Qid', str]] = None,
40
40
  meas_key_id_map: Optional[Dict[str, str]] = None,
41
+ meas_key_bitcount: Optional[Dict[str, int]] = None,
41
42
  ) -> None:
42
43
  """Inits QasmArgs.
43
44
 
@@ -49,11 +50,14 @@ class QasmArgs(string.Formatter):
49
50
  qubit_id_map: A dictionary mapping qubits to qreg QASM identifiers.
50
51
  meas_key_id_map: A dictionary mapping measurement keys to creg QASM
51
52
  identifiers.
53
+ meas_key_bitcount: A dictionary with of bits for each measurement
54
+ key.
52
55
  """
53
56
  self.precision = precision
54
57
  self.version = version
55
58
  self.qubit_id_map = {} if qubit_id_map is None else qubit_id_map
56
59
  self.meas_key_id_map = {} if meas_key_id_map is None else meas_key_id_map
60
+ self.meas_key_bitcount = {} if meas_key_bitcount is None else meas_key_bitcount
57
61
 
58
62
  def _format_number(self, value) -> str:
59
63
  """OpenQASM 2.0 does not support '1e-5' and wants '1.0e-5'"""
@@ -147,7 +151,7 @@ def qasm(
147
151
  involving qubits that the operation wouldn't otherwise know about.
148
152
  qubits: A list of qubits that the value is being applied to. This is
149
153
  needed for `cirq.Gate` values, which otherwise wouldn't know what
150
- qubits to talk about.
154
+ qubits to talk about. It should generally not be specified otherwise.
151
155
  default: A default result to use if the value doesn't have a
152
156
  `_qasm_` method or that method returns `NotImplemented` or `None`.
153
157
  If not specified, non-decomposable values cause a `TypeError`.
@@ -168,10 +172,16 @@ def qasm(
168
172
  kwargs: Dict[str, Any] = {}
169
173
  if args is not None:
170
174
  kwargs['args'] = args
175
+ # pylint: disable=not-callable
171
176
  if qubits is not None:
172
177
  kwargs['qubits'] = tuple(qubits)
173
- # pylint: disable=not-callable
174
- result = method(**kwargs)
178
+ try:
179
+ result = method(**kwargs)
180
+ except TypeError as error:
181
+ raise TypeError(
182
+ "cirq.qasm does not expect qubits or args to be specified"
183
+ f"for the given value of type {type(val)}."
184
+ ) from error
175
185
  # pylint: enable=not-callable
176
186
  if result is not None and result is not NotImplemented:
177
187
  return result
@@ -54,6 +54,11 @@ def test_qasm():
54
54
  assert cirq.qasm(ExpectsArgsQubits(), args=cirq.QasmArgs(), qubits=()) == 'text'
55
55
 
56
56
 
57
+ def test_qasm_qubits_improperly_supplied():
58
+ with pytest.raises(TypeError, match="does not expect qubits or args to be specified"):
59
+ _ = cirq.qasm(cirq.Circuit(), qubits=[cirq.LineQubit(1)])
60
+
61
+
57
62
  def test_qasm_args_formatting():
58
63
  args = cirq.QasmArgs()
59
64
  assert args.format_field(0.01, '') == '0.01'
cirq/value/condition.py CHANGED
@@ -14,7 +14,7 @@
14
14
 
15
15
  import abc
16
16
  import dataclasses
17
- from typing import Mapping, Tuple, TYPE_CHECKING, FrozenSet
17
+ from typing import Mapping, Tuple, TYPE_CHECKING, FrozenSet, Optional
18
18
 
19
19
  import sympy
20
20
 
@@ -47,6 +47,9 @@ class Condition(abc.ABC):
47
47
  def qasm(self):
48
48
  """Returns the qasm of this condition."""
49
49
 
50
+ def _qasm_(self, args: 'cirq.QasmArgs', **kwargs) -> Optional[str]:
51
+ return self.qasm
52
+
50
53
  def _with_measurement_key_mapping_(self, key_map: Mapping[str, str]) -> 'cirq.Condition':
51
54
  condition = self
52
55
  for k in self.keys:
@@ -115,6 +118,22 @@ class KeyCondition(Condition):
115
118
  def qasm(self):
116
119
  raise ValueError('QASM is defined only for SympyConditions of type key == constant.')
117
120
 
121
+ def _qasm_(self, args: 'cirq.QasmArgs', **kwargs) -> Optional[str]:
122
+ args.validate_version('2.0', '3.0')
123
+ key_str = str(self.key)
124
+ if key_str not in args.meas_key_id_map:
125
+ raise ValueError(f'Key "{key_str}" not in QasmArgs.meas_key_id_map.')
126
+ key = args.meas_key_id_map[key_str]
127
+ # QASM 3.0 supports !=, so we return it directly.
128
+ if args.version == '3.0':
129
+ return f'{key}!=0'
130
+ # QASM 2.0 only has == operator, so we must limit to single-bit measurement keys == 1.
131
+ if key not in args.meas_key_bitcount:
132
+ raise ValueError(f'Key "{key}" not in QasmArgs.meas_key_bitcount.')
133
+ if args.meas_key_bitcount[str(key)] != 1:
134
+ raise ValueError('QASM is defined only for single-bit classical conditions.')
135
+ return f'{key}==1'
136
+
118
137
 
119
138
  @dataclasses.dataclass(frozen=True)
120
139
  class SympyCondition(Condition):
@@ -71,6 +71,35 @@ def test_key_condition_qasm():
71
71
  _ = cirq.KeyCondition(cirq.MeasurementKey('a')).qasm
72
72
 
73
73
 
74
+ def test_key_condition_qasm_protocol():
75
+ cond = cirq.KeyCondition(cirq.MeasurementKey('a'))
76
+ args = cirq.QasmArgs(meas_key_id_map={'a': 'm_a'}, meas_key_bitcount={'m_a': 1})
77
+ qasm = cirq.qasm(cond, args=args)
78
+ assert qasm == 'm_a==1'
79
+
80
+
81
+ def test_key_condition_qasm_protocol_v3():
82
+ cond = cirq.KeyCondition(cirq.MeasurementKey('a'))
83
+ args = cirq.QasmArgs(meas_key_id_map={'a': 'm_a'}, version='3.0')
84
+ qasm = cirq.qasm(cond, args=args)
85
+ assert qasm == 'm_a!=0'
86
+
87
+
88
+ def test_key_condition_qasm_protocol_invalid_args():
89
+ cond = cirq.KeyCondition(cirq.MeasurementKey('a'))
90
+ args = cirq.QasmArgs()
91
+ with pytest.raises(ValueError, match='Key "a" not in QasmArgs.meas_key_id_map.'):
92
+ _ = cirq.qasm(cond, args=args)
93
+ args = cirq.QasmArgs(meas_key_id_map={'a': 'm_a'})
94
+ with pytest.raises(ValueError, match='Key "m_a" not in QasmArgs.meas_key_bitcount.'):
95
+ _ = cirq.qasm(cond, args=args)
96
+ args = cirq.QasmArgs(meas_key_id_map={'a': 'm_a'}, meas_key_bitcount={'m_a': 2})
97
+ with pytest.raises(
98
+ ValueError, match='QASM is defined only for single-bit classical conditions.'
99
+ ):
100
+ _ = cirq.qasm(cond, args=args)
101
+
102
+
74
103
  def test_sympy_condition_with_keys():
75
104
  c = init_sympy_condition.replace_key(key_a, key_b)
76
105
  assert c.keys == (key_b,)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: cirq-core
3
- Version: 1.5.0.dev20250102012912
3
+ Version: 1.5.0.dev20250102032600
4
4
  Summary: A framework for creating, editing, and invoking Noisy Intermediate Scale Quantum (NISQ) circuits.
5
5
  Home-page: http://github.com/quantumlib/cirq
6
6
  Author: The Cirq Developers
@@ -4,8 +4,8 @@ cirq/_compat_test.py,sha256=Qq3ZcfgD-Nb81cEppQdJqhAyrVqXKtfXZYGXT0p-Wh0,34718
4
4
  cirq/_doc.py,sha256=yDyWUD_2JDS0gShfGRb-rdqRt9-WeL7DhkqX7np0Nko,2879
5
5
  cirq/_import.py,sha256=p9gMHJscbtDDkfHOaulvd3Aer0pwUF5AXpL89XR8dNw,8402
6
6
  cirq/_import_test.py,sha256=6K_v0riZJXOXUphHNkGA8MY-JcmGlezFaGmvrNhm3OQ,1015
7
- cirq/_version.py,sha256=hjDNzZiwSD3oblkH7KQS5JtKGD16TXuAu3uVEJV87h8,1206
8
- cirq/_version_test.py,sha256=MglY2GxB6Y-NcvW-8KMSoXN1aa9DZMDsQlDxlbe1vZs,147
7
+ cirq/_version.py,sha256=J0r5SOn_ANC11d5zrAPyjHHvRUEV09wGAkLtD7X9Ys0,1206
8
+ cirq/_version_test.py,sha256=aEJgmUVMrQnnHdSVCrH9FeJ0sdS_gJr4MrLK1cYKTa0,147
9
9
  cirq/conftest.py,sha256=X7yLFL8GLhg2CjPw0hp5e_dGASfvHx1-QT03aUbhKJw,1168
10
10
  cirq/json_resolver_cache.py,sha256=03MVo6Y-UYrzt9CKHmwpiBLN2ixL6uSU-OWnKZXfG7k,13302
11
11
  cirq/py.typed,sha256=VFSlmh_lNwnaXzwY-ZuW-C2Ws5PkuDoVgBdNCs0jXJE,63
@@ -28,7 +28,7 @@ cirq/circuits/moment.py,sha256=MskIVl5jbGnZdKKLNWbrQhWI5FHwjsuPOEm0hze8GDE,26299
28
28
  cirq/circuits/moment_test.py,sha256=oNHNXhiPEoCKbzeh16tRwiW1qZWlg4X2O_uiVDP1D58,27375
29
29
  cirq/circuits/optimization_pass.py,sha256=uw3ne0-ebZo6GNjwfQMuQ3b5u9RCgyaXRfhpbljlxao,6468
30
30
  cirq/circuits/optimization_pass_test.py,sha256=eQB0NBJ9EvqjgSFGQMgaHIh5niQhksdnvqSXhsj3nOg,5947
31
- cirq/circuits/qasm_output.py,sha256=atCdZwEx3T8NgiFuA7X4vx0jEo9REh1MyjiROutx4cg,12963
31
+ cirq/circuits/qasm_output.py,sha256=QUOeggq7NK3qm342dk47SNRi2qh4_98_gI3SdPjqRkA,13073
32
32
  cirq/circuits/qasm_output_test.py,sha256=PawmzjqGpwauWgESqoi_U_iaYVZAMg_eIhZ_2VrPkPw,13634
33
33
  cirq/circuits/text_diagram_drawer.py,sha256=ctZUG5fk2pf4XswHTJG4kteQYzzH0TefL9JWUagLJvc,17232
34
34
  cirq/circuits/text_diagram_drawer_test.py,sha256=2bSoBIeQajRi0aQxqYDpbMlT2eqpx_f-Cmg9XO6A9Jk,10750
@@ -268,8 +268,8 @@ cirq/ops/arithmetic_operation.py,sha256=PBqIwOfADRlsij11Lo1ao_OZM-O8PDlObgZBxGKs
268
268
  cirq/ops/arithmetic_operation_test.py,sha256=axy8xy9IvDb-ATUV-LE1HNWRqCEz06VyZWVrLNOtXXI,4942
269
269
  cirq/ops/boolean_hamiltonian.py,sha256=li003lNq6zS8pNPTobqzfzYJvyvaIpCVo3wkliI6Hzk,14930
270
270
  cirq/ops/boolean_hamiltonian_test.py,sha256=1ey5yfYZPKZDsfM3jpCPAOpbPs_y8i4K_WvDK2d5_4Y,8518
271
- cirq/ops/classically_controlled_operation.py,sha256=3YhnNQa7wNyDN0A45z23nkWzl5cI95KMYukUb4cQa2c,9082
272
- cirq/ops/classically_controlled_operation_test.py,sha256=aNyt2RFWlC_v0PX5TVYWiSkvXB_-z-rkVrHu6ZjJdVg,49679
271
+ cirq/ops/classically_controlled_operation.py,sha256=qTOsbGRZFbQIaBj9iee31V_V8oMLqWIJjgFomy3kg4A,9104
272
+ cirq/ops/classically_controlled_operation_test.py,sha256=pWuvxqbH9AvXdpMMaCkvozD8rIVNH0vmaYQkDPTyk4E,50117
273
273
  cirq/ops/clifford_gate.py,sha256=qAKS0wqqoHljOF63treyR95I6H0yWFZBiHQoM4sLgSc,39350
274
274
  cirq/ops/clifford_gate_test.py,sha256=NF_if1X8LCMA9hy0vBO7lxvVPdumlvMMnI2XRQ-RLpk,37472
275
275
  cirq/ops/common_channels.py,sha256=uqgocTUhtuJ4VZI_9_3L34gBRTf1A10mByhZY4Q1fB8,38283
@@ -419,8 +419,8 @@ cirq/protocols/phase_protocol.py,sha256=dXZRJb7aT8ZvtliItZOvoiaev-QvjBT4SknwZ5p-
419
419
  cirq/protocols/phase_protocol_test.py,sha256=eU4g6VDqfWZCpklVlY1t5msc5kAZsP-UlPrROLll_ms,1939
420
420
  cirq/protocols/pow_protocol.py,sha256=0wgb4LLAkOWjmP_u-_6IweXovDViocbdSgtsMOcXdkM,3290
421
421
  cirq/protocols/pow_protocol_test.py,sha256=8eBcGUqRWSSYkEkvSHXL6tcv1o-ilnl6nzgNl9vfctg,1626
422
- cirq/protocols/qasm.py,sha256=ekPlvfHIz9PUPdLeO7P_KMRuAh0rngM7r5grmW3kdWM,6869
423
- cirq/protocols/qasm_test.py,sha256=MFkqSHByCbB46XOlAJgKQgEpANVwnmfO-tD-XofqrQ4,2013
422
+ cirq/protocols/qasm.py,sha256=5i9_hznujNQ96dNipsBd7gy9B3p2SKlXk3VMTEBh-RY,7406
423
+ cirq/protocols/qasm_test.py,sha256=O6QdL45eEPigqzy_oLB_CjFSQhtKUBmCtQWNdk7j8Zg,2216
424
424
  cirq/protocols/qid_shape_protocol.py,sha256=jCAdpBBkEyK6JGmZwVBp__lHW3JhLmYt0Qzf8OgZtNU,7690
425
425
  cirq/protocols/qid_shape_protocol_test.py,sha256=Qjo-wemjkP__1jQnVkkB91mUs8EpfXyKI9GzeZQVb1E,2303
426
426
  cirq/protocols/resolve_parameters.py,sha256=NVFS5PSq18Hcvjv_P6vaZIa2D4OCgZY1u5j6QgPMlTA,7374
@@ -1136,8 +1136,8 @@ cirq/value/angle.py,sha256=vNZfTE3WmbWPYBKSPt--wvTub5bgUhmKR7ao_dIlyBQ,3313
1136
1136
  cirq/value/angle_test.py,sha256=PqeTBGJw6zfain4cG8FYMobtYQsfyxLQeBu_CF5fIjg,3548
1137
1137
  cirq/value/classical_data.py,sha256=so7OCCfEGU2XU1yc5kWz2yhryK8s4FFChqi9GEV4hqE,11607
1138
1138
  cirq/value/classical_data_test.py,sha256=23ZraKZ-V3p-uux21bkcboQcEp81RW6VKnVIYPQc6_o,5231
1139
- cirq/value/condition.py,sha256=QrxKBAox4C-z2pL2_xeKMvmfp0OP4tVFXJdPULx1pik,5900
1140
- cirq/value/condition_test.py,sha256=FGnCFcpeIQFRbnszKsHKA5K7sderTz7kwS7zWbWwx64,4037
1139
+ cirq/value/condition.py,sha256=6zySgSYoBILG9jpybxQns3J_Yni3tsd-bM6aI69AUPo,6842
1140
+ cirq/value/condition_test.py,sha256=qA2o54siDnTXdvCP2meoynhGgUnbIgqN-WiUqdruGbA,5208
1141
1141
  cirq/value/digits.py,sha256=pUQi6PIA1FMbXUOWknefb6dBApCyLsTkpLFrhvNgE0Q,6024
1142
1142
  cirq/value/digits_test.py,sha256=evx-y619LfjSN_gUO1B6K7O80X5HJmxxBPl61RrOovo,3812
1143
1143
  cirq/value/duration.py,sha256=isNzA1TuKb5rSaAYy4JpgT91Zt9_5XLQBSmMkuWCtD4,10358
@@ -1189,8 +1189,8 @@ cirq/work/sampler.py,sha256=bE5tmVkcR6cZZMLETxDfHehdsYUMbx2RvBeIBetehI4,19187
1189
1189
  cirq/work/sampler_test.py,sha256=hL2UWx3dz2ukZVNxWftiKVvJcQoLplLZdQm-k1QcA40,13282
1190
1190
  cirq/work/zeros_sampler.py,sha256=x1C7cup66a43n-3tm8QjhiqJa07qcJW10FxNp9jJ59Q,2356
1191
1191
  cirq/work/zeros_sampler_test.py,sha256=JIkpBBFPJe5Ba4142vzogyWyboG1Q1ZAm0UVGgOoZn8,3279
1192
- cirq_core-1.5.0.dev20250102012912.dist-info/LICENSE,sha256=tAkwu8-AdEyGxGoSvJ2gVmQdcicWw3j1ZZueVV74M-E,11357
1193
- cirq_core-1.5.0.dev20250102012912.dist-info/METADATA,sha256=s4xkfrGYnefP_1yKv-sW10ys8FedPI67_fcuBGnrpRw,1992
1194
- cirq_core-1.5.0.dev20250102012912.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
1195
- cirq_core-1.5.0.dev20250102012912.dist-info/top_level.txt,sha256=Sz9iOxHU0IEMLSFGwiwOCaN2e9K-jFbBbtpPN1hB73g,5
1196
- cirq_core-1.5.0.dev20250102012912.dist-info/RECORD,,
1192
+ cirq_core-1.5.0.dev20250102032600.dist-info/LICENSE,sha256=tAkwu8-AdEyGxGoSvJ2gVmQdcicWw3j1ZZueVV74M-E,11357
1193
+ cirq_core-1.5.0.dev20250102032600.dist-info/METADATA,sha256=WoEJv1juOxa6z-_njCWMj9FJErh6l6ZzYzSRdsG8CeU,1992
1194
+ cirq_core-1.5.0.dev20250102032600.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
1195
+ cirq_core-1.5.0.dev20250102032600.dist-info/top_level.txt,sha256=Sz9iOxHU0IEMLSFGwiwOCaN2e9K-jFbBbtpPN1hB73g,5
1196
+ cirq_core-1.5.0.dev20250102032600.dist-info/RECORD,,