cirq-core 1.6.0.dev20250501173104__py3-none-any.whl → 1.6.0.dev20250501231232__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.

Files changed (59) hide show
  1. cirq/_version.py +1 -1
  2. cirq/_version_test.py +1 -1
  3. cirq/contrib/paulistring/pauli_string_measurement_with_readout_mitigation.py +211 -107
  4. cirq/contrib/paulistring/pauli_string_measurement_with_readout_mitigation_test.py +347 -3
  5. cirq/transformers/analytical_decompositions/two_qubit_to_cz.py +18 -18
  6. cirq/transformers/analytical_decompositions/two_qubit_to_fsim.py +18 -19
  7. cirq/transformers/analytical_decompositions/two_qubit_to_ms.py +8 -10
  8. cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py +26 -28
  9. cirq/transformers/drop_empty_moments.py +4 -2
  10. cirq/transformers/drop_negligible_operations.py +6 -4
  11. cirq/transformers/dynamical_decoupling.py +6 -4
  12. cirq/transformers/dynamical_decoupling_test.py +8 -6
  13. cirq/transformers/eject_phased_paulis.py +14 -12
  14. cirq/transformers/eject_z.py +8 -6
  15. cirq/transformers/expand_composite.py +5 -3
  16. cirq/transformers/gauge_compiling/sqrt_cz_gauge.py +3 -1
  17. cirq/transformers/heuristic_decompositions/two_qubit_gate_tabulation.py +4 -1
  18. cirq/transformers/insertion_sort.py +6 -4
  19. cirq/transformers/measurement_transformers.py +21 -21
  20. cirq/transformers/merge_k_qubit_gates.py +11 -9
  21. cirq/transformers/merge_k_qubit_gates_test.py +5 -3
  22. cirq/transformers/merge_single_qubit_gates.py +15 -13
  23. cirq/transformers/optimize_for_target_gateset.py +14 -12
  24. cirq/transformers/optimize_for_target_gateset_test.py +7 -3
  25. cirq/transformers/qubit_management_transformers.py +10 -8
  26. cirq/transformers/randomized_measurements.py +9 -7
  27. cirq/transformers/routing/initial_mapper.py +5 -3
  28. cirq/transformers/routing/line_initial_mapper.py +15 -13
  29. cirq/transformers/routing/mapping_manager.py +9 -9
  30. cirq/transformers/routing/route_circuit_cqc.py +17 -15
  31. cirq/transformers/routing/visualize_routed_circuit.py +7 -6
  32. cirq/transformers/stratify.py +13 -11
  33. cirq/transformers/synchronize_terminal_measurements.py +9 -9
  34. cirq/transformers/target_gatesets/compilation_target_gateset.py +19 -17
  35. cirq/transformers/target_gatesets/compilation_target_gateset_test.py +11 -7
  36. cirq/transformers/target_gatesets/cz_gateset.py +4 -2
  37. cirq/transformers/target_gatesets/sqrt_iswap_gateset.py +5 -3
  38. cirq/transformers/transformer_api.py +17 -15
  39. cirq/transformers/transformer_primitives.py +22 -20
  40. cirq/transformers/transformer_primitives_test.py +3 -1
  41. cirq/value/classical_data.py +26 -26
  42. cirq/value/condition.py +23 -21
  43. cirq/value/duration.py +11 -8
  44. cirq/value/linear_dict.py +22 -20
  45. cirq/value/periodic_value.py +4 -4
  46. cirq/value/probability.py +3 -1
  47. cirq/value/product_state.py +14 -12
  48. cirq/work/collector.py +7 -5
  49. cirq/work/observable_measurement.py +24 -22
  50. cirq/work/observable_measurement_data.py +9 -7
  51. cirq/work/observable_readout_calibration.py +4 -1
  52. cirq/work/observable_readout_calibration_test.py +4 -1
  53. cirq/work/observable_settings.py +4 -2
  54. cirq/work/pauli_sum_collector.py +8 -6
  55. {cirq_core-1.6.0.dev20250501173104.dist-info → cirq_core-1.6.0.dev20250501231232.dist-info}/METADATA +1 -1
  56. {cirq_core-1.6.0.dev20250501173104.dist-info → cirq_core-1.6.0.dev20250501231232.dist-info}/RECORD +59 -59
  57. {cirq_core-1.6.0.dev20250501173104.dist-info → cirq_core-1.6.0.dev20250501231232.dist-info}/WHEEL +0 -0
  58. {cirq_core-1.6.0.dev20250501173104.dist-info → cirq_core-1.6.0.dev20250501231232.dist-info}/licenses/LICENSE +0 -0
  59. {cirq_core-1.6.0.dev20250501173104.dist-info → cirq_core-1.6.0.dev20250501231232.dist-info}/top_level.txt +0 -0
@@ -12,6 +12,8 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
+ from __future__ import annotations
16
+
15
17
  import itertools
16
18
  from collections import defaultdict
17
19
  from typing import Any, cast, Dict, Iterable, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union
@@ -33,7 +35,7 @@ class _MeasurementQid(ops.Qid):
33
35
  Exactly one qubit will be created per qubit in the measurement gate.
34
36
  """
35
37
 
36
- def __init__(self, key: Union[str, 'cirq.MeasurementKey'], qid: 'cirq.Qid', index: int = 0):
38
+ def __init__(self, key: Union[str, cirq.MeasurementKey], qid: cirq.Qid, index: int = 0):
37
39
  """Initializes the qubit.
38
40
 
39
41
  Args:
@@ -63,8 +65,8 @@ class _MeasurementQid(ops.Qid):
63
65
 
64
66
  @transformer_api.transformer
65
67
  def defer_measurements(
66
- circuit: 'cirq.AbstractCircuit', *, context: Optional['cirq.TransformerContext'] = None
67
- ) -> 'cirq.Circuit':
68
+ circuit: cirq.AbstractCircuit, *, context: Optional[cirq.TransformerContext] = None
69
+ ) -> cirq.Circuit:
68
70
  """Implements the Deferred Measurement Principle.
69
71
 
70
72
  Uses the Deferred Measurement Principle to move all measurements to the
@@ -94,11 +96,9 @@ def defer_measurements(
94
96
 
95
97
  circuit = transformer_primitives.unroll_circuit_op(circuit, deep=True, tags_to_check=None)
96
98
  terminal_measurements = {op for _, op in find_terminal_measurements(circuit)}
97
- measurement_qubits: Dict['cirq.MeasurementKey', List[Tuple['cirq.Qid', ...]]] = defaultdict(
98
- list
99
- )
99
+ measurement_qubits: Dict[cirq.MeasurementKey, List[Tuple[cirq.Qid, ...]]] = defaultdict(list)
100
100
 
101
- def defer(op: 'cirq.Operation', _) -> 'cirq.OP_TREE':
101
+ def defer(op: cirq.Operation, _) -> cirq.OP_TREE:
102
102
  if op in terminal_measurements:
103
103
  return op
104
104
  gate = op.gate
@@ -169,9 +169,9 @@ def defer_measurements(
169
169
 
170
170
 
171
171
  def _all_possible_datastore_states(
172
- keys: Iterable[Tuple['cirq.MeasurementKey', int]],
173
- measurement_qubits: Dict['cirq.MeasurementKey', List[Tuple['cirq.Qid', ...]]],
174
- ) -> Iterable['cirq.ClassicalDataStoreReader']:
172
+ keys: Iterable[Tuple[cirq.MeasurementKey, int]],
173
+ measurement_qubits: Dict[cirq.MeasurementKey, List[Tuple[cirq.Qid, ...]]],
174
+ ) -> Iterable[cirq.ClassicalDataStoreReader]:
175
175
  """The cartesian product of all possible DataStore states for the given keys."""
176
176
  # First we get the list of all possible values. So if we have a key mapped to qubits of shape
177
177
  # (2, 2) and a key mapped to a qutrit, the possible measurement values are:
@@ -214,10 +214,10 @@ def _all_possible_datastore_states(
214
214
 
215
215
  @transformer_api.transformer
216
216
  def dephase_measurements(
217
- circuit: 'cirq.AbstractCircuit',
217
+ circuit: cirq.AbstractCircuit,
218
218
  *,
219
- context: Optional['cirq.TransformerContext'] = transformer_api.TransformerContext(deep=True),
220
- ) -> 'cirq.Circuit':
219
+ context: Optional[cirq.TransformerContext] = transformer_api.TransformerContext(deep=True),
220
+ ) -> cirq.Circuit:
221
221
  """Changes all measurements to a dephase operation.
222
222
 
223
223
  This transformer is useful when using a density matrix simulator, when
@@ -240,7 +240,7 @@ def dephase_measurements(
240
240
  surprises.
241
241
  """
242
242
 
243
- def dephase(op: 'cirq.Operation', _) -> 'cirq.OP_TREE':
243
+ def dephase(op: cirq.Operation, _) -> cirq.OP_TREE:
244
244
  gate = op.gate
245
245
  if isinstance(gate, ops.MeasurementGate):
246
246
  key = value.MeasurementKey.parse_serialized(gate.key)
@@ -257,10 +257,10 @@ def dephase_measurements(
257
257
 
258
258
  @transformer_api.transformer
259
259
  def drop_terminal_measurements(
260
- circuit: 'cirq.AbstractCircuit',
260
+ circuit: cirq.AbstractCircuit,
261
261
  *,
262
- context: Optional['cirq.TransformerContext'] = transformer_api.TransformerContext(deep=True),
263
- ) -> 'cirq.Circuit':
262
+ context: Optional[cirq.TransformerContext] = transformer_api.TransformerContext(deep=True),
263
+ ) -> cirq.Circuit:
264
264
  """Removes terminal measurements from a circuit.
265
265
 
266
266
  This transformer is helpful when trying to capture the final state vector
@@ -289,7 +289,7 @@ def drop_terminal_measurements(
289
289
  if not circuit.are_all_measurements_terminal():
290
290
  raise ValueError('Circuit contains a non-terminal measurement.')
291
291
 
292
- def flip_inversion(op: 'cirq.Operation', _) -> 'cirq.OP_TREE':
292
+ def flip_inversion(op: cirq.Operation, _) -> cirq.OP_TREE:
293
293
  if isinstance(op.gate, ops.MeasurementGate):
294
294
  return [
295
295
  (
@@ -432,7 +432,7 @@ class _ConfusionChannel(ops.Gate):
432
432
  def _kraus_(self) -> Tuple[np.ndarray, ...]:
433
433
  return self._kraus
434
434
 
435
- def _apply_channel_(self, args: 'cirq.ApplyChannelArgs'):
435
+ def _apply_channel_(self, args: cirq.ApplyChannelArgs):
436
436
  configs: List[transformations._BuildFromSlicesArgs] = []
437
437
  for i in range(np.prod(self._shape) ** 2):
438
438
  scale = cast(complex, self._confusion_map.flat[i])
@@ -472,7 +472,7 @@ class _ModAdd(ops.ArithmeticGate):
472
472
  def registers(self) -> Tuple[Tuple[int], Tuple[int]]:
473
473
  return (self._dimension,), (self._dimension,)
474
474
 
475
- def with_registers(self, *new_registers) -> '_ModAdd':
475
+ def with_registers(self, *new_registers) -> _ModAdd:
476
476
  raise NotImplementedError()
477
477
 
478
478
  def apply(self, *register_values: int) -> Tuple[int, int]:
@@ -482,7 +482,7 @@ class _ModAdd(ops.ArithmeticGate):
482
482
  return self._dimension
483
483
 
484
484
 
485
- def _mod_add(source: 'cirq.Qid', target: 'cirq.Qid') -> 'cirq.Operation':
485
+ def _mod_add(source: cirq.Qid, target: cirq.Qid) -> cirq.Operation:
486
486
  assert source.dimension == target.dimension
487
487
  if source.dimension == 2:
488
488
  # Use a CX gate in 2D case for simplicity.
@@ -14,6 +14,8 @@
14
14
 
15
15
  """Transformer pass to merge connected components of k-qubit unitary operations."""
16
16
 
17
+ from __future__ import annotations
18
+
17
19
  from typing import Callable, cast, Optional, TYPE_CHECKING
18
20
 
19
21
  from cirq import circuits, ops, protocols
@@ -24,16 +26,16 @@ if TYPE_CHECKING:
24
26
 
25
27
 
26
28
  def _rewrite_merged_k_qubit_unitaries(
27
- circuit: 'cirq.AbstractCircuit',
29
+ circuit: cirq.AbstractCircuit,
28
30
  *,
29
- context: Optional['cirq.TransformerContext'] = None,
31
+ context: Optional[cirq.TransformerContext] = None,
30
32
  k: int = 0,
31
- rewriter: Optional[Callable[['cirq.CircuitOperation'], 'cirq.OP_TREE']] = None,
33
+ rewriter: Optional[Callable[[cirq.CircuitOperation], cirq.OP_TREE]] = None,
32
34
  merged_circuit_op_tag: str = "_merged_k_qubit_unitaries_component",
33
- ) -> 'cirq.Circuit':
35
+ ) -> cirq.Circuit:
34
36
  deep = context.deep if context else False
35
37
 
36
- def map_func(op: 'cirq.Operation', _) -> 'cirq.OP_TREE':
38
+ def map_func(op: cirq.Operation, _) -> cirq.OP_TREE:
37
39
  op_untagged = op.untagged
38
40
  if (
39
41
  deep
@@ -66,12 +68,12 @@ def _rewrite_merged_k_qubit_unitaries(
66
68
 
67
69
  @transformer_api.transformer
68
70
  def merge_k_qubit_unitaries(
69
- circuit: 'cirq.AbstractCircuit',
71
+ circuit: cirq.AbstractCircuit,
70
72
  *,
71
- context: Optional['cirq.TransformerContext'] = None,
73
+ context: Optional[cirq.TransformerContext] = None,
72
74
  k: int = 0,
73
- rewriter: Optional[Callable[['cirq.CircuitOperation'], 'cirq.OP_TREE']] = None,
74
- ) -> 'cirq.Circuit':
75
+ rewriter: Optional[Callable[[cirq.CircuitOperation], cirq.OP_TREE]] = None,
76
+ ) -> cirq.Circuit:
75
77
  """Merges connected components of unitary operations, acting on <= k qubits.
76
78
 
77
79
  Uses rewriter to convert a connected component of unitary operations acting on <= k-qubits
@@ -14,6 +14,8 @@
14
14
 
15
15
  # pylint: skip-file
16
16
 
17
+ from __future__ import annotations
18
+
17
19
  from typing import List
18
20
 
19
21
  import numpy as np
@@ -133,7 +135,7 @@ a: ═════════════════════════
133
135
  )
134
136
  component_id = 0
135
137
 
136
- def rewriter_merge_to_circuit_op(op: 'cirq.CircuitOperation') -> 'cirq.OP_TREE':
138
+ def rewriter_merge_to_circuit_op(op: cirq.CircuitOperation) -> cirq.OP_TREE:
137
139
  nonlocal component_id
138
140
  component_id = component_id + 1
139
141
  return op.with_tags(f'{component_id}')
@@ -160,7 +162,7 @@ a: ═════════════════════════
160
162
 
161
163
  component_id = 0
162
164
 
163
- def rewriter_replace_with_decomp(op: 'cirq.CircuitOperation') -> 'cirq.OP_TREE':
165
+ def rewriter_replace_with_decomp(op: cirq.CircuitOperation) -> cirq.OP_TREE:
164
166
  nonlocal component_id
165
167
  component_id = component_id + 1
166
168
  tag = f'{component_id}'
@@ -220,7 +222,7 @@ def test_merge_k_qubit_unitaries_deep():
220
222
 
221
223
  component_id = 0
222
224
 
223
- def rewriter_merge_to_circuit_op(op: 'cirq.CircuitOperation') -> 'cirq.OP_TREE':
225
+ def rewriter_merge_to_circuit_op(op: cirq.CircuitOperation) -> cirq.OP_TREE:
224
226
  nonlocal component_id
225
227
  component_id = component_id + 1
226
228
  return op.with_tags(f'{component_id}')
@@ -14,6 +14,8 @@
14
14
 
15
15
  """Transformer passes to combine adjacent single-qubit rotations."""
16
16
 
17
+ from __future__ import annotations
18
+
17
19
  from typing import Optional, TYPE_CHECKING
18
20
 
19
21
  from cirq import circuits, ops, protocols
@@ -26,11 +28,11 @@ if TYPE_CHECKING:
26
28
 
27
29
  @transformer_api.transformer
28
30
  def merge_single_qubit_gates_to_phased_x_and_z(
29
- circuit: 'cirq.AbstractCircuit',
31
+ circuit: cirq.AbstractCircuit,
30
32
  *,
31
- context: Optional['cirq.TransformerContext'] = None,
33
+ context: Optional[cirq.TransformerContext] = None,
32
34
  atol: float = 1e-8,
33
- ) -> 'cirq.Circuit':
35
+ ) -> cirq.Circuit:
34
36
  """Replaces runs of single qubit rotations with `cirq.PhasedXPowGate` and `cirq.ZPowGate`.
35
37
 
36
38
  Specifically, any run of non-parameterized single-qubit unitaries will be replaced by an
@@ -46,7 +48,7 @@ def merge_single_qubit_gates_to_phased_x_and_z(
46
48
  Copy of the transformed input circuit.
47
49
  """
48
50
 
49
- def rewriter(op: 'cirq.CircuitOperation') -> 'cirq.OP_TREE':
51
+ def rewriter(op: cirq.CircuitOperation) -> cirq.OP_TREE:
50
52
  u = protocols.unitary(op)
51
53
  if protocols.num_qubits(op) == 0:
52
54
  return ops.GlobalPhaseGate(u[0, 0]).on()
@@ -62,11 +64,11 @@ def merge_single_qubit_gates_to_phased_x_and_z(
62
64
 
63
65
  @transformer_api.transformer
64
66
  def merge_single_qubit_gates_to_phxz(
65
- circuit: 'cirq.AbstractCircuit',
67
+ circuit: cirq.AbstractCircuit,
66
68
  *,
67
- context: Optional['cirq.TransformerContext'] = None,
69
+ context: Optional[cirq.TransformerContext] = None,
68
70
  atol: float = 1e-8,
69
- ) -> 'cirq.Circuit':
71
+ ) -> cirq.Circuit:
70
72
  """Replaces runs of single qubit rotations with a single optional `cirq.PhasedXZGate`.
71
73
 
72
74
  Specifically, any run of non-parameterized single-qubit unitaries will be replaced by an
@@ -82,7 +84,7 @@ def merge_single_qubit_gates_to_phxz(
82
84
  Copy of the transformed input circuit.
83
85
  """
84
86
 
85
- def rewriter(op: 'cirq.CircuitOperation') -> 'cirq.OP_TREE':
87
+ def rewriter(op: cirq.CircuitOperation) -> cirq.OP_TREE:
86
88
  u = protocols.unitary(op)
87
89
  if protocols.num_qubits(op) == 0:
88
90
  return ops.GlobalPhaseGate(u[0, 0]).on()
@@ -96,11 +98,11 @@ def merge_single_qubit_gates_to_phxz(
96
98
 
97
99
  @transformer_api.transformer
98
100
  def merge_single_qubit_moments_to_phxz(
99
- circuit: 'cirq.AbstractCircuit',
101
+ circuit: cirq.AbstractCircuit,
100
102
  *,
101
- context: Optional['cirq.TransformerContext'] = None,
103
+ context: Optional[cirq.TransformerContext] = None,
102
104
  atol: float = 1e-8,
103
- ) -> 'cirq.Circuit':
105
+ ) -> cirq.Circuit:
104
106
  """Merges adjacent moments with only 1-qubit rotations to a single moment with PhasedXZ gates.
105
107
 
106
108
  Args:
@@ -114,7 +116,7 @@ def merge_single_qubit_moments_to_phxz(
114
116
  """
115
117
  tags_to_ignore = set(context.tags_to_ignore) if context else set()
116
118
 
117
- def can_merge_moment(m: 'cirq.Moment'):
119
+ def can_merge_moment(m: cirq.Moment):
118
120
  return all(
119
121
  protocols.num_qubits(op) == 1
120
122
  and protocols.has_unitary(op)
@@ -122,7 +124,7 @@ def merge_single_qubit_moments_to_phxz(
122
124
  for op in m
123
125
  )
124
126
 
125
- def merge_func(m1: 'cirq.Moment', m2: 'cirq.Moment') -> Optional['cirq.Moment']:
127
+ def merge_func(m1: cirq.Moment, m2: cirq.Moment) -> Optional[cirq.Moment]:
126
128
  if not (can_merge_moment(m1) and can_merge_moment(m2)):
127
129
  return None
128
130
  ret_ops = []
@@ -14,6 +14,8 @@
14
14
 
15
15
  """Transformers to rewrite a circuit using gates from a given target gateset."""
16
16
 
17
+ from __future__ import annotations
18
+
17
19
  from typing import Callable, Hashable, Optional, Sequence, TYPE_CHECKING, Union
18
20
 
19
21
  from cirq import circuits
@@ -24,8 +26,8 @@ if TYPE_CHECKING:
24
26
  import cirq
25
27
 
26
28
 
27
- def _create_on_stuck_raise_error(gateset: 'cirq.Gateset'):
28
- def _value_error_describing_bad_operation(op: 'cirq.Operation') -> ValueError:
29
+ def _create_on_stuck_raise_error(gateset: cirq.Gateset):
30
+ def _value_error_describing_bad_operation(op: cirq.Operation) -> ValueError:
29
31
  return ValueError(f"Unable to convert {op} to target gateset {gateset!r}")
30
32
 
31
33
  return _value_error_describing_bad_operation
@@ -33,14 +35,14 @@ def _create_on_stuck_raise_error(gateset: 'cirq.Gateset'):
33
35
 
34
36
  @transformer_api.transformer
35
37
  def _decompose_operations_to_target_gateset(
36
- circuit: 'cirq.AbstractCircuit',
38
+ circuit: cirq.AbstractCircuit,
37
39
  *,
38
- context: Optional['cirq.TransformerContext'] = None,
39
- gateset: Optional['cirq.Gateset'] = None,
40
- decomposer: Callable[['cirq.Operation', int], dp.DecomposeResult] = lambda *_: NotImplemented,
40
+ context: Optional[cirq.TransformerContext] = None,
41
+ gateset: Optional[cirq.Gateset] = None,
42
+ decomposer: Callable[[cirq.Operation, int], dp.DecomposeResult] = lambda *_: NotImplemented,
41
43
  ignore_failures: bool = True,
42
44
  tags_to_decompose: Sequence[Hashable] = (),
43
- ) -> 'cirq.Circuit':
45
+ ) -> cirq.Circuit:
44
46
  """Decomposes every operation to `gateset` using `cirq.decompose` and `decomposer`.
45
47
 
46
48
  This transformer attempts to decompose every operation `op` in the given circuit to `gateset`
@@ -68,7 +70,7 @@ def _decompose_operations_to_target_gateset(
68
70
  ValueError: If any input operation fails to convert and `ignore_failures` is False.
69
71
  """
70
72
 
71
- def map_func(op: 'cirq.Operation', moment_index: int):
73
+ def map_func(op: cirq.Operation, moment_index: int):
72
74
  if (
73
75
  context
74
76
  and context.deep
@@ -97,13 +99,13 @@ def _decompose_operations_to_target_gateset(
97
99
 
98
100
  @transformer_api.transformer
99
101
  def optimize_for_target_gateset(
100
- circuit: 'cirq.AbstractCircuit',
102
+ circuit: cirq.AbstractCircuit,
101
103
  *,
102
- context: Optional['cirq.TransformerContext'] = None,
103
- gateset: Optional['cirq.CompilationTargetGateset'] = None,
104
+ context: Optional[cirq.TransformerContext] = None,
105
+ gateset: Optional[cirq.CompilationTargetGateset] = None,
104
106
  ignore_failures: bool = True,
105
107
  max_num_passes: Union[int, None] = 1,
106
- ) -> 'cirq.Circuit':
108
+ ) -> cirq.Circuit:
107
109
  """Transforms the given circuit into an equivalent circuit using gates accepted by `gateset`.
108
110
 
109
111
  Repeat max_num_passes times or when `max_num_passes=None` until no further changes can be done
@@ -12,14 +12,18 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- from typing import Union
15
+ from __future__ import annotations
16
+
17
+ from typing import TYPE_CHECKING, Union
16
18
 
17
19
  import pytest
18
20
 
19
21
  import cirq
20
- from cirq.protocols.decompose_protocol import DecomposeResult
21
22
  from cirq.transformers.optimize_for_target_gateset import _decompose_operations_to_target_gateset
22
23
 
24
+ if TYPE_CHECKING:
25
+ from cirq.protocols.decompose_protocol import DecomposeResult
26
+
23
27
 
24
28
  def test_decompose_operations_raises_on_stuck():
25
29
  c_orig = cirq.Circuit(cirq.X(cirq.NamedQubit("q")).with_tags("ignore"))
@@ -121,7 +125,7 @@ class MatrixGateTargetGateset(cirq.CompilationTargetGateset):
121
125
  def num_qubits(self) -> int:
122
126
  return 2
123
127
 
124
- def decompose_to_target_gateset(self, op: 'cirq.Operation', _) -> DecomposeResult:
128
+ def decompose_to_target_gateset(self, op: cirq.Operation, _) -> DecomposeResult:
125
129
  if cirq.num_qubits(op) != 2 or not cirq.has_unitary(op):
126
130
  return NotImplemented
127
131
  return cirq.MatrixGate(cirq.unitary(op), name="M").on(*op.qubits)
@@ -12,6 +12,8 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
+ from __future__ import annotations
16
+
15
17
  from typing import Dict, Optional, Set, Tuple, TYPE_CHECKING
16
18
 
17
19
  from cirq import circuits, ops
@@ -21,8 +23,8 @@ if TYPE_CHECKING:
21
23
 
22
24
 
23
25
  def _get_qubit_mapping_first_and_last_moment(
24
- circuit: 'cirq.AbstractCircuit',
25
- ) -> Dict['cirq.Qid', Tuple[int, int]]:
26
+ circuit: cirq.AbstractCircuit,
27
+ ) -> Dict[cirq.Qid, Tuple[int, int]]:
26
28
  """Computes `(first_moment_idx, last_moment_idx)` tuple for each qubit in the input circuit.
27
29
 
28
30
  Args:
@@ -41,13 +43,13 @@ def _get_qubit_mapping_first_and_last_moment(
41
43
  return ret
42
44
 
43
45
 
44
- def _is_temp(q: 'cirq.Qid') -> bool:
46
+ def _is_temp(q: cirq.Qid) -> bool:
45
47
  return isinstance(q, (ops.CleanQubit, ops.BorrowableQubit))
46
48
 
47
49
 
48
50
  def map_clean_and_borrowable_qubits(
49
- circuit: 'cirq.AbstractCircuit', *, qm: Optional['cirq.QubitManager'] = None
50
- ) -> 'cirq.Circuit':
51
+ circuit: cirq.AbstractCircuit, *, qm: Optional[cirq.QubitManager] = None
52
+ ) -> cirq.Circuit:
51
53
  """Uses `qm: QubitManager` to map all `CleanQubit`/`BorrowableQubit`s to system qubits.
52
54
 
53
55
  `CleanQubit` and `BorrowableQubit` are internal qubit types that are used as placeholder qubits
@@ -97,11 +99,11 @@ def map_clean_and_borrowable_qubits(
97
99
  trivial_map = {q: q for q in all_qubits}
98
100
  # `allocated_map` maintains the mapping of all temporary qubits seen so far, mapping each of
99
101
  # them to either a newly allocated managed ancilla or an existing borrowed system qubit.
100
- allocated_map: Dict['cirq.Qid', 'cirq.Qid'] = {}
101
- to_free: Set['cirq.Qid'] = set()
102
+ allocated_map: Dict[cirq.Qid, cirq.Qid] = {}
103
+ to_free: Set[cirq.Qid] = set()
102
104
  last_op_idx = -1
103
105
 
104
- def map_func(op: 'cirq.Operation', idx: int) -> 'cirq.OP_TREE':
106
+ def map_func(op: cirq.Operation, idx: int) -> cirq.OP_TREE:
105
107
  nonlocal last_op_idx, to_free
106
108
  assert isinstance(qm, ops.QubitManager)
107
109
 
@@ -12,6 +12,8 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
+ from __future__ import annotations
16
+
15
17
  from collections.abc import Sequence
16
18
  from typing import Any
17
19
 
@@ -39,12 +41,12 @@ class RandomizedMeasurements:
39
41
 
40
42
  def __call__(
41
43
  self,
42
- circuit: "cirq.AbstractCircuit",
44
+ circuit: cirq.AbstractCircuit,
43
45
  unitary_ensemble: str = "pauli",
44
46
  rng: np.random.Generator | None = None,
45
47
  *,
46
48
  context: transformer_api.TransformerContext | None = None,
47
- ) -> "cirq.Circuit":
49
+ ) -> cirq.Circuit:
48
50
  """Apply the transformer to the given circuit. Given an input circuit returns
49
51
  a new circuit with the pre-measurement unitaries and measurements gates added.
50
52
  to the qubits in the subsystem provided.If no subsystem is specified in the
@@ -80,7 +82,7 @@ class RandomizedMeasurements:
80
82
 
81
83
  def random_single_qubit_unitary_moment(
82
84
  self, unitary_ensemble: str, qubits: Sequence[Any], rng: np.random.Generator
83
- ) -> "cirq.Moment":
85
+ ) -> cirq.Moment:
84
86
  """Outputs the cirq moment associated with the pre-measurement rotations.
85
87
 
86
88
  Args:
@@ -115,7 +117,7 @@ class RandomizedMeasurements:
115
117
  return cirq.Moment.from_ops(*op_list)
116
118
 
117
119
 
118
- def _pauli_basis_rotation(rng: np.random.Generator) -> "cirq.Gate":
120
+ def _pauli_basis_rotation(rng: np.random.Generator) -> cirq.Gate:
119
121
  """Randomly generate a Pauli basis rotation.
120
122
 
121
123
  Args:
@@ -127,7 +129,7 @@ def _pauli_basis_rotation(rng: np.random.Generator) -> "cirq.Gate":
127
129
  basis_idx = rng.choice(np.arange(3))
128
130
 
129
131
  if basis_idx == 0:
130
- gate: "cirq.Gate" = cirq.Ry(rads=-np.pi / 2)
132
+ gate: cirq.Gate = cirq.Ry(rads=-np.pi / 2)
131
133
  elif basis_idx == 1:
132
134
  gate = cirq.Rx(rads=np.pi / 2)
133
135
  else:
@@ -135,7 +137,7 @@ def _pauli_basis_rotation(rng: np.random.Generator) -> "cirq.Gate":
135
137
  return gate
136
138
 
137
139
 
138
- def _single_qubit_clifford(rng: np.random.Generator) -> "cirq.Gate":
140
+ def _single_qubit_clifford(rng: np.random.Generator) -> cirq.Gate:
139
141
  """Randomly generate a single-qubit Clifford rotation.
140
142
 
141
143
  Args:
@@ -153,7 +155,7 @@ def _single_qubit_clifford(rng: np.random.Generator) -> "cirq.Gate":
153
155
  )
154
156
 
155
157
 
156
- def _single_qubit_cue(rng: np.random.Generator) -> "cirq.Gate":
158
+ def _single_qubit_cue(rng: np.random.Generator) -> cirq.Gate:
157
159
  """Randomly generate a CUE gate.
158
160
 
159
161
  Args:
@@ -12,6 +12,8 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
+ from __future__ import annotations
16
+
15
17
  import abc
16
18
  from typing import Dict, TYPE_CHECKING
17
19
 
@@ -37,7 +39,7 @@ class AbstractInitialMapper(metaclass=abc.ABCMeta):
37
39
  """
38
40
 
39
41
  @abc.abstractmethod
40
- def initial_mapping(self, circuit: 'cirq.AbstractCircuit') -> Dict['cirq.Qid', 'cirq.Qid']:
42
+ def initial_mapping(self, circuit: cirq.AbstractCircuit) -> Dict[cirq.Qid, cirq.Qid]:
41
43
  """Maps the logical qubits of a circuit onto physical qubits on a device.
42
44
 
43
45
  Args:
@@ -52,10 +54,10 @@ class AbstractInitialMapper(metaclass=abc.ABCMeta):
52
54
  class HardCodedInitialMapper(AbstractInitialMapper):
53
55
  """Initial Mapper class takes a hard-coded mapping and returns it."""
54
56
 
55
- def __init__(self, _map: Dict['cirq.Qid', 'cirq.Qid']) -> None:
57
+ def __init__(self, _map: Dict[cirq.Qid, cirq.Qid]) -> None:
56
58
  self._map = _map
57
59
 
58
- def initial_mapping(self, circuit: 'cirq.AbstractCircuit') -> Dict['cirq.Qid', 'cirq.Qid']:
60
+ def initial_mapping(self, circuit: cirq.AbstractCircuit) -> Dict[cirq.Qid, cirq.Qid]:
59
61
  """Returns the hard-coded initial mapping.
60
62
 
61
63
  Args:
@@ -30,6 +30,8 @@ If some logical qubits are unampped after this first procedure then there are tw
30
30
  the nearest available neighbor to the center of the device.
31
31
  """
32
32
 
33
+ from __future__ import annotations
34
+
33
35
  from collections import deque
34
36
  from typing import Deque, Dict, List, Set, Tuple, TYPE_CHECKING
35
37
 
@@ -82,8 +84,8 @@ class LineInitialMapper(initial_mapper.AbstractInitialMapper):
82
84
  self.center = nx.center(self.device_graph)[0]
83
85
 
84
86
  def _make_circuit_graph(
85
- self, circuit: 'cirq.AbstractCircuit'
86
- ) -> Tuple[List[Deque['cirq.Qid']], Dict['cirq.Qid', 'cirq.Qid']]:
87
+ self, circuit: cirq.AbstractCircuit
88
+ ) -> Tuple[List[Deque[cirq.Qid]], Dict[cirq.Qid, cirq.Qid]]:
87
89
  """Creates a (potentially incomplete) qubit connectivity graph of the circuit.
88
90
 
89
91
  Iterates over moments in the circuit from left to right and adds edges between logical
@@ -99,11 +101,11 @@ class LineInitialMapper(initial_mapper.AbstractInitialMapper):
99
101
  The (potentially incomplete) qubit connectivity graph of the circuit, which is
100
102
  guaranteed to be a forest of line graphs.
101
103
  """
102
- circuit_graph: List[Deque['cirq.Qid']] = [deque([q]) for q in sorted(circuit.all_qubits())]
103
- component_id: Dict['cirq.Qid', int] = {q[0]: i for i, q in enumerate(circuit_graph)}
104
- partners: Dict['cirq.Qid', 'cirq.Qid'] = {}
104
+ circuit_graph: List[Deque[cirq.Qid]] = [deque([q]) for q in sorted(circuit.all_qubits())]
105
+ component_id: Dict[cirq.Qid, int] = {q[0]: i for i, q in enumerate(circuit_graph)}
106
+ partners: Dict[cirq.Qid, cirq.Qid] = {}
105
107
 
106
- def degree_lt_two(q: 'cirq.Qid'):
108
+ def degree_lt_two(q: cirq.Qid):
107
109
  return any(circuit_graph[component_id[q]][i] == q for i in [-1, 0])
108
110
 
109
111
  for op in circuit.all_operations():
@@ -141,7 +143,7 @@ class LineInitialMapper(initial_mapper.AbstractInitialMapper):
141
143
  )
142
144
  return graph, partners
143
145
 
144
- def initial_mapping(self, circuit: 'cirq.AbstractCircuit') -> Dict['cirq.Qid', 'cirq.Qid']:
146
+ def initial_mapping(self, circuit: cirq.AbstractCircuit) -> Dict[cirq.Qid, cirq.Qid]:
145
147
  """Maps disjoint lines of logical qubits onto lines of physical qubits.
146
148
 
147
149
  Args:
@@ -151,13 +153,13 @@ class LineInitialMapper(initial_mapper.AbstractInitialMapper):
151
153
  a dictionary that maps logical qubits in the circuit (keys) to physical qubits on the
152
154
  device (values).
153
155
  """
154
- mapped_physicals: Set['cirq.Qid'] = set()
155
- qubit_map: Dict['cirq.Qid', 'cirq.Qid'] = {}
156
+ mapped_physicals: Set[cirq.Qid] = set()
157
+ qubit_map: Dict[cirq.Qid, cirq.Qid] = {}
156
158
  circuit_graph, partners = self._make_circuit_graph(circuit)
157
159
 
158
160
  def next_physical(
159
- current_physical: 'cirq.Qid', partner: 'cirq.Qid', isolated: bool = False
160
- ) -> 'cirq.Qid':
161
+ current_physical: cirq.Qid, partner: cirq.Qid, isolated: bool = False
162
+ ) -> cirq.Qid:
161
163
  # Handle the first physical qubit getting mapped.
162
164
  if current_physical not in mapped_physicals:
163
165
  return current_physical
@@ -189,8 +191,8 @@ class LineInitialMapper(initial_mapper.AbstractInitialMapper):
189
191
  return qubit_map
190
192
 
191
193
  def _closest_unmapped_qubit(
192
- self, source: 'cirq.Qid', mapped_physicals: Set['cirq.Qid']
193
- ) -> 'cirq.Qid':
194
+ self, source: cirq.Qid, mapped_physicals: Set[cirq.Qid]
195
+ ) -> cirq.Qid:
194
196
  """Finds the closest available neighbor to a physical qubit 'source' on the device.
195
197
 
196
198
  Args: