cirq-core 1.6.0.dev20250520054601__py3-none-any.whl → 1.6.0.dev20250520181654__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 (289) hide show
  1. cirq/_compat.py +15 -17
  2. cirq/_compat_test.py +6 -9
  3. cirq/_doc.py +2 -2
  4. cirq/_import.py +6 -6
  5. cirq/_version.py +1 -1
  6. cirq/_version_test.py +1 -1
  7. cirq/circuits/_block_diagram_drawer.py +9 -10
  8. cirq/circuits/_box_drawing_character_data.py +6 -8
  9. cirq/circuits/_bucket_priority_queue.py +7 -7
  10. cirq/circuits/circuit.py +118 -125
  11. cirq/circuits/circuit_operation.py +38 -52
  12. cirq/circuits/circuit_test.py +4 -4
  13. cirq/circuits/frozen_circuit.py +13 -23
  14. cirq/circuits/moment.py +23 -29
  15. cirq/circuits/optimization_pass.py +4 -4
  16. cirq/circuits/optimization_pass_test.py +4 -6
  17. cirq/circuits/qasm_output.py +11 -11
  18. cirq/circuits/text_diagram_drawer.py +21 -36
  19. cirq/contrib/acquaintance/bipartite.py +5 -8
  20. cirq/contrib/acquaintance/executor.py +5 -5
  21. cirq/contrib/acquaintance/executor_test.py +3 -3
  22. cirq/contrib/acquaintance/gates.py +16 -26
  23. cirq/contrib/acquaintance/gates_test.py +3 -3
  24. cirq/contrib/acquaintance/mutation_utils.py +4 -4
  25. cirq/contrib/acquaintance/optimizers.py +4 -4
  26. cirq/contrib/acquaintance/permutation.py +15 -27
  27. cirq/contrib/acquaintance/shift.py +3 -3
  28. cirq/contrib/acquaintance/shift_swap_network.py +4 -4
  29. cirq/contrib/acquaintance/strategies/cubic.py +2 -2
  30. cirq/contrib/acquaintance/strategies/quartic_paired.py +6 -6
  31. cirq/contrib/bayesian_network/bayesian_network_gate.py +9 -10
  32. cirq/contrib/circuitdag/circuit_dag.py +2 -2
  33. cirq/contrib/custom_simulators/custom_state_simulator.py +3 -3
  34. cirq/contrib/custom_simulators/custom_state_simulator_test.py +4 -4
  35. cirq/contrib/graph_device/graph_device.py +5 -5
  36. cirq/contrib/graph_device/hypergraph.py +12 -12
  37. cirq/contrib/graph_device/uniform_graph_device.py +4 -4
  38. cirq/contrib/paulistring/clifford_optimize.py +2 -2
  39. cirq/contrib/paulistring/clifford_target_gateset.py +7 -7
  40. cirq/contrib/paulistring/pauli_string_measurement_with_readout_mitigation.py +31 -31
  41. cirq/contrib/paulistring/pauli_string_measurement_with_readout_mitigation_test.py +23 -23
  42. cirq/contrib/paulistring/recombine.py +3 -3
  43. cirq/contrib/paulistring/separate.py +2 -2
  44. cirq/contrib/qasm_import/_parser.py +20 -32
  45. cirq/contrib/qcircuit/qcircuit_diagram_info.py +3 -5
  46. cirq/contrib/quantum_volume/quantum_volume.py +24 -24
  47. cirq/contrib/quimb/density_matrix.py +12 -14
  48. cirq/contrib/quimb/mps_simulator.py +20 -20
  49. cirq/contrib/quimb/state_vector.py +6 -10
  50. cirq/contrib/quirk/export_to_quirk.py +3 -3
  51. cirq/contrib/quirk/quirk_gate.py +15 -15
  52. cirq/contrib/routing/device.py +3 -3
  53. cirq/contrib/routing/greedy.py +10 -21
  54. cirq/contrib/routing/initialization.py +2 -2
  55. cirq/contrib/routing/swap_network.py +3 -3
  56. cirq/contrib/routing/utils.py +2 -2
  57. cirq/contrib/shuffle_circuits/shuffle_circuits_with_readout_benchmarking.py +8 -8
  58. cirq/contrib/svg/svg.py +3 -3
  59. cirq/devices/grid_device_metadata.py +10 -10
  60. cirq/devices/grid_qubit.py +20 -20
  61. cirq/devices/insertion_noise_model.py +5 -5
  62. cirq/devices/line_qubit.py +13 -13
  63. cirq/devices/named_topologies.py +18 -29
  64. cirq/devices/noise_model.py +3 -3
  65. cirq/devices/noise_properties.py +2 -2
  66. cirq/devices/noise_properties_test.py +1 -3
  67. cirq/devices/noise_utils.py +7 -7
  68. cirq/devices/superconducting_qubits_noise_properties.py +21 -21
  69. cirq/devices/superconducting_qubits_noise_properties_test.py +5 -7
  70. cirq/devices/thermal_noise_model.py +14 -14
  71. cirq/devices/unconstrained_device.py +2 -2
  72. cirq/experiments/benchmarking/parallel_xeb.py +29 -31
  73. cirq/experiments/n_qubit_tomography.py +5 -7
  74. cirq/experiments/qubit_characterizations.py +29 -40
  75. cirq/experiments/qubit_characterizations_test.py +1 -1
  76. cirq/experiments/random_quantum_circuit_generation.py +19 -33
  77. cirq/experiments/random_quantum_circuit_generation_test.py +6 -6
  78. cirq/experiments/readout_confusion_matrix.py +14 -14
  79. cirq/experiments/single_qubit_readout_calibration.py +12 -12
  80. cirq/experiments/t2_decay_experiment.py +7 -7
  81. cirq/experiments/two_qubit_xeb.py +32 -32
  82. cirq/experiments/two_qubit_xeb_test.py +5 -5
  83. cirq/experiments/xeb_fitting.py +25 -25
  84. cirq/experiments/xeb_sampling.py +22 -33
  85. cirq/experiments/xeb_simulation.py +5 -5
  86. cirq/experiments/xeb_simulation_test.py +3 -3
  87. cirq/experiments/z_phase_calibration.py +19 -19
  88. cirq/interop/quirk/cells/arithmetic_cells.py +23 -36
  89. cirq/interop/quirk/cells/cell.py +9 -21
  90. cirq/interop/quirk/cells/composite_cell.py +7 -22
  91. cirq/interop/quirk/cells/control_cells.py +8 -8
  92. cirq/interop/quirk/cells/input_cells.py +4 -4
  93. cirq/interop/quirk/cells/input_rotation_cells.py +5 -5
  94. cirq/interop/quirk/cells/parse.py +20 -23
  95. cirq/interop/quirk/cells/qubit_permutation_cells.py +3 -3
  96. cirq/interop/quirk/cells/swap_cell.py +3 -3
  97. cirq/interop/quirk/cells/testing.py +5 -7
  98. cirq/interop/quirk/url_to_circuit.py +17 -33
  99. cirq/json_resolver_cache.py +6 -6
  100. cirq/linalg/decompositions.py +20 -31
  101. cirq/linalg/diagonalize.py +4 -4
  102. cirq/linalg/diagonalize_test.py +3 -4
  103. cirq/linalg/operator_spaces.py +5 -5
  104. cirq/linalg/predicates.py +7 -7
  105. cirq/linalg/transformations.py +20 -20
  106. cirq/ops/arithmetic_operation.py +13 -15
  107. cirq/ops/boolean_hamiltonian.py +17 -17
  108. cirq/ops/classically_controlled_operation.py +13 -25
  109. cirq/ops/clifford_gate.py +31 -35
  110. cirq/ops/clifford_gate_test.py +2 -3
  111. cirq/ops/common_channels.py +30 -32
  112. cirq/ops/common_gates.py +64 -74
  113. cirq/ops/control_values.py +12 -12
  114. cirq/ops/controlled_gate.py +15 -30
  115. cirq/ops/controlled_gate_test.py +5 -5
  116. cirq/ops/controlled_operation.py +12 -25
  117. cirq/ops/controlled_operation_test.py +5 -5
  118. cirq/ops/dense_pauli_string.py +23 -34
  119. cirq/ops/dense_pauli_string_test.py +1 -2
  120. cirq/ops/diagonal_gate.py +9 -20
  121. cirq/ops/diagonal_gate_test.py +1 -3
  122. cirq/ops/eigen_gate.py +11 -23
  123. cirq/ops/eigen_gate_test.py +6 -8
  124. cirq/ops/fourier_transform.py +5 -5
  125. cirq/ops/fsim_gate.py +14 -14
  126. cirq/ops/gate_operation.py +23 -44
  127. cirq/ops/gateset.py +23 -37
  128. cirq/ops/gateset_test.py +2 -2
  129. cirq/ops/global_phase_op.py +8 -10
  130. cirq/ops/greedy_qubit_manager.py +6 -6
  131. cirq/ops/identity.py +9 -9
  132. cirq/ops/kraus_channel.py +7 -7
  133. cirq/ops/linear_combinations.py +29 -48
  134. cirq/ops/matrix_gates.py +8 -8
  135. cirq/ops/measure_util.py +13 -14
  136. cirq/ops/measurement_gate.py +18 -29
  137. cirq/ops/mixed_unitary_channel.py +8 -8
  138. cirq/ops/named_qubit.py +10 -10
  139. cirq/ops/op_tree.py +7 -7
  140. cirq/ops/parallel_gate.py +5 -5
  141. cirq/ops/parity_gates.py +14 -14
  142. cirq/ops/pauli_gates.py +8 -10
  143. cirq/ops/pauli_interaction_gate.py +6 -6
  144. cirq/ops/pauli_measurement_gate.py +11 -23
  145. cirq/ops/pauli_string.py +35 -52
  146. cirq/ops/pauli_string_phasor.py +4 -14
  147. cirq/ops/pauli_string_raw_types.py +3 -3
  148. cirq/ops/pauli_sum_exponential.py +2 -2
  149. cirq/ops/permutation_gate.py +4 -4
  150. cirq/ops/phased_iswap_gate.py +9 -9
  151. cirq/ops/phased_x_gate.py +10 -10
  152. cirq/ops/phased_x_z_gate.py +11 -11
  153. cirq/ops/projector.py +6 -6
  154. cirq/ops/qubit_manager.py +6 -6
  155. cirq/ops/qubit_order.py +3 -3
  156. cirq/ops/random_gate_channel.py +4 -4
  157. cirq/ops/raw_types.py +48 -70
  158. cirq/ops/state_preparation_channel.py +3 -3
  159. cirq/ops/swap_gates.py +9 -9
  160. cirq/ops/tags.py +2 -4
  161. cirq/ops/three_qubit_gates.py +20 -38
  162. cirq/ops/two_qubit_diagonal_gate.py +5 -5
  163. cirq/ops/uniform_superposition_gate.py +2 -2
  164. cirq/ops/wait_gate.py +5 -5
  165. cirq/protocols/act_on_protocol_test.py +3 -3
  166. cirq/protocols/apply_channel_protocol.py +8 -14
  167. cirq/protocols/apply_mixture_protocol.py +14 -16
  168. cirq/protocols/apply_mixture_protocol_test.py +5 -6
  169. cirq/protocols/apply_unitary_protocol.py +17 -19
  170. cirq/protocols/circuit_diagram_info_protocol.py +19 -30
  171. cirq/protocols/decompose_protocol.py +30 -34
  172. cirq/protocols/inverse_protocol.py +7 -7
  173. cirq/protocols/json_serialization.py +32 -51
  174. cirq/protocols/json_serialization_test.py +9 -10
  175. cirq/protocols/kraus_protocol.py +4 -4
  176. cirq/protocols/kraus_protocol_test.py +3 -3
  177. cirq/protocols/measurement_key_protocol.py +11 -13
  178. cirq/protocols/mixture_protocol.py +4 -4
  179. cirq/protocols/qasm.py +11 -13
  180. cirq/protocols/qid_shape_protocol.py +6 -8
  181. cirq/qis/clifford_tableau.py +12 -12
  182. cirq/qis/measures.py +7 -7
  183. cirq/qis/quantum_state_representation.py +3 -3
  184. cirq/qis/states.py +51 -51
  185. cirq/sim/classical_simulator.py +10 -10
  186. cirq/sim/clifford/clifford_simulator.py +6 -6
  187. cirq/sim/clifford/clifford_tableau_simulation_state_test.py +1 -3
  188. cirq/sim/clifford/stabilizer_sampler.py +4 -4
  189. cirq/sim/clifford/stabilizer_state_ch_form.py +3 -3
  190. cirq/sim/density_matrix_simulation_state.py +15 -15
  191. cirq/sim/density_matrix_simulator.py +11 -11
  192. cirq/sim/density_matrix_utils.py +9 -9
  193. cirq/sim/mux.py +9 -9
  194. cirq/sim/simulation_product_state.py +9 -9
  195. cirq/sim/simulation_product_state_test.py +2 -2
  196. cirq/sim/simulation_state.py +14 -27
  197. cirq/sim/simulation_state_base.py +8 -24
  198. cirq/sim/simulation_utils.py +3 -4
  199. cirq/sim/simulator.py +28 -43
  200. cirq/sim/simulator_base.py +12 -25
  201. cirq/sim/simulator_base_test.py +6 -6
  202. cirq/sim/simulator_test.py +7 -7
  203. cirq/sim/sparse_simulator.py +8 -8
  204. cirq/sim/state_vector.py +8 -8
  205. cirq/sim/state_vector_simulation_state.py +17 -17
  206. cirq/sim/state_vector_simulator.py +4 -4
  207. cirq/study/flatten_expressions.py +12 -14
  208. cirq/study/resolver.py +9 -11
  209. cirq/study/result.py +11 -24
  210. cirq/study/sweepable.py +5 -5
  211. cirq/study/sweeps.py +27 -40
  212. cirq/testing/circuit_compare.py +5 -5
  213. cirq/testing/consistent_controlled_gate_op_test.py +7 -11
  214. cirq/testing/consistent_protocols.py +10 -10
  215. cirq/testing/consistent_protocols_test.py +7 -7
  216. cirq/testing/consistent_qasm.py +4 -4
  217. cirq/testing/consistent_qasm_test.py +2 -3
  218. cirq/testing/devices.py +4 -5
  219. cirq/testing/equals_tester.py +2 -2
  220. cirq/testing/equivalent_basis_map.py +4 -4
  221. cirq/testing/equivalent_repr_eval.py +3 -3
  222. cirq/testing/json.py +14 -14
  223. cirq/testing/logs.py +3 -3
  224. cirq/testing/no_identifier_qubit.py +2 -3
  225. cirq/testing/random_circuit.py +7 -7
  226. cirq/testing/random_circuit_test.py +3 -3
  227. cirq/transformers/analytical_decompositions/clifford_decomposition.py +16 -16
  228. cirq/transformers/analytical_decompositions/controlled_gate_decomposition.py +13 -13
  229. cirq/transformers/analytical_decompositions/cphase_to_fsim.py +5 -5
  230. cirq/transformers/analytical_decompositions/cphase_to_fsim_test.py +3 -3
  231. cirq/transformers/analytical_decompositions/pauli_string_decomposition.py +3 -3
  232. cirq/transformers/analytical_decompositions/quantum_shannon_decomposition.py +4 -4
  233. cirq/transformers/analytical_decompositions/single_qubit_decompositions.py +6 -7
  234. cirq/transformers/analytical_decompositions/single_to_two_qubit_isometry.py +2 -2
  235. cirq/transformers/analytical_decompositions/three_qubit_decomposition.py +7 -7
  236. cirq/transformers/analytical_decompositions/two_qubit_state_preparation.py +4 -4
  237. cirq/transformers/analytical_decompositions/two_qubit_to_cz.py +7 -7
  238. cirq/transformers/analytical_decompositions/two_qubit_to_fsim.py +11 -11
  239. cirq/transformers/analytical_decompositions/two_qubit_to_ms.py +5 -5
  240. cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py +14 -14
  241. cirq/transformers/dynamical_decoupling.py +13 -13
  242. cirq/transformers/dynamical_decoupling_test.py +4 -4
  243. cirq/transformers/eject_phased_paulis.py +16 -16
  244. cirq/transformers/eject_z.py +5 -7
  245. cirq/transformers/gauge_compiling/gauge_compiling.py +38 -38
  246. cirq/transformers/gauge_compiling/sqrt_cz_gauge.py +2 -2
  247. cirq/transformers/heuristic_decompositions/two_qubit_gate_tabulation.py +8 -8
  248. cirq/transformers/insertion_sort.py +5 -5
  249. cirq/transformers/measurement_transformers.py +14 -14
  250. cirq/transformers/merge_k_qubit_gates_test.py +1 -3
  251. cirq/transformers/merge_single_qubit_gates_test.py +1 -3
  252. cirq/transformers/qubit_management_transformers.py +5 -5
  253. cirq/transformers/routing/initial_mapper.py +4 -4
  254. cirq/transformers/routing/line_initial_mapper.py +9 -9
  255. cirq/transformers/routing/mapping_manager.py +7 -7
  256. cirq/transformers/routing/route_circuit_cqc.py +27 -27
  257. cirq/transformers/routing/visualize_routed_circuit.py +4 -4
  258. cirq/transformers/stratify.py +8 -8
  259. cirq/transformers/synchronize_terminal_measurements.py +6 -6
  260. cirq/transformers/target_gatesets/compilation_target_gateset.py +8 -8
  261. cirq/transformers/target_gatesets/compilation_target_gateset_test.py +2 -2
  262. cirq/transformers/target_gatesets/cz_gateset.py +4 -4
  263. cirq/transformers/target_gatesets/sqrt_iswap_gateset.py +5 -5
  264. cirq/transformers/transformer_api.py +11 -26
  265. cirq/transformers/transformer_primitives.py +24 -36
  266. cirq/transformers/transformer_primitives_test.py +3 -3
  267. cirq/value/classical_data.py +18 -18
  268. cirq/value/condition.py +8 -8
  269. cirq/value/digits.py +7 -7
  270. cirq/value/duration.py +12 -12
  271. cirq/value/linear_dict.py +8 -12
  272. cirq/value/measurement_key.py +8 -8
  273. cirq/value/product_state.py +9 -9
  274. cirq/value/value_equality_attr.py +4 -4
  275. cirq/vis/heatmap.py +23 -35
  276. cirq/work/collector.py +9 -17
  277. cirq/work/observable_grouping.py +4 -7
  278. cirq/work/observable_measurement.py +29 -41
  279. cirq/work/observable_measurement_data.py +14 -14
  280. cirq/work/observable_measurement_test.py +2 -2
  281. cirq/work/observable_settings.py +9 -10
  282. cirq/work/pauli_sum_collector.py +5 -5
  283. cirq/work/sampler.py +17 -17
  284. cirq/work/zeros_sampler.py +3 -3
  285. {cirq_core-1.6.0.dev20250520054601.dist-info → cirq_core-1.6.0.dev20250520181654.dist-info}/METADATA +1 -1
  286. {cirq_core-1.6.0.dev20250520054601.dist-info → cirq_core-1.6.0.dev20250520181654.dist-info}/RECORD +289 -289
  287. {cirq_core-1.6.0.dev20250520054601.dist-info → cirq_core-1.6.0.dev20250520181654.dist-info}/WHEEL +1 -1
  288. {cirq_core-1.6.0.dev20250520054601.dist-info → cirq_core-1.6.0.dev20250520181654.dist-info}/licenses/LICENSE +0 -0
  289. {cirq_core-1.6.0.dev20250520054601.dist-info → cirq_core-1.6.0.dev20250520181654.dist-info}/top_level.txt +0 -0
cirq/value/linear_dict.py CHANGED
@@ -20,7 +20,6 @@ from typing import (
20
20
  AbstractSet,
21
21
  Any,
22
22
  Callable,
23
- Dict,
24
23
  Generic,
25
24
  ItemsView,
26
25
  Iterable,
@@ -28,12 +27,9 @@ from typing import (
28
27
  KeysView,
29
28
  Mapping,
30
29
  MutableMapping,
31
- Optional,
32
30
  overload,
33
- Tuple,
34
31
  TYPE_CHECKING,
35
32
  TypeVar,
36
- Union,
37
33
  ValuesView,
38
34
  )
39
35
 
@@ -46,7 +42,7 @@ from cirq import protocols
46
42
  if TYPE_CHECKING:
47
43
  import cirq
48
44
 
49
- Scalar = Union[complex, np.number]
45
+ Scalar = complex | np.number
50
46
  TVector = TypeVar('TVector')
51
47
 
52
48
  TDefault = TypeVar('TDefault')
@@ -95,7 +91,7 @@ def _format_term(format_spec: str, vector: TVector, coefficient: cirq.TParamValC
95
91
  return '+' + result
96
92
 
97
93
 
98
- def _format_terms(terms: Iterable[Tuple[TVector, cirq.TParamValComplex]], format_spec: str):
94
+ def _format_terms(terms: Iterable[tuple[TVector, cirq.TParamValComplex]], format_spec: str):
99
95
  formatted_terms = [_format_term(format_spec, vector, coeff) for vector, coeff in terms]
100
96
  s = ''.join(formatted_terms)
101
97
  if not s:
@@ -122,8 +118,8 @@ class LinearDict(Generic[TVector], MutableMapping[TVector, 'cirq.TParamValComple
122
118
 
123
119
  def __init__(
124
120
  self,
125
- terms: Optional[Mapping[TVector, cirq.TParamValComplex]] = None,
126
- validator: Optional[Callable[[TVector], bool]] = None,
121
+ terms: Mapping[TVector, cirq.TParamValComplex] | None = None,
122
+ validator: Callable[[TVector], bool] | None = None,
127
123
  ) -> None:
128
124
  """Initializes linear combination from a collection of terms.
129
125
 
@@ -138,7 +134,7 @@ class LinearDict(Generic[TVector], MutableMapping[TVector, 'cirq.TParamValComple
138
134
  """
139
135
  self._has_validator = validator is not None
140
136
  self._is_valid = validator or (lambda x: True)
141
- self._terms: Dict[TVector, cirq.TParamValComplex] = {}
137
+ self._terms: dict[TVector, cirq.TParamValComplex] = {}
142
138
  if terms is not None:
143
139
  self.update(terms)
144
140
 
@@ -192,7 +188,7 @@ class LinearDict(Generic[TVector], MutableMapping[TVector, 'cirq.TParamValComple
192
188
  @overload
193
189
  def update(
194
190
  self,
195
- other: Iterable[Tuple[TVector, cirq.TParamValComplex]],
191
+ other: Iterable[tuple[TVector, cirq.TParamValComplex]],
196
192
  **kwargs: cirq.TParamValComplex,
197
193
  ) -> None:
198
194
  pass
@@ -217,7 +213,7 @@ class LinearDict(Generic[TVector], MutableMapping[TVector, 'cirq.TParamValComple
217
213
  pass
218
214
 
219
215
  @overload
220
- def get(self, vector: TVector, default: TDefault) -> Union[cirq.TParamValComplex, TDefault]:
216
+ def get(self, vector: TVector, default: TDefault) -> cirq.TParamValComplex | TDefault:
221
217
  pass
222
218
 
223
219
  def get(self, vector, default=0):
@@ -354,7 +350,7 @@ class LinearDict(Generic[TVector], MutableMapping[TVector, 'cirq.TParamValComple
354
350
  else:
355
351
  p.text(str(self))
356
352
 
357
- def _json_dict_(self) -> Dict[Any, Any]:
353
+ def _json_dict_(self) -> dict[Any, Any]:
358
354
  if self._has_validator:
359
355
  raise ValueError('LinearDict with a validator is not json serializable.')
360
356
  return {
@@ -15,7 +15,7 @@
15
15
  from __future__ import annotations
16
16
 
17
17
  import dataclasses
18
- from typing import Any, Dict, FrozenSet, Mapping, Optional, Tuple
18
+ from typing import Any, Mapping
19
19
 
20
20
  MEASUREMENT_KEY_SEPARATOR = ':'
21
21
 
@@ -35,11 +35,11 @@ class MeasurementKey:
35
35
  appears first in the tuple.
36
36
  """
37
37
 
38
- _hash: Optional[int] = dataclasses.field(default=None, init=False)
39
- _str: Optional[str] = dataclasses.field(default=None, init=False)
38
+ _hash: int | None = dataclasses.field(default=None, init=False)
39
+ _str: str | None = dataclasses.field(default=None, init=False)
40
40
 
41
41
  name: str
42
- path: Tuple[str, ...] = dataclasses.field(default_factory=tuple)
42
+ path: tuple[str, ...] = dataclasses.field(default_factory=tuple)
43
43
 
44
44
  def __post_init__(self):
45
45
  if not isinstance(self.name, str):
@@ -78,7 +78,7 @@ class MeasurementKey:
78
78
  object.__setattr__(self, '_hash', hash(str(self)))
79
79
  return self._hash
80
80
 
81
- def __getstate__(self) -> Dict[str, Any]:
81
+ def __getstate__(self) -> dict[str, Any]:
82
82
  # clear cached hash value when pickling, see #6674
83
83
  state = self.__dict__
84
84
  if "_hash" in state:
@@ -112,10 +112,10 @@ class MeasurementKey:
112
112
  components = key_str.split(MEASUREMENT_KEY_SEPARATOR)
113
113
  return MeasurementKey(name=components[-1], path=tuple(components[:-1]))
114
114
 
115
- def _with_key_path_(self, path: Tuple[str, ...]):
115
+ def _with_key_path_(self, path: tuple[str, ...]):
116
116
  return self.replace(path=path)
117
117
 
118
- def _with_key_path_prefix_(self, prefix: Tuple[str, ...]):
118
+ def _with_key_path_prefix_(self, prefix: tuple[str, ...]):
119
119
  return self._with_key_path_(path=prefix + self.path)
120
120
 
121
121
  def with_key_path_prefix(self, *path_component: str):
@@ -126,7 +126,7 @@ class MeasurementKey:
126
126
  """
127
127
  return self.replace(path=path_component + self.path)
128
128
 
129
- def _with_rescoped_keys_(self, path: Tuple[str, ...], bindable_keys: FrozenSet[MeasurementKey]):
129
+ def _with_rescoped_keys_(self, path: tuple[str, ...], bindable_keys: frozenset[MeasurementKey]):
130
130
  return self.replace(path=path + self.path)
131
131
 
132
132
  def _with_measurement_key_mapping_(self, key_map: Mapping[str, str]):
@@ -16,7 +16,7 @@ from __future__ import annotations
16
16
 
17
17
  import abc
18
18
  from dataclasses import dataclass
19
- from typing import Dict, Iterator, Optional, Sequence, Tuple, TYPE_CHECKING
19
+ from typing import Iterator, Sequence, TYPE_CHECKING
20
20
 
21
21
  import numpy as np
22
22
 
@@ -59,7 +59,7 @@ class ProductState:
59
59
  with `cirq.KET_PLUS(q0)`.
60
60
  """
61
61
 
62
- states: Dict[cirq.Qid, _NamedOneQubitState]
62
+ states: dict[cirq.Qid, _NamedOneQubitState]
63
63
 
64
64
  def __init__(self, states=None):
65
65
  if states is None:
@@ -99,7 +99,7 @@ class ProductState:
99
99
  """Return the _NamedOneQubitState at the given qubit."""
100
100
  return self.states[qubit]
101
101
 
102
- def __iter__(self) -> Iterator[Tuple[cirq.Qid, _NamedOneQubitState]]:
102
+ def __iter__(self) -> Iterator[tuple[cirq.Qid, _NamedOneQubitState]]:
103
103
  yield from self.states.items()
104
104
 
105
105
  def __len__(self) -> int:
@@ -121,7 +121,7 @@ class ProductState:
121
121
  def _from_json_dict_(cls, states, **kwargs):
122
122
  return cls(states=dict(states))
123
123
 
124
- def state_vector(self, qubit_order: Optional[cirq.QubitOrder] = None) -> np.ndarray:
124
+ def state_vector(self, qubit_order: cirq.QubitOrder | None = None) -> np.ndarray:
125
125
  """The state-vector representation of this state."""
126
126
  from cirq import ops
127
127
 
@@ -138,7 +138,7 @@ class ProductState:
138
138
 
139
139
  return mat
140
140
 
141
- def projector(self, qubit_order: Optional[cirq.QubitOrder] = None) -> np.ndarray:
141
+ def projector(self, qubit_order: cirq.QubitOrder | None = None) -> np.ndarray:
142
142
  """The projector associated with this state expressed as a matrix.
143
143
 
144
144
  This is |s⟩⟨s| where |s⟩ is this state.
@@ -176,7 +176,7 @@ class _PauliEigenState(_NamedOneQubitState):
176
176
  return f'cirq.{self._symbol}.basis[{self.eigenvalue:+d}]'
177
177
 
178
178
  @abc.abstractmethod
179
- def stabilized_by(self) -> Tuple[int, cirq.Pauli]:
179
+ def stabilized_by(self) -> tuple[int, cirq.Pauli]:
180
180
  pass
181
181
 
182
182
  def __eq__(self, other) -> bool:
@@ -203,7 +203,7 @@ class _XEigenState(_PauliEigenState):
203
203
  return np.array([1, -1]) / np.sqrt(2)
204
204
  raise ValueError(f"Bad eigenvalue: {self.eigenvalue}") # pragma: no cover
205
205
 
206
- def stabilized_by(self) -> Tuple[int, cirq.Pauli]:
206
+ def stabilized_by(self) -> tuple[int, cirq.Pauli]:
207
207
  # Prevent circular import from `value.value_equality`
208
208
  from cirq import ops
209
209
 
@@ -220,7 +220,7 @@ class _YEigenState(_PauliEigenState):
220
220
  return np.array([1, -1j]) / np.sqrt(2)
221
221
  raise ValueError(f"Bad eigenvalue: {self.eigenvalue}") # pragma: no cover
222
222
 
223
- def stabilized_by(self) -> Tuple[int, cirq.Pauli]:
223
+ def stabilized_by(self) -> tuple[int, cirq.Pauli]:
224
224
  from cirq import ops
225
225
 
226
226
  return self.eigenvalue, ops.Y
@@ -236,7 +236,7 @@ class _ZEigenState(_PauliEigenState):
236
236
  return np.array([0, 1])
237
237
  raise ValueError(f"Bad eigenvalue: {self.eigenvalue}") # pragma: no cover
238
238
 
239
- def stabilized_by(self) -> Tuple[int, cirq.Pauli]:
239
+ def stabilized_by(self) -> tuple[int, cirq.Pauli]:
240
240
  from cirq import ops
241
241
 
242
242
  return self.eigenvalue, ops.Z
@@ -16,7 +16,7 @@
16
16
 
17
17
  from __future__ import annotations
18
18
 
19
- from typing import Any, Callable, Dict, Optional, overload, Union
19
+ from typing import Any, Callable, overload
20
20
 
21
21
  from typing_extensions import Protocol
22
22
 
@@ -113,7 +113,7 @@ def _value_equality_approx_eq(
113
113
  )
114
114
 
115
115
 
116
- def _value_equality_getstate(self: _SupportsValueEquality) -> Dict[str, Any]:
116
+ def _value_equality_getstate(self: _SupportsValueEquality) -> dict[str, Any]:
117
117
  # clear cached hash value when pickling, see #6674
118
118
  state = self.__dict__
119
119
  hash_attr = _compat._method_cache_name(self.__hash__)
@@ -148,13 +148,13 @@ def value_equality(
148
148
 
149
149
 
150
150
  def value_equality(
151
- cls: Optional[type] = None,
151
+ cls: type | None = None,
152
152
  *,
153
153
  unhashable: bool = False,
154
154
  distinct_child_types: bool = False,
155
155
  manual_cls: bool = False,
156
156
  approximate: bool = False,
157
- ) -> Union[Callable[[type], type], type]:
157
+ ) -> Callable[[type], type] | type:
158
158
  """Implements __eq__/__ne__/__hash__ via a _value_equality_values_ method.
159
159
 
160
160
  _value_equality_values_ is a method that the decorated class must implement.
cirq/vis/heatmap.py CHANGED
@@ -16,19 +16,7 @@ from __future__ import annotations
16
16
 
17
17
  import copy
18
18
  from dataclasses import astuple, dataclass
19
- from typing import (
20
- Any,
21
- cast,
22
- Dict,
23
- List,
24
- Mapping,
25
- Optional,
26
- overload,
27
- Sequence,
28
- SupportsFloat,
29
- Tuple,
30
- Union,
31
- )
19
+ from typing import Any, cast, Mapping, overload, Sequence, SupportsFloat
32
20
 
33
21
  import matplotlib as mpl
34
22
  import matplotlib.collections as mpl_collections
@@ -39,9 +27,9 @@ from mpl_toolkits import axes_grid1
39
27
  from cirq.devices import grid_qubit
40
28
  from cirq.vis import vis_utils
41
29
 
42
- QubitTuple = Tuple[grid_qubit.GridQubit, ...]
30
+ QubitTuple = tuple[grid_qubit.GridQubit, ...]
43
31
 
44
- Polygon = Sequence[Tuple[float, float]]
32
+ Polygon = Sequence[tuple[float, float]]
45
33
 
46
34
 
47
35
  @dataclass
@@ -71,7 +59,7 @@ class PolygonUnit:
71
59
  polygon: Polygon
72
60
  value: float
73
61
  center: Point
74
- annot: Optional[str]
62
+ annot: str | None
75
63
 
76
64
 
77
65
  class Heatmap:
@@ -88,9 +76,9 @@ class Heatmap:
88
76
 
89
77
  def __init__(
90
78
  self,
91
- value_map: Union[
92
- Mapping[QubitTuple, SupportsFloat], Mapping[grid_qubit.GridQubit, SupportsFloat]
93
- ],
79
+ value_map: (
80
+ Mapping[QubitTuple, SupportsFloat] | Mapping[grid_qubit.GridQubit, SupportsFloat]
81
+ ),
94
82
  **kwargs,
95
83
  ):
96
84
  """2D qubit grid Heatmaps
@@ -131,7 +119,7 @@ class Heatmap:
131
119
  }
132
120
  self._validate_kwargs(kwargs)
133
121
  if '_config' not in self.__dict__:
134
- self._config: Dict[str, Any] = {}
122
+ self._config: dict[str, Any] = {}
135
123
  self._config.update(
136
124
  {
137
125
  "plot_colorbar": True,
@@ -144,7 +132,7 @@ class Heatmap:
144
132
  )
145
133
  self._config.update(kwargs)
146
134
 
147
- def _extra_valid_kwargs(self) -> List[str]:
135
+ def _extra_valid_kwargs(self) -> list[str]:
148
136
  return []
149
137
 
150
138
  def _validate_kwargs(self, kwargs) -> None:
@@ -179,7 +167,7 @@ class Heatmap:
179
167
  self._config.update(kwargs)
180
168
  return self
181
169
 
182
- def _qubits_to_polygon(self, qubits: QubitTuple) -> Tuple[Polygon, Point]:
170
+ def _qubits_to_polygon(self, qubits: QubitTuple) -> tuple[Polygon, Point]:
183
171
  qubit = qubits[0]
184
172
  x, y = float(qubit.row), float(qubit.col)
185
173
  return (
@@ -187,7 +175,7 @@ class Heatmap:
187
175
  Point(y, x),
188
176
  )
189
177
 
190
- def _get_annotation_value(self, key, value) -> Optional[str]:
178
+ def _get_annotation_value(self, key, value) -> str | None:
191
179
  if self._config.get('annotation_map'):
192
180
  return self._config['annotation_map'].get(key)
193
181
  elif self._config.get('annotation_format'):
@@ -198,8 +186,8 @@ class Heatmap:
198
186
  else:
199
187
  return None
200
188
 
201
- def _get_polygon_units(self) -> List[PolygonUnit]:
202
- polygon_unit_list: List[PolygonUnit] = []
189
+ def _get_polygon_units(self) -> list[PolygonUnit]:
190
+ polygon_unit_list: list[PolygonUnit] = []
203
191
  for qubits, value in sorted(self._value_map.items()):
204
192
  polygon, center = self._qubits_to_polygon(qubits)
205
193
  polygon_unit_list.append(
@@ -231,7 +219,7 @@ class Heatmap:
231
219
 
232
220
  def _write_annotations(
233
221
  self,
234
- centers_and_annot: List[Tuple[Point, Optional[str]]],
222
+ centers_and_annot: list[tuple[Point, str | None]],
235
223
  collection: mpl_collections.Collection,
236
224
  ax: plt.Axes,
237
225
  ) -> None:
@@ -245,7 +233,7 @@ class Heatmap:
245
233
  x, y = center
246
234
  face_luminance = vis_utils.relative_luminance(facecolor)
247
235
  text_color = 'black' if face_luminance > 0.4 else 'white'
248
- text_kwargs: Dict[str, Any] = dict(color=text_color, ha="center", va="center")
236
+ text_kwargs: dict[str, Any] = dict(color=text_color, ha="center", va="center")
249
237
  text_kwargs.update(self._config.get('annotation_text_kwargs', {}))
250
238
  ax.text(x, y, annotation, **text_kwargs)
251
239
 
@@ -286,8 +274,8 @@ class Heatmap:
286
274
  return collection
287
275
 
288
276
  def plot(
289
- self, ax: Optional[plt.Axes] = None, **kwargs: Any
290
- ) -> Tuple[plt.Axes, mpl_collections.Collection]:
277
+ self, ax: plt.Axes | None = None, **kwargs: Any
278
+ ) -> tuple[plt.Axes, mpl_collections.Collection]:
291
279
  """Plots the heatmap on the given Axes.
292
280
  Args:
293
281
  ax: the Axes to plot on. If not given, a new figure is created,
@@ -358,13 +346,13 @@ class TwoQubitInteractionHeatmap(Heatmap):
358
346
  coupler_margin: float, default = 0.03
359
347
  coupler_width: float, default = 0.6
360
348
  """
361
- self._config: Dict[str, Any] = {"coupler_margin": 0.03, "coupler_width": 0.6}
349
+ self._config: dict[str, Any] = {"coupler_margin": 0.03, "coupler_width": 0.6}
362
350
  super().__init__(value_map, **kwargs)
363
351
 
364
- def _extra_valid_kwargs(self) -> List[str]:
352
+ def _extra_valid_kwargs(self) -> list[str]:
365
353
  return ["coupler_margin", "coupler_width"]
366
354
 
367
- def _qubits_to_polygon(self, qubits: QubitTuple) -> Tuple[Polygon, Point]:
355
+ def _qubits_to_polygon(self, qubits: QubitTuple) -> tuple[Polygon, Point]:
368
356
  coupler_margin = self._config["coupler_margin"]
369
357
  coupler_width = self._config["coupler_width"]
370
358
  cwidth = coupler_width / 2.0
@@ -403,8 +391,8 @@ class TwoQubitInteractionHeatmap(Heatmap):
403
391
  return (polygon, Point((col1 + col2) / 2.0, (row1 + row2) / 2.0))
404
392
 
405
393
  def plot(
406
- self, ax: Optional[plt.Axes] = None, **kwargs: Any
407
- ) -> Tuple[plt.Axes, mpl_collections.Collection]:
394
+ self, ax: plt.Axes | None = None, **kwargs: Any
395
+ ) -> tuple[plt.Axes, mpl_collections.Collection]:
408
396
  """Plots the heatmap on the given Axes.
409
397
  Args:
410
398
  ax: the Axes to plot on. If not given, a new figure is created,
@@ -422,7 +410,7 @@ class TwoQubitInteractionHeatmap(Heatmap):
422
410
  original_config = copy.deepcopy(self._config)
423
411
  self.update_config(**kwargs)
424
412
  qubits = set([q for qubits in self._value_map.keys() for q in qubits])
425
- collection_options: Dict[str, Any] = {"cmap": "binary"}
413
+ collection_options: dict[str, Any] = {"cmap": "binary"}
426
414
  highlighted_qubits = frozenset(kwargs.get("highlighted_qubits", ()))
427
415
  if not highlighted_qubits:
428
416
  collection_options.update(
cirq/work/collector.py CHANGED
@@ -15,7 +15,7 @@
15
15
  from __future__ import annotations
16
16
 
17
17
  import abc
18
- from typing import Any, Iterator, List, Optional, Tuple, TYPE_CHECKING, Union
18
+ from typing import Any, Iterator, TYPE_CHECKING
19
19
 
20
20
  import duet
21
21
  import numpy as np
@@ -59,11 +59,11 @@ class CircuitSampleJob:
59
59
 
60
60
 
61
61
  class CircuitSampleJobTree(Protocol):
62
- def __iter__(self) -> Iterator[Union[CircuitSampleJob, CircuitSampleJobTree]]:
62
+ def __iter__(self) -> Iterator[CircuitSampleJob | CircuitSampleJobTree]:
63
63
  pass
64
64
 
65
65
 
66
- CIRCUIT_SAMPLE_JOB_TREE = Union[CircuitSampleJob, CircuitSampleJobTree]
66
+ CIRCUIT_SAMPLE_JOB_TREE = CircuitSampleJob | CircuitSampleJobTree
67
67
 
68
68
 
69
69
  class Collector(metaclass=abc.ABCMeta):
@@ -77,7 +77,7 @@ class Collector(metaclass=abc.ABCMeta):
77
77
  """
78
78
 
79
79
  @abc.abstractmethod
80
- def next_job(self) -> Optional[CIRCUIT_SAMPLE_JOB_TREE]:
80
+ def next_job(self) -> CIRCUIT_SAMPLE_JOB_TREE | None:
81
81
  """Determines what to sample next.
82
82
 
83
83
  This method is called by driving code when more samples can be
@@ -107,11 +107,7 @@ class Collector(metaclass=abc.ABCMeta):
107
107
  """
108
108
 
109
109
  def collect(
110
- self,
111
- sampler: cirq.Sampler,
112
- *,
113
- concurrency: int = 2,
114
- max_total_samples: Optional[int] = None,
110
+ self, sampler: cirq.Sampler, *, concurrency: int = 2, max_total_samples: int | None = None
115
111
  ) -> None:
116
112
  """Collects needed samples from a sampler.
117
113
 
@@ -142,11 +138,7 @@ class Collector(metaclass=abc.ABCMeta):
142
138
  )
143
139
 
144
140
  async def collect_async(
145
- self,
146
- sampler: cirq.Sampler,
147
- *,
148
- concurrency: int = 2,
149
- max_total_samples: Optional[int] = None,
141
+ self, sampler: cirq.Sampler, *, concurrency: int = 2, max_total_samples: int | None = None
150
142
  ) -> None:
151
143
  """Asynchronously collects needed samples from a sampler.
152
144
 
@@ -169,10 +161,10 @@ class Collector(metaclass=abc.ABCMeta):
169
161
  The collector's result after all desired samples have been
170
162
  collected.
171
163
  """
172
- results: duet.AsyncCollector[Tuple[CircuitSampleJob, cirq.Result]] = duet.AsyncCollector()
164
+ results: duet.AsyncCollector[tuple[CircuitSampleJob, cirq.Result]] = duet.AsyncCollector()
173
165
  job_error = None
174
166
  running_jobs = 0
175
- queued_jobs: List[CircuitSampleJob] = []
167
+ queued_jobs: list[CircuitSampleJob] = []
176
168
  remaining_samples = np.inf if max_total_samples is None else max_total_samples
177
169
 
178
170
  async def run_job(job):
@@ -215,7 +207,7 @@ class Collector(metaclass=abc.ABCMeta):
215
207
  self.on_job_result(job, result)
216
208
 
217
209
 
218
- def _flatten_jobs(tree: Optional[CIRCUIT_SAMPLE_JOB_TREE]) -> Iterator[CircuitSampleJob]:
210
+ def _flatten_jobs(tree: CIRCUIT_SAMPLE_JOB_TREE | None) -> Iterator[CircuitSampleJob]:
219
211
  if isinstance(tree, CircuitSampleJob):
220
212
  yield tree
221
213
  elif tree is not None:
@@ -14,20 +14,17 @@
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
- from typing import Callable, cast, Dict, Iterable, List, TYPE_CHECKING
17
+ from typing import Callable, cast, Iterable
18
18
 
19
19
  from cirq import ops, value
20
20
  from cirq.work.observable_settings import _max_weight_observable, _max_weight_state, InitObsSetting
21
21
 
22
- if TYPE_CHECKING:
23
- pass
24
-
25
- GROUPER_T = Callable[[Iterable[InitObsSetting]], Dict[InitObsSetting, List[InitObsSetting]]]
22
+ GROUPER_T = Callable[[Iterable[InitObsSetting]], dict[InitObsSetting, list[InitObsSetting]]]
26
23
 
27
24
 
28
25
  def group_settings_greedy(
29
26
  settings: Iterable[InitObsSetting],
30
- ) -> Dict[InitObsSetting, List[InitObsSetting]]:
27
+ ) -> dict[InitObsSetting, list[InitObsSetting]]:
31
28
  """Greedily group settings which can be simultaneously measured.
32
29
 
33
30
  We construct a dictionary keyed by `max_setting` (see docstrings
@@ -48,7 +45,7 @@ def group_settings_greedy(
48
45
  input list of settings. Each dictionary value is a list of
49
46
  settings compatible with `max_setting`.
50
47
  """
51
- grouped_settings: Dict[InitObsSetting, List[InitObsSetting]] = {}
48
+ grouped_settings: dict[InitObsSetting, list[InitObsSetting]] = {}
52
49
  for setting in settings:
53
50
  for max_setting, simul_settings in grouped_settings.items():
54
51
  trial_grouped_settings = simul_settings + [setting]