cirq-core 1.5.0.dev20250403170622__py3-none-any.whl → 1.5.0.dev20250404165440__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 (56) hide show
  1. cirq/_version.py +1 -1
  2. cirq/_version_test.py +1 -1
  3. cirq/circuits/circuit.py +144 -147
  4. cirq/circuits/circuit_operation.py +37 -34
  5. cirq/circuits/circuit_operation_test.py +1 -1
  6. cirq/circuits/circuit_test.py +4 -6
  7. cirq/circuits/frozen_circuit.py +30 -26
  8. cirq/circuits/moment.py +37 -37
  9. cirq/circuits/optimization_pass.py +11 -11
  10. cirq/circuits/optimization_pass_test.py +6 -8
  11. cirq/circuits/qasm_output.py +13 -11
  12. cirq/circuits/text_diagram_drawer.py +9 -7
  13. cirq/contrib/acquaintance/bipartite.py +7 -5
  14. cirq/contrib/acquaintance/devices.py +3 -1
  15. cirq/contrib/acquaintance/executor.py +14 -16
  16. cirq/contrib/acquaintance/gates.py +19 -21
  17. cirq/contrib/acquaintance/inspection_utils.py +8 -6
  18. cirq/contrib/acquaintance/mutation_utils.py +8 -6
  19. cirq/contrib/acquaintance/optimizers.py +5 -3
  20. cirq/contrib/acquaintance/permutation.py +19 -19
  21. cirq/contrib/acquaintance/shift.py +5 -3
  22. cirq/contrib/acquaintance/shift_swap_network.py +5 -3
  23. cirq/contrib/acquaintance/strategies/complete.py +4 -2
  24. cirq/contrib/acquaintance/strategies/cubic.py +4 -2
  25. cirq/contrib/acquaintance/strategies/quartic_paired.py +8 -6
  26. cirq/contrib/acquaintance/topological_sort.py +4 -2
  27. cirq/contrib/bayesian_network/bayesian_network_gate.py +4 -2
  28. cirq/contrib/circuitdag/circuit_dag.py +18 -16
  29. cirq/contrib/custom_simulators/custom_state_simulator.py +10 -8
  30. cirq/contrib/custom_simulators/custom_state_simulator_test.py +9 -7
  31. cirq/contrib/graph_device/graph_device.py +4 -2
  32. cirq/contrib/noise_models/noise_models.py +7 -5
  33. cirq/contrib/paulistring/clifford_target_gateset.py +11 -9
  34. cirq/contrib/qcircuit/qcircuit_diagram.py +5 -2
  35. cirq/contrib/qcircuit/qcircuit_pdf.py +7 -11
  36. cirq/contrib/qcircuit/qcircuit_pdf_test.py +10 -2
  37. cirq/contrib/quantum_volume/quantum_volume.py +4 -4
  38. cirq/contrib/quimb/mps_simulator.py +25 -26
  39. cirq/contrib/routing/greedy.py +5 -3
  40. cirq/contrib/routing/initialization.py +3 -1
  41. cirq/contrib/routing/swap_network.py +5 -5
  42. cirq/contrib/routing/utils.py +4 -2
  43. cirq/contrib/svg/svg.py +9 -6
  44. cirq/devices/device.py +11 -9
  45. cirq/devices/grid_device_metadata.py +14 -11
  46. cirq/devices/grid_qubit.py +17 -21
  47. cirq/devices/grid_qubit_test.py +1 -1
  48. cirq/devices/insertion_noise_model.py +5 -5
  49. cirq/devices/line_qubit.py +15 -17
  50. cirq/devices/named_topologies.py +6 -4
  51. cirq/devices/noise_model.py +27 -31
  52. {cirq_core-1.5.0.dev20250403170622.dist-info → cirq_core-1.5.0.dev20250404165440.dist-info}/METADATA +1 -1
  53. {cirq_core-1.5.0.dev20250403170622.dist-info → cirq_core-1.5.0.dev20250404165440.dist-info}/RECORD +56 -56
  54. {cirq_core-1.5.0.dev20250403170622.dist-info → cirq_core-1.5.0.dev20250404165440.dist-info}/LICENSE +0 -0
  55. {cirq_core-1.5.0.dev20250403170622.dist-info → cirq_core-1.5.0.dev20250404165440.dist-info}/WHEEL +0 -0
  56. {cirq_core-1.5.0.dev20250403170622.dist-info → cirq_core-1.5.0.dev20250404165440.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 typing import (
17
19
  Callable,
@@ -109,7 +111,7 @@ class _GreedyRouter:
109
111
  op1.qubits
110
112
  )
111
113
  & set(op2.qubits),
112
- random_state: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,
114
+ random_state: cirq.RANDOM_STATE_OR_SEED_LIKE = None,
113
115
  ):
114
116
 
115
117
  self.prng = value.parse_random_state(random_state)
@@ -148,12 +150,12 @@ class _GreedyRouter:
148
150
  ]
149
151
  return self.edge_sets[edge_set_size]
150
152
 
151
- def log_to_phys(self, *qubits: 'cirq.Qid') -> Iterable[ops.Qid]:
153
+ def log_to_phys(self, *qubits: cirq.Qid) -> Iterable[ops.Qid]:
152
154
  """Returns an iterator over the physical qubits mapped to by the given
153
155
  logical qubits."""
154
156
  return (self._log_to_phys[q] for q in qubits)
155
157
 
156
- def phys_to_log(self, *qubits: 'cirq.Qid') -> Iterable[Optional[ops.Qid]]:
158
+ def phys_to_log(self, *qubits: cirq.Qid) -> Iterable[Optional[ops.Qid]]:
157
159
  """Returns an iterator over the logical qubits that map to the given
158
160
  physical qubits."""
159
161
  return (self._phys_to_log[q] for q in 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
  import itertools
16
18
  from typing import cast, Dict, Hashable, TYPE_CHECKING
17
19
 
@@ -32,7 +34,7 @@ def get_center(graph: nx.Graph) -> Hashable:
32
34
  def get_initial_mapping(
33
35
  logical_graph: nx.Graph,
34
36
  device_graph: nx.Graph,
35
- random_state: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,
37
+ random_state: cirq.RANDOM_STATE_OR_SEED_LIKE = None,
36
38
  ) -> Dict[ops.Qid, ops.Qid]:
37
39
  """Gets an initial mapping of logical to physical qubits for routing.
38
40
 
@@ -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, Iterable, TYPE_CHECKING
16
18
 
17
19
  import cirq.contrib.acquaintance as cca
@@ -35,20 +37,18 @@ class SwapNetwork:
35
37
  initial_mapping: The initial mapping from physical to logical qubits.
36
38
  """
37
39
 
38
- def __init__(
39
- self, circuit: 'cirq.Circuit', initial_mapping: Dict['cirq.Qid', 'cirq.Qid']
40
- ) -> None:
40
+ def __init__(self, circuit: cirq.Circuit, initial_mapping: Dict[cirq.Qid, cirq.Qid]) -> None:
41
41
  if not all(isinstance(i, ops.Qid) for I in initial_mapping.items() for i in I):
42
42
  raise ValueError('Mapping must be from Qids to Qids.')
43
43
  self.circuit = circuit
44
44
  self.initial_mapping = initial_mapping
45
45
 
46
- def final_mapping(self) -> Dict['cirq.Qid', 'cirq.Qid']:
46
+ def final_mapping(self) -> Dict[cirq.Qid, cirq.Qid]:
47
47
  mapping = dict(self.initial_mapping)
48
48
  cca.update_mapping(mapping, self.circuit.all_operations())
49
49
  return mapping
50
50
 
51
- def get_logical_operations(self) -> Iterable['cirq.Operation']:
51
+ def get_logical_operations(self) -> Iterable[cirq.Operation]:
52
52
  return cca.get_logical_operations(self.circuit.all_operations(), self.initial_mapping)
53
53
 
54
54
  def __eq__(self, other) -> bool:
@@ -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 operator
16
18
  import re
17
19
  from typing import Callable, Iterable, List, TYPE_CHECKING
@@ -21,10 +23,10 @@ import networkx as nx
21
23
  import cirq.contrib.acquaintance as cca
22
24
  from cirq import circuits, ops
23
25
  from cirq.contrib.circuitdag import CircuitDag
24
- from cirq.contrib.routing.swap_network import SwapNetwork
25
26
 
26
27
  if TYPE_CHECKING:
27
28
  import cirq
29
+ from cirq.contrib.routing import SwapNetwork
28
30
 
29
31
  BINARY_OP_PREDICATE = Callable[[ops.Operation, ops.Operation], bool]
30
32
 
@@ -86,7 +88,7 @@ def is_valid_routing(
86
88
  raise
87
89
 
88
90
 
89
- def get_circuit_connectivity(circuit: 'cirq.Circuit') -> nx.Graph:
91
+ def get_circuit_connectivity(circuit: cirq.Circuit) -> nx.Graph:
90
92
  """Return a graph of all 2q interactions in a circuit.
91
93
 
92
94
  Nodes are qubits and undirected edges correspond to any two-qubit
cirq/contrib/svg/svg.py CHANGED
@@ -1,4 +1,7 @@
1
1
  # pylint: disable=wrong-or-nonexistent-copyright-notice
2
+
3
+ from __future__ import annotations
4
+
2
5
  from typing import cast, Dict, List, Tuple, TYPE_CHECKING
3
6
 
4
7
  import matplotlib.font_manager
@@ -59,7 +62,7 @@ def _text(x: float, y: float, text: str, fontsize: int = 14):
59
62
 
60
63
 
61
64
  def _fit_horizontal(
62
- tdd: 'cirq.TextDiagramDrawer', ref_boxwidth: float, col_padding: float
65
+ tdd: cirq.TextDiagramDrawer, ref_boxwidth: float, col_padding: float
63
66
  ) -> Tuple[List[float], List[float]]:
64
67
  """Figure out the horizontal spacing of columns to fit everything in.
65
68
 
@@ -89,7 +92,7 @@ def _fit_horizontal(
89
92
 
90
93
 
91
94
  def _fit_vertical(
92
- tdd: 'cirq.TextDiagramDrawer', ref_boxheight: float, row_padding: float
95
+ tdd: cirq.TextDiagramDrawer, ref_boxheight: float, row_padding: float
93
96
  ) -> Tuple[List[float], List[float], Dict[float, int]]:
94
97
  """Return data structures used to turn tdd vertical coordinates into
95
98
  well-spaced SVG coordinates.
@@ -164,7 +167,7 @@ def _debug_spacing(col_starts, row_starts): # pragma: no cover
164
167
 
165
168
 
166
169
  def tdd_to_svg(
167
- tdd: 'cirq.TextDiagramDrawer',
170
+ tdd: cirq.TextDiagramDrawer,
168
171
  ref_boxwidth: float = 40,
169
172
  ref_boxheight: float = 40,
170
173
  col_padding: float = 20,
@@ -246,7 +249,7 @@ def tdd_to_svg(
246
249
  return t
247
250
 
248
251
 
249
- def _validate_circuit(circuit: 'cirq.Circuit'):
252
+ def _validate_circuit(circuit: cirq.Circuit):
250
253
  if len(circuit) == 0:
251
254
  raise ValueError("Can't draw SVG diagram for empty circuits")
252
255
 
@@ -260,14 +263,14 @@ class SVGCircuit:
260
263
  which will cause the circuit to be displayed as an SVG image.
261
264
  """
262
265
 
263
- def __init__(self, circuit: 'cirq.Circuit'):
266
+ def __init__(self, circuit: cirq.Circuit):
264
267
  self.circuit = circuit
265
268
 
266
269
  def _repr_svg_(self) -> str:
267
270
  return circuit_to_svg(self.circuit)
268
271
 
269
272
 
270
- def circuit_to_svg(circuit: 'cirq.Circuit') -> str:
273
+ def circuit_to_svg(circuit: cirq.Circuit) -> str:
271
274
  """Render a circuit as SVG."""
272
275
  _validate_circuit(circuit)
273
276
  tdd = circuit.to_text_diagram_drawer(transpose=False)
cirq/devices/device.py CHANGED
@@ -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 FrozenSet, Iterable, Optional, TYPE_CHECKING
17
19
 
@@ -57,7 +59,7 @@ class Device(metaclass=abc.ABCMeta):
57
59
  """
58
60
 
59
61
  @property
60
- def metadata(self) -> Optional['DeviceMetadata']:
62
+ def metadata(self) -> Optional[DeviceMetadata]:
61
63
  """Returns the associated Metadata with the device if applicable.
62
64
 
63
65
  Returns:
@@ -65,7 +67,7 @@ class Device(metaclass=abc.ABCMeta):
65
67
  """
66
68
  return None
67
69
 
68
- def validate_operation(self, operation: 'cirq.Operation') -> None:
70
+ def validate_operation(self, operation: cirq.Operation) -> None:
69
71
  """Raises an exception if an operation is not valid.
70
72
 
71
73
  Args:
@@ -75,7 +77,7 @@ class Device(metaclass=abc.ABCMeta):
75
77
  ValueError: The operation isn't valid for this device.
76
78
  """
77
79
 
78
- def validate_circuit(self, circuit: 'cirq.AbstractCircuit') -> None:
80
+ def validate_circuit(self, circuit: cirq.AbstractCircuit) -> None:
79
81
  """Raises an exception if a circuit is not valid.
80
82
 
81
83
  Args:
@@ -87,7 +89,7 @@ class Device(metaclass=abc.ABCMeta):
87
89
  for moment in circuit:
88
90
  self.validate_moment(moment)
89
91
 
90
- def validate_moment(self, moment: 'cirq.Moment') -> None:
92
+ def validate_moment(self, moment: cirq.Moment) -> None:
91
93
  """Raises an exception if a moment is not valid.
92
94
 
93
95
  Args:
@@ -104,7 +106,7 @@ class Device(metaclass=abc.ABCMeta):
104
106
  class DeviceMetadata:
105
107
  """Parent type for all device specific metadata classes."""
106
108
 
107
- def __init__(self, qubits: Iterable['cirq.Qid'], nx_graph: 'nx.Graph'):
109
+ def __init__(self, qubits: Iterable[cirq.Qid], nx_graph: nx.Graph):
108
110
  """Construct a DeviceMetadata object.
109
111
 
110
112
  Args:
@@ -114,11 +116,11 @@ class DeviceMetadata:
114
116
  directional coupling, undirected edges indicate bi-directional
115
117
  coupling.
116
118
  """
117
- self._qubits_set: FrozenSet['cirq.Qid'] = frozenset(qubits)
119
+ self._qubits_set: FrozenSet[cirq.Qid] = frozenset(qubits)
118
120
  self._nx_graph = nx_graph
119
121
 
120
122
  @property
121
- def qubit_set(self) -> FrozenSet['cirq.Qid']:
123
+ def qubit_set(self) -> FrozenSet[cirq.Qid]:
122
124
  """Returns the set of qubits on the device.
123
125
 
124
126
  Returns:
@@ -127,7 +129,7 @@ class DeviceMetadata:
127
129
  return self._qubits_set
128
130
 
129
131
  @property
130
- def nx_graph(self) -> 'nx.Graph':
132
+ def nx_graph(self) -> nx.Graph:
131
133
  """Returns a nx.Graph where nodes are qubits and edges are couple-able qubits.
132
134
 
133
135
  Returns:
@@ -150,6 +152,6 @@ class DeviceMetadata:
150
152
  return {'qubits': qubits_payload, 'nx_graph': graph_payload}
151
153
 
152
154
  @classmethod
153
- def _from_json_dict_(cls, qubits: Iterable['cirq.Qid'], nx_graph: 'nx.Graph', **kwargs):
155
+ def _from_json_dict_(cls, qubits: Iterable[cirq.Qid], nx_graph: nx.Graph, **kwargs):
154
156
  graph_obj = nx.readwrite.json_graph.node_link_graph(nx_graph)
155
157
  return cls(qubits, graph_obj)
@@ -11,8 +11,11 @@
11
11
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
+
14
15
  """Metadata subtype for 2D Homogenous devices."""
15
16
 
17
+ from __future__ import annotations
18
+
16
19
  from typing import cast, FrozenSet, Iterable, Mapping, Optional, Tuple, TYPE_CHECKING
17
20
 
18
21
  import networkx as nx
@@ -30,11 +33,11 @@ class GridDeviceMetadata(device.DeviceMetadata):
30
33
 
31
34
  def __init__(
32
35
  self,
33
- qubit_pairs: Iterable[Tuple['cirq.GridQubit', 'cirq.GridQubit']],
34
- gateset: 'cirq.Gateset',
35
- gate_durations: Optional[Mapping['cirq.GateFamily', 'cirq.Duration']] = None,
36
- all_qubits: Optional[Iterable['cirq.GridQubit']] = None,
37
- compilation_target_gatesets: Iterable['cirq.CompilationTargetGateset'] = (),
36
+ qubit_pairs: Iterable[Tuple[cirq.GridQubit, cirq.GridQubit]],
37
+ gateset: cirq.Gateset,
38
+ gate_durations: Optional[Mapping[cirq.GateFamily, cirq.Duration]] = None,
39
+ all_qubits: Optional[Iterable[cirq.GridQubit]] = None,
40
+ compilation_target_gatesets: Iterable[cirq.CompilationTargetGateset] = (),
38
41
  ):
39
42
  """Create a GridDeviceMetadata object.
40
43
 
@@ -115,7 +118,7 @@ class GridDeviceMetadata(device.DeviceMetadata):
115
118
  self._gate_durations = gate_durations
116
119
 
117
120
  @property
118
- def qubit_set(self) -> FrozenSet['cirq.GridQubit']:
121
+ def qubit_set(self) -> FrozenSet[cirq.GridQubit]:
119
122
  """Returns the set of grid qubits on the device.
120
123
 
121
124
  Returns:
@@ -124,7 +127,7 @@ class GridDeviceMetadata(device.DeviceMetadata):
124
127
  return cast(FrozenSet['cirq.GridQubit'], super().qubit_set)
125
128
 
126
129
  @property
127
- def qubit_pairs(self) -> FrozenSet[FrozenSet['cirq.GridQubit']]:
130
+ def qubit_pairs(self) -> FrozenSet[FrozenSet[cirq.GridQubit]]:
128
131
  """Returns the set of all couple-able qubits on the device.
129
132
 
130
133
  Each element in the outer frozenset is a 2-element frozenset representing a bidirectional
@@ -133,22 +136,22 @@ class GridDeviceMetadata(device.DeviceMetadata):
133
136
  return self._qubit_pairs
134
137
 
135
138
  @property
136
- def isolated_qubits(self) -> FrozenSet['cirq.GridQubit']:
139
+ def isolated_qubits(self) -> FrozenSet[cirq.GridQubit]:
137
140
  """Returns the set of all isolated qubits on the device (if applicable)."""
138
141
  return self._isolated_qubits
139
142
 
140
143
  @property
141
- def gateset(self) -> 'cirq.Gateset':
144
+ def gateset(self) -> cirq.Gateset:
142
145
  """Returns the `cirq.Gateset` of supported gates on this device."""
143
146
  return self._gateset
144
147
 
145
148
  @property
146
- def compilation_target_gatesets(self) -> Tuple['cirq.CompilationTargetGateset', ...]:
149
+ def compilation_target_gatesets(self) -> Tuple[cirq.CompilationTargetGateset, ...]:
147
150
  """Returns a sequence of valid `cirq.CompilationTargetGateset`s for this device."""
148
151
  return self._compilation_target_gatesets
149
152
 
150
153
  @property
151
- def gate_durations(self) -> Optional[Mapping['cirq.GateFamily', 'cirq.Duration']]:
154
+ def gate_durations(self) -> Optional[Mapping[cirq.GateFamily, cirq.Duration]]:
152
155
  """Get a dictionary mapping from gate family to duration for gates.
153
156
 
154
157
  To look up the duration of a specific gate instance / gate type / operation which is part of
@@ -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
  import functools
17
19
  import weakref
@@ -104,17 +106,17 @@ class _BaseGridQid(ops.Qid):
104
106
  def dimension(self) -> int:
105
107
  return self._dimension
106
108
 
107
- def with_dimension(self, dimension: int) -> 'GridQid':
109
+ def with_dimension(self, dimension: int) -> GridQid:
108
110
  return GridQid(self._row, self._col, dimension=dimension)
109
111
 
110
- def is_adjacent(self, other: 'cirq.Qid') -> bool:
112
+ def is_adjacent(self, other: cirq.Qid) -> bool:
111
113
  """Determines if two qubits are adjacent qubits."""
112
114
  return (
113
115
  isinstance(other, GridQubit)
114
116
  and abs(self._row - other._row) + abs(self._col - other._col) == 1
115
117
  )
116
118
 
117
- def neighbors(self, qids: Optional[Iterable[ops.Qid]] = None) -> Set['_BaseGridQid']:
119
+ def neighbors(self, qids: Optional[Iterable[ops.Qid]] = None) -> Set[_BaseGridQid]:
118
120
  """Returns qubits that are potential neighbors to this GridQid
119
121
 
120
122
  Args:
@@ -204,7 +206,7 @@ class GridQid(_BaseGridQid):
204
206
  # Holds weak references so instances can still be garbage collected.
205
207
  _cache = weakref.WeakValueDictionary[Tuple[int, int, int], 'cirq.GridQid']()
206
208
 
207
- def __new__(cls, row: int, col: int, *, dimension: int) -> 'cirq.GridQid':
209
+ def __new__(cls, row: int, col: int, *, dimension: int) -> cirq.GridQid:
208
210
  """Creates a grid qid at the given row, col coordinate
209
211
 
210
212
  Args:
@@ -234,11 +236,11 @@ class GridQid(_BaseGridQid):
234
236
  def __getstate__(self) -> Dict[str, Any]:
235
237
  return {}
236
238
 
237
- def _with_row_col(self, row: int, col: int) -> 'GridQid':
239
+ def _with_row_col(self, row: int, col: int) -> GridQid:
238
240
  return GridQid(row, col, dimension=self._dimension)
239
241
 
240
242
  @staticmethod
241
- def square(diameter: int, top: int = 0, left: int = 0, *, dimension: int) -> List['GridQid']:
243
+ def square(diameter: int, top: int = 0, left: int = 0, *, dimension: int) -> List[GridQid]:
242
244
  """Returns a square of GridQid.
243
245
 
244
246
  Args:
@@ -254,9 +256,7 @@ class GridQid(_BaseGridQid):
254
256
  return GridQid.rect(diameter, diameter, top=top, left=left, dimension=dimension)
255
257
 
256
258
  @staticmethod
257
- def rect(
258
- rows: int, cols: int, top: int = 0, left: int = 0, *, dimension: int
259
- ) -> List['GridQid']:
259
+ def rect(rows: int, cols: int, top: int = 0, left: int = 0, *, dimension: int) -> List[GridQid]:
260
260
  """Returns a rectangle of GridQid.
261
261
 
262
262
  Args:
@@ -277,7 +277,7 @@ class GridQid(_BaseGridQid):
277
277
  ]
278
278
 
279
279
  @staticmethod
280
- def from_diagram(diagram: str, dimension: int) -> List['GridQid']:
280
+ def from_diagram(diagram: str, dimension: int) -> List[GridQid]:
281
281
  """Parse ASCII art device layout into a device.
282
282
 
283
283
  As an example, the below diagram will create a list of GridQid in a
@@ -337,9 +337,7 @@ class GridQid(_BaseGridQid):
337
337
  def __str__(self) -> str:
338
338
  return f"q({self._row}, {self._col}) (d={self._dimension})"
339
339
 
340
- def _circuit_diagram_info_(
341
- self, args: 'cirq.CircuitDiagramInfoArgs'
342
- ) -> 'cirq.CircuitDiagramInfo':
340
+ def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> cirq.CircuitDiagramInfo:
343
341
  return protocols.CircuitDiagramInfo(
344
342
  wire_symbols=(f"({self._row}, {self._col}) (d={self._dimension})",)
345
343
  )
@@ -371,7 +369,7 @@ class GridQubit(_BaseGridQid):
371
369
  # Holds weak references so instances can still be garbage collected.
372
370
  _cache = weakref.WeakValueDictionary[Tuple[int, int], 'cirq.GridQubit']()
373
371
 
374
- def __new__(cls, row: int, col: int) -> 'cirq.GridQubit':
372
+ def __new__(cls, row: int, col: int) -> cirq.GridQubit:
375
373
  """Creates a grid qubit at the given row, col coordinate
376
374
 
377
375
  Args:
@@ -396,11 +394,11 @@ class GridQubit(_BaseGridQid):
396
394
  def __getstate__(self) -> Dict[str, Any]:
397
395
  return {}
398
396
 
399
- def _with_row_col(self, row: int, col: int) -> 'GridQubit':
397
+ def _with_row_col(self, row: int, col: int) -> GridQubit:
400
398
  return GridQubit(row, col)
401
399
 
402
400
  @staticmethod
403
- def square(diameter: int, top: int = 0, left: int = 0) -> List['GridQubit']:
401
+ def square(diameter: int, top: int = 0, left: int = 0) -> List[GridQubit]:
404
402
  """Returns a square of GridQubits.
405
403
 
406
404
  Args:
@@ -414,7 +412,7 @@ class GridQubit(_BaseGridQid):
414
412
  return GridQubit.rect(diameter, diameter, top=top, left=left)
415
413
 
416
414
  @staticmethod
417
- def rect(rows: int, cols: int, top: int = 0, left: int = 0) -> List['GridQubit']:
415
+ def rect(rows: int, cols: int, top: int = 0, left: int = 0) -> List[GridQubit]:
418
416
  """Returns a rectangle of GridQubits.
419
417
 
420
418
  Args:
@@ -433,7 +431,7 @@ class GridQubit(_BaseGridQid):
433
431
  ]
434
432
 
435
433
  @staticmethod
436
- def from_diagram(diagram: str) -> List['GridQubit']:
434
+ def from_diagram(diagram: str) -> List[GridQubit]:
437
435
  """Parse ASCII art into device layout info.
438
436
 
439
437
  As an example, the below diagram will create a list of
@@ -490,9 +488,7 @@ class GridQubit(_BaseGridQid):
490
488
  def __str__(self) -> str:
491
489
  return f"q({self._row}, {self._col})"
492
490
 
493
- def _circuit_diagram_info_(
494
- self, args: 'cirq.CircuitDiagramInfoArgs'
495
- ) -> 'cirq.CircuitDiagramInfo':
491
+ def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> cirq.CircuitDiagramInfo:
496
492
  return protocols.CircuitDiagramInfo(wire_symbols=(f"({self._row}, {self._col})",))
497
493
 
498
494
  def _json_dict_(self) -> Dict[str, Any]:
@@ -58,7 +58,7 @@ def test_grid_qid_pickled_hash():
58
58
  _test_qid_pickled_hash(q, q_bad)
59
59
 
60
60
 
61
- def _test_qid_pickled_hash(q: 'cirq.Qid', q_bad: 'cirq.Qid') -> None:
61
+ def _test_qid_pickled_hash(q: cirq.Qid, q_bad: cirq.Qid) -> None:
62
62
  """Test that hashes are not pickled with Qid instances."""
63
63
  assert q_bad is not q
64
64
  _ = hash(q_bad) # compute hash to ensure it is cached.
@@ -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 dataclasses
16
18
  from typing import Any, Dict, List, Optional, Sequence, TYPE_CHECKING
17
19
 
@@ -42,16 +44,14 @@ class InsertionNoiseModel(devices.NoiseModel):
42
44
  with PHYSICAL_GATE_TAG.
43
45
  """
44
46
 
45
- ops_added: Dict[noise_utils.OpIdentifier, 'cirq.Operation'] = dataclasses.field(
47
+ ops_added: Dict[noise_utils.OpIdentifier, cirq.Operation] = dataclasses.field(
46
48
  default_factory=dict
47
49
  )
48
50
  prepend: bool = False
49
51
  require_physical_tag: bool = True
50
52
 
51
- def noisy_moment(
52
- self, moment: 'cirq.Moment', system_qubits: Sequence['cirq.Qid']
53
- ) -> 'cirq.OP_TREE':
54
- noise_ops: List['cirq.Operation'] = []
53
+ def noisy_moment(self, moment: cirq.Moment, system_qubits: Sequence[cirq.Qid]) -> cirq.OP_TREE:
54
+ noise_ops: List[cirq.Operation] = []
55
55
  candidate_ops = [
56
56
  op
57
57
  for op in moment
@@ -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
  import functools
17
19
  import weakref
@@ -93,10 +95,10 @@ class _BaseLineQid(ops.Qid):
93
95
  def dimension(self) -> int:
94
96
  return self._dimension
95
97
 
96
- def with_dimension(self, dimension: int) -> 'LineQid':
98
+ def with_dimension(self, dimension: int) -> LineQid:
97
99
  return LineQid(self._x, dimension)
98
100
 
99
- def is_adjacent(self, other: 'cirq.Qid') -> bool:
101
+ def is_adjacent(self, other: cirq.Qid) -> bool:
100
102
  """Determines if two qubits are adjacent line qubits.
101
103
 
102
104
  Args:
@@ -106,7 +108,7 @@ class _BaseLineQid(ops.Qid):
106
108
  """
107
109
  return isinstance(other, _BaseLineQid) and abs(self._x - other._x) == 1
108
110
 
109
- def neighbors(self, qids: Optional[Iterable[ops.Qid]] = None) -> Set['_BaseLineQid']:
111
+ def neighbors(self, qids: Optional[Iterable[ops.Qid]] = None) -> Set[_BaseLineQid]:
110
112
  """Returns qubits that are potential neighbors to this LineQubit
111
113
 
112
114
  Args:
@@ -184,7 +186,7 @@ class LineQid(_BaseLineQid):
184
186
  # Holds weak references so instances can still be garbage collected.
185
187
  _cache = weakref.WeakValueDictionary[Tuple[int, int], 'cirq.LineQid']()
186
188
 
187
- def __new__(cls, x: int, dimension: int) -> 'cirq.LineQid':
189
+ def __new__(cls, x: int, dimension: int) -> cirq.LineQid:
188
190
  """Initializes a line qid at the given x coordinate.
189
191
 
190
192
  Args:
@@ -212,11 +214,11 @@ class LineQid(_BaseLineQid):
212
214
  def __getstate__(self) -> Dict[str, Any]:
213
215
  return {}
214
216
 
215
- def _with_x(self, x: int) -> 'LineQid':
217
+ def _with_x(self, x: int) -> LineQid:
216
218
  return LineQid(x, dimension=self._dimension)
217
219
 
218
220
  @staticmethod
219
- def range(*range_args, dimension: int) -> List['LineQid']:
221
+ def range(*range_args, dimension: int) -> List[LineQid]:
220
222
  """Returns a range of line qids.
221
223
 
222
224
  Args:
@@ -230,7 +232,7 @@ class LineQid(_BaseLineQid):
230
232
  return [LineQid(i, dimension=dimension) for i in range(*range_args)]
231
233
 
232
234
  @staticmethod
233
- def for_qid_shape(qid_shape: Sequence[int], start: int = 0, step: int = 1) -> List['LineQid']:
235
+ def for_qid_shape(qid_shape: Sequence[int], start: int = 0, step: int = 1) -> List[LineQid]:
234
236
  """Returns a range of line qids for each entry in `qid_shape` with
235
237
  matching dimension.
236
238
 
@@ -244,7 +246,7 @@ class LineQid(_BaseLineQid):
244
246
  ]
245
247
 
246
248
  @staticmethod
247
- def for_gate(val: Any, start: int = 0, step: int = 1) -> List['LineQid']:
249
+ def for_gate(val: Any, start: int = 0, step: int = 1) -> List[LineQid]:
248
250
  """Returns a range of line qids with the same qid shape as the gate.
249
251
 
250
252
  Args:
@@ -264,9 +266,7 @@ class LineQid(_BaseLineQid):
264
266
  def __str__(self) -> str:
265
267
  return f"q({self._x}) (d={self._dimension})"
266
268
 
267
- def _circuit_diagram_info_(
268
- self, args: 'cirq.CircuitDiagramInfoArgs'
269
- ) -> 'cirq.CircuitDiagramInfo':
269
+ def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> cirq.CircuitDiagramInfo:
270
270
  return protocols.CircuitDiagramInfo(wire_symbols=(f"{self._x} (d={self._dimension})",))
271
271
 
272
272
  def _json_dict_(self) -> Dict[str, Any]:
@@ -296,7 +296,7 @@ class LineQubit(_BaseLineQid):
296
296
  # Holds weak references so instances can still be garbage collected.
297
297
  _cache = weakref.WeakValueDictionary[int, 'cirq.LineQubit']()
298
298
 
299
- def __new__(cls, x: int) -> 'cirq.LineQubit':
299
+ def __new__(cls, x: int) -> cirq.LineQubit:
300
300
  """Initializes a line qid at the given x coordinate.
301
301
 
302
302
  Args:
@@ -318,11 +318,11 @@ class LineQubit(_BaseLineQid):
318
318
  def __getstate__(self) -> Dict[str, Any]:
319
319
  return {}
320
320
 
321
- def _with_x(self, x: int) -> 'LineQubit':
321
+ def _with_x(self, x: int) -> LineQubit:
322
322
  return LineQubit(x)
323
323
 
324
324
  @staticmethod
325
- def range(*range_args) -> List['LineQubit']:
325
+ def range(*range_args) -> List[LineQubit]:
326
326
  """Returns a range of line qubits.
327
327
 
328
328
  Args:
@@ -339,9 +339,7 @@ class LineQubit(_BaseLineQid):
339
339
  def __str__(self) -> str:
340
340
  return f"q({self._x})"
341
341
 
342
- def _circuit_diagram_info_(
343
- self, args: 'cirq.CircuitDiagramInfoArgs'
344
- ) -> 'cirq.CircuitDiagramInfo':
342
+ def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> cirq.CircuitDiagramInfo:
345
343
  return protocols.CircuitDiagramInfo(wire_symbols=(f"{self._x}",))
346
344
 
347
345
  def _json_dict_(self) -> Dict[str, Any]:
@@ -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
  import warnings
17
19
  from dataclasses import dataclass
@@ -127,7 +129,7 @@ class LineTopology(NamedTopology):
127
129
  )
128
130
  object.__setattr__(self, 'graph', graph)
129
131
 
130
- def nodes_as_linequbits(self) -> List['cirq.LineQubit']:
132
+ def nodes_as_linequbits(self) -> List[cirq.LineQubit]:
131
133
  """Get the graph nodes as cirq.LineQubit"""
132
134
  return [LineQubit(x) for x in sorted(self.graph.nodes)]
133
135
 
@@ -142,7 +144,7 @@ class LineTopology(NamedTopology):
142
144
  g2 = nx.relabel_nodes(self.graph, {n: (n, 1) for n in self.graph.nodes})
143
145
  return draw_gridlike(g2, ax=ax, tilted=tilted, **kwargs)
144
146
 
145
- def nodes_to_linequbits(self, offset: int = 0) -> Dict[int, 'cirq.LineQubit']:
147
+ def nodes_to_linequbits(self, offset: int = 0) -> Dict[int, cirq.LineQubit]:
146
148
  """Return a mapping from graph nodes to `cirq.LineQubit`
147
149
 
148
150
  Args:
@@ -240,11 +242,11 @@ class TiltedSquareLattice(NamedTopology):
240
242
  """
241
243
  return draw_gridlike(self.graph, ax=ax, tilted=tilted, **kwargs)
242
244
 
243
- def nodes_as_gridqubits(self) -> List['cirq.GridQubit']:
245
+ def nodes_as_gridqubits(self) -> List[cirq.GridQubit]:
244
246
  """Get the graph nodes as cirq.GridQubit"""
245
247
  return [GridQubit(r, c) for r, c in sorted(self.graph.nodes)]
246
248
 
247
- def nodes_to_gridqubits(self, offset=(0, 0)) -> Dict[Tuple[int, int], 'cirq.GridQubit']:
249
+ def nodes_to_gridqubits(self, offset=(0, 0)) -> Dict[Tuple[int, int], cirq.GridQubit]:
248
250
  """Return a mapping from graph nodes to `cirq.GridQubit`
249
251
 
250
252
  Args: