cirq-core 1.7.0.dev20250825174419__py3-none-any.whl → 1.7.0.dev20251203004401__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.
Files changed (426) hide show
  1. cirq/__init__.py +1 -0
  2. cirq/_compat.py +3 -2
  3. cirq/_compat_test.py +16 -15
  4. cirq/_doc.py +4 -3
  5. cirq/_import.py +2 -1
  6. cirq/_version.py +1 -1
  7. cirq/_version_test.py +1 -1
  8. cirq/circuits/_bucket_priority_queue.py +2 -1
  9. cirq/circuits/circuit.py +19 -17
  10. cirq/circuits/circuit_operation.py +2 -1
  11. cirq/circuits/circuit_operation_test.py +19 -0
  12. cirq/circuits/circuit_test.py +31 -12
  13. cirq/circuits/frozen_circuit.py +3 -2
  14. cirq/circuits/moment.py +3 -15
  15. cirq/circuits/optimization_pass.py +2 -1
  16. cirq/circuits/qasm_output.py +39 -10
  17. cirq/circuits/qasm_output_test.py +51 -2
  18. cirq/circuits/text_diagram_drawer.py +2 -1
  19. cirq/contrib/acquaintance/bipartite.py +2 -1
  20. cirq/contrib/acquaintance/devices.py +1 -1
  21. cirq/contrib/acquaintance/executor.py +4 -5
  22. cirq/contrib/acquaintance/executor_test.py +2 -1
  23. cirq/contrib/acquaintance/gates.py +2 -1
  24. cirq/contrib/acquaintance/gates_test.py +1 -1
  25. cirq/contrib/acquaintance/inspection_utils.py +2 -1
  26. cirq/contrib/acquaintance/mutation_utils.py +2 -1
  27. cirq/contrib/acquaintance/optimizers.py +2 -1
  28. cirq/contrib/acquaintance/permutation.py +2 -1
  29. cirq/contrib/acquaintance/permutation_test.py +1 -1
  30. cirq/contrib/acquaintance/shift.py +2 -1
  31. cirq/contrib/acquaintance/shift_swap_network.py +2 -1
  32. cirq/contrib/acquaintance/strategies/complete.py +3 -2
  33. cirq/contrib/acquaintance/strategies/cubic.py +2 -1
  34. cirq/contrib/acquaintance/strategies/quartic_paired.py +2 -1
  35. cirq/contrib/acquaintance/strategies/quartic_paired_test.py +1 -1
  36. cirq/contrib/acquaintance/testing.py +2 -1
  37. cirq/contrib/acquaintance/topological_sort.py +2 -1
  38. cirq/contrib/bayesian_network/bayesian_network_gate.py +3 -2
  39. cirq/contrib/circuitdag/circuit_dag.py +4 -2
  40. cirq/contrib/custom_simulators/custom_state_simulator.py +2 -1
  41. cirq/contrib/custom_simulators/custom_state_simulator_test.py +1 -1
  42. cirq/contrib/graph_device/graph_device.py +2 -1
  43. cirq/contrib/graph_device/graph_device_test.py +2 -1
  44. cirq/contrib/graph_device/hypergraph.py +2 -1
  45. cirq/contrib/graph_device/uniform_graph_device.py +2 -1
  46. cirq/contrib/json.py +14 -2
  47. cirq/contrib/json_test_data/BayesianNetworkGate.json +10 -0
  48. cirq/contrib/json_test_data/BayesianNetworkGate.repr +3 -0
  49. cirq/contrib/json_test_data/QuantumVolumeResult.json +169 -0
  50. cirq/contrib/json_test_data/QuantumVolumeResult.repr +22 -0
  51. cirq/contrib/json_test_data/SwapPermutationGate.json +3 -0
  52. cirq/contrib/json_test_data/SwapPermutationGate.repr +1 -0
  53. cirq/contrib/json_test_data/spec.py +0 -2
  54. cirq/contrib/noise_models/noise_models.py +2 -1
  55. cirq/contrib/paulistring/clifford_optimize.py +20 -2
  56. cirq/contrib/paulistring/optimize.py +1 -1
  57. cirq/contrib/paulistring/pauli_string_measurement_with_readout_mitigation.py +146 -35
  58. cirq/contrib/paulistring/pauli_string_measurement_with_readout_mitigation_test.py +81 -178
  59. cirq/contrib/paulistring/recombine.py +5 -2
  60. cirq/contrib/paulistring/separate.py +1 -1
  61. cirq/contrib/qasm_import/_lexer.py +6 -1
  62. cirq/contrib/qasm_import/_lexer_test.py +1 -1
  63. cirq/contrib/qasm_import/_parser.py +24 -8
  64. cirq/contrib/qasm_import/_parser_test.py +44 -6
  65. cirq/contrib/qcircuit/qcircuit_pdf_test.py +6 -9
  66. cirq/contrib/quantikz/__init__.py +21 -0
  67. cirq/contrib/quantikz/circuit_to_latex_quantikz.py +680 -0
  68. cirq/contrib/quantikz/circuit_to_latex_quantikz_test.py +253 -0
  69. cirq/contrib/quantikz/circuit_to_latex_render.py +424 -0
  70. cirq/contrib/quantikz/circuit_to_latex_render_test.py +44 -0
  71. cirq/contrib/quantum_volume/quantum_volume.py +2 -1
  72. cirq/contrib/quimb/density_matrix.py +1 -1
  73. cirq/contrib/quimb/grid_circuits.py +2 -1
  74. cirq/contrib/quimb/grid_circuits_test.py +1 -1
  75. cirq/contrib/quimb/mps_simulator.py +4 -3
  76. cirq/contrib/quimb/state_vector.py +2 -1
  77. cirq/contrib/quirk/export_to_quirk.py +2 -1
  78. cirq/contrib/quirk/linearize_circuit.py +1 -1
  79. cirq/contrib/quirk/quirk_gate.py +2 -1
  80. cirq/contrib/routing/device.py +1 -1
  81. cirq/contrib/routing/greedy.py +2 -1
  82. cirq/contrib/routing/initialization.py +2 -1
  83. cirq/contrib/routing/router.py +2 -1
  84. cirq/contrib/routing/swap_network.py +2 -1
  85. cirq/contrib/routing/utils.py +2 -1
  86. cirq/contrib/shuffle_circuits/shuffle_circuits_with_readout_benchmarking.py +7 -5
  87. cirq/contrib/shuffle_circuits/shuffle_circuits_with_readout_benchmarking_test.py +6 -6
  88. cirq/devices/device.py +2 -1
  89. cirq/devices/grid_device_metadata.py +2 -1
  90. cirq/devices/grid_qubit.py +7 -6
  91. cirq/devices/insertion_noise_model.py +2 -1
  92. cirq/devices/line_qubit.py +2 -1
  93. cirq/devices/named_topologies.py +2 -1
  94. cirq/devices/noise_model.py +2 -1
  95. cirq/devices/noise_model_test.py +1 -1
  96. cirq/devices/noise_properties.py +2 -1
  97. cirq/devices/superconducting_qubits_noise_properties_test.py +2 -1
  98. cirq/devices/thermal_noise_model.py +2 -1
  99. cirq/experiments/__init__.py +2 -0
  100. cirq/experiments/benchmarking/parallel_xeb.py +2 -1
  101. cirq/experiments/benchmarking/parallel_xeb_test.py +1 -1
  102. cirq/experiments/fidelity_estimation.py +2 -1
  103. cirq/experiments/fidelity_estimation_test.py +1 -1
  104. cirq/experiments/ghz_2d.py +150 -0
  105. cirq/experiments/ghz_2d_test.py +155 -0
  106. cirq/experiments/n_qubit_tomography.py +2 -1
  107. cirq/experiments/n_qubit_tomography_test.py +1 -1
  108. cirq/experiments/purity_estimation.py +1 -1
  109. cirq/experiments/qubit_characterizations.py +33 -4
  110. cirq/experiments/qubit_characterizations_test.py +16 -0
  111. cirq/experiments/random_quantum_circuit_generation.py +2 -1
  112. cirq/experiments/random_quantum_circuit_generation_test.py +2 -1
  113. cirq/experiments/readout_confusion_matrix.py +2 -1
  114. cirq/experiments/readout_confusion_matrix_test.py +1 -1
  115. cirq/experiments/single_qubit_readout_calibration.py +2 -1
  116. cirq/experiments/single_qubit_readout_calibration_test.py +1 -1
  117. cirq/experiments/t1_decay_experiment.py +2 -1
  118. cirq/experiments/two_qubit_xeb.py +2 -1
  119. cirq/experiments/two_qubit_xeb_test.py +1 -1
  120. cirq/experiments/xeb_fitting.py +2 -1
  121. cirq/experiments/xeb_fitting_test.py +1 -1
  122. cirq/experiments/xeb_sampling.py +5 -3
  123. cirq/experiments/xeb_sampling_test.py +1 -1
  124. cirq/experiments/xeb_simulation.py +2 -1
  125. cirq/experiments/xeb_simulation_test.py +2 -1
  126. cirq/experiments/z_phase_calibration.py +2 -1
  127. cirq/experiments/z_phase_calibration_test.py +18 -3
  128. cirq/interop/quirk/cells/__init__.py +1 -2
  129. cirq/interop/quirk/cells/all_cells.py +2 -1
  130. cirq/interop/quirk/cells/arithmetic_cells.py +2 -1
  131. cirq/interop/quirk/cells/cell.py +2 -1
  132. cirq/interop/quirk/cells/composite_cell.py +2 -1
  133. cirq/interop/quirk/cells/composite_cell_test.py +1 -1
  134. cirq/interop/quirk/cells/control_cells.py +2 -1
  135. cirq/interop/quirk/cells/frequency_space_cells.py +1 -1
  136. cirq/interop/quirk/cells/ignored_cells.py +1 -1
  137. cirq/interop/quirk/cells/input_cells.py +2 -1
  138. cirq/interop/quirk/cells/input_rotation_cells.py +2 -1
  139. cirq/interop/quirk/cells/measurement_cells.py +2 -1
  140. cirq/interop/quirk/cells/parse.py +2 -11
  141. cirq/interop/quirk/cells/qubit_permutation_cells.py +2 -1
  142. cirq/interop/quirk/cells/scalar_cells.py +2 -1
  143. cirq/interop/quirk/cells/single_qubit_rotation_cells.py +2 -1
  144. cirq/interop/quirk/cells/swap_cell.py +2 -1
  145. cirq/interop/quirk/cells/unsupported_cells.py +1 -1
  146. cirq/interop/quirk/url_to_circuit.py +2 -1
  147. cirq/json_resolver_cache.py +0 -2
  148. cirq/linalg/decompositions.py +6 -2
  149. cirq/linalg/decompositions_test.py +1 -0
  150. cirq/linalg/diagonalize.py +1 -1
  151. cirq/linalg/predicates.py +2 -1
  152. cirq/linalg/tolerance.py +2 -1
  153. cirq/linalg/transformations.py +3 -2
  154. cirq/ops/arithmetic_operation.py +4 -3
  155. cirq/ops/arithmetic_operation_test.py +1 -1
  156. cirq/ops/boolean_hamiltonian.py +4 -3
  157. cirq/ops/classically_controlled_operation.py +11 -11
  158. cirq/ops/classically_controlled_operation_test.py +26 -2
  159. cirq/ops/clifford_gate.py +3 -2
  160. cirq/ops/clifford_gate_test.py +1 -2
  161. cirq/ops/common_channels.py +2 -1
  162. cirq/ops/common_gates.py +3 -2
  163. cirq/ops/control_values.py +2 -1
  164. cirq/ops/controlled_gate.py +3 -2
  165. cirq/ops/controlled_gate_test.py +2 -1
  166. cirq/ops/controlled_operation.py +3 -2
  167. cirq/ops/controlled_operation_test.py +2 -1
  168. cirq/ops/dense_pauli_string.py +44 -81
  169. cirq/ops/dense_pauli_string_test.py +21 -0
  170. cirq/ops/diagonal_gate.py +3 -2
  171. cirq/ops/eigen_gate.py +9 -7
  172. cirq/ops/fourier_transform.py +3 -2
  173. cirq/ops/fourier_transform_test.py +2 -4
  174. cirq/ops/fsim_gate.py +3 -2
  175. cirq/ops/gate_operation.py +23 -12
  176. cirq/ops/gateset.py +22 -2
  177. cirq/ops/global_phase_op.py +3 -2
  178. cirq/ops/greedy_qubit_manager.py +2 -1
  179. cirq/ops/identity.py +2 -1
  180. cirq/ops/kraus_channel.py +2 -1
  181. cirq/ops/linear_combinations.py +12 -17
  182. cirq/ops/linear_combinations_test.py +23 -1
  183. cirq/ops/matrix_gates.py +2 -1
  184. cirq/ops/measure_util.py +8 -6
  185. cirq/ops/measurement_gate.py +2 -1
  186. cirq/ops/mixed_unitary_channel.py +2 -1
  187. cirq/ops/named_qubit.py +2 -2
  188. cirq/ops/op_tree.py +2 -1
  189. cirq/ops/parallel_gate.py +3 -2
  190. cirq/ops/parity_gates.py +2 -1
  191. cirq/ops/parity_gates_test.py +35 -0
  192. cirq/ops/pauli_interaction_gate.py +2 -1
  193. cirq/ops/pauli_measurement_gate.py +2 -1
  194. cirq/ops/pauli_string.py +37 -57
  195. cirq/ops/pauli_string_phasor.py +6 -5
  196. cirq/ops/pauli_string_raw_types.py +2 -1
  197. cirq/ops/pauli_string_test.py +49 -6
  198. cirq/ops/pauli_sum_exponential.py +2 -1
  199. cirq/ops/permutation_gate.py +2 -1
  200. cirq/ops/phased_iswap_gate.py +3 -2
  201. cirq/ops/phased_x_gate.py +5 -4
  202. cirq/ops/phased_x_z_gate.py +12 -5
  203. cirq/ops/projector.py +2 -1
  204. cirq/ops/qubit_manager.py +2 -1
  205. cirq/ops/qubit_order.py +2 -1
  206. cirq/ops/qubit_order_or_list.py +1 -1
  207. cirq/ops/random_gate_channel.py +3 -2
  208. cirq/ops/raw_types.py +33 -16
  209. cirq/ops/raw_types_test.py +4 -3
  210. cirq/ops/state_preparation_channel.py +2 -1
  211. cirq/ops/three_qubit_gates.py +3 -2
  212. cirq/ops/two_qubit_diagonal_gate.py +3 -2
  213. cirq/ops/uniform_superposition_gate.py +2 -1
  214. cirq/ops/wait_gate.py +10 -4
  215. cirq/protocols/act_on_protocol.py +2 -1
  216. cirq/protocols/act_on_protocol_test.py +2 -1
  217. cirq/protocols/apply_channel_protocol.py +2 -1
  218. cirq/protocols/apply_mixture_protocol.py +2 -1
  219. cirq/protocols/apply_mixture_protocol_test.py +2 -1
  220. cirq/protocols/apply_unitary_protocol.py +2 -1
  221. cirq/protocols/apply_unitary_protocol_test.py +2 -0
  222. cirq/protocols/approximate_equality_protocol.py +2 -1
  223. cirq/protocols/circuit_diagram_info_protocol.py +2 -1
  224. cirq/protocols/control_key_protocol.py +7 -0
  225. cirq/protocols/decompose_protocol.py +2 -12
  226. cirq/protocols/has_stabilizer_effect_protocol.py +1 -1
  227. cirq/protocols/has_stabilizer_effect_protocol_test.py +11 -9
  228. cirq/protocols/has_unitary_protocol_test.py +3 -3
  229. cirq/protocols/hash_from_pickle_test.py +2 -2
  230. cirq/protocols/inverse_protocol.py +2 -1
  231. cirq/protocols/json_serialization.py +5 -4
  232. cirq/protocols/json_serialization_test.py +31 -31
  233. cirq/protocols/kraus_protocol.py +4 -3
  234. cirq/protocols/kraus_protocol_test.py +7 -7
  235. cirq/protocols/measurement_key_protocol.py +32 -8
  236. cirq/protocols/mixture_protocol.py +3 -2
  237. cirq/protocols/mixture_protocol_test.py +7 -7
  238. cirq/protocols/mul_protocol_test.py +4 -4
  239. cirq/protocols/phase_protocol.py +13 -4
  240. cirq/protocols/pow_protocol.py +2 -1
  241. cirq/protocols/pow_protocol_test.py +5 -5
  242. cirq/protocols/qasm.py +2 -1
  243. cirq/protocols/qid_shape_protocol.py +2 -1
  244. cirq/protocols/resolve_parameters.py +17 -15
  245. cirq/protocols/trace_distance_bound.py +2 -1
  246. cirq/protocols/unitary_protocol.py +21 -21
  247. cirq/protocols/unitary_protocol_test.py +31 -19
  248. cirq/qis/channels.py +1 -1
  249. cirq/qis/channels_test.py +1 -1
  250. cirq/qis/clifford_tableau.py +16 -15
  251. cirq/qis/clifford_tableau_test.py +17 -17
  252. cirq/qis/entropy.py +3 -3
  253. cirq/qis/entropy_test.py +1 -1
  254. cirq/qis/quantum_state_representation.py +2 -1
  255. cirq/qis/states.py +7 -2
  256. cirq/qis/states_test.py +54 -54
  257. cirq/sim/classical_simulator.py +25 -14
  258. cirq/sim/classical_simulator_test.py +85 -30
  259. cirq/sim/clifford/clifford_simulator.py +7 -6
  260. cirq/sim/clifford/clifford_simulator_test.py +51 -50
  261. cirq/sim/clifford/clifford_tableau_simulation_state.py +2 -1
  262. cirq/sim/clifford/stabilizer_ch_form_simulation_state.py +2 -1
  263. cirq/sim/clifford/stabilizer_sampler.py +1 -1
  264. cirq/sim/clifford/stabilizer_simulation_state.py +2 -1
  265. cirq/sim/clifford/stabilizer_state_ch_form.py +16 -15
  266. cirq/sim/clifford/stabilizer_state_ch_form_test.py +0 -1
  267. cirq/sim/density_matrix_simulation_state.py +7 -6
  268. cirq/sim/density_matrix_simulator.py +3 -2
  269. cirq/sim/density_matrix_simulator_test.py +94 -84
  270. cirq/sim/density_matrix_utils.py +2 -1
  271. cirq/sim/density_matrix_utils_test.py +1 -1
  272. cirq/sim/mux.py +35 -8
  273. cirq/sim/mux_test.py +39 -26
  274. cirq/sim/simulation_product_state.py +2 -1
  275. cirq/sim/simulation_product_state_test.py +8 -7
  276. cirq/sim/simulation_state.py +6 -5
  277. cirq/sim/simulation_state_base.py +3 -2
  278. cirq/sim/simulation_state_test.py +7 -6
  279. cirq/sim/simulation_utils.py +2 -1
  280. cirq/sim/simulator.py +4 -3
  281. cirq/sim/simulator_base.py +2 -1
  282. cirq/sim/simulator_base_test.py +51 -36
  283. cirq/sim/simulator_test.py +41 -36
  284. cirq/sim/sparse_simulator.py +3 -2
  285. cirq/sim/sparse_simulator_test.py +92 -82
  286. cirq/sim/state_vector.py +5 -6
  287. cirq/sim/state_vector_simulation_state.py +10 -9
  288. cirq/sim/state_vector_simulator.py +2 -1
  289. cirq/sim/state_vector_simulator_test.py +9 -9
  290. cirq/sim/state_vector_test.py +40 -39
  291. cirq/study/__init__.py +1 -0
  292. cirq/study/flatten_expressions.py +2 -1
  293. cirq/study/resolver.py +31 -18
  294. cirq/study/resolver_test.py +1 -1
  295. cirq/study/result.py +2 -1
  296. cirq/study/result_test.py +20 -20
  297. cirq/study/sweepable.py +2 -1
  298. cirq/study/sweepable_test.py +20 -20
  299. cirq/study/sweeps.py +26 -1
  300. cirq/study/sweeps_test.py +67 -43
  301. cirq/testing/_compat_test_data/__init__.py +3 -3
  302. cirq/testing/circuit_compare.py +2 -1
  303. cirq/testing/circuit_compare_test.py +16 -14
  304. cirq/testing/consistent_act_on_test.py +1 -1
  305. cirq/testing/consistent_channels.py +2 -2
  306. cirq/testing/consistent_controlled_gate_op.py +2 -2
  307. cirq/testing/consistent_controlled_gate_op_test.py +2 -1
  308. cirq/testing/consistent_decomposition.py +4 -2
  309. cirq/testing/consistent_phase_by.py +1 -1
  310. cirq/testing/consistent_protocols.py +2 -1
  311. cirq/testing/consistent_protocols_test.py +3 -3
  312. cirq/testing/consistent_qasm.py +4 -3
  313. cirq/testing/consistent_qasm_test.py +3 -3
  314. cirq/testing/consistent_resolve_parameters.py +1 -1
  315. cirq/testing/consistent_unitary.py +1 -1
  316. cirq/testing/consistent_unitary_test.py +1 -1
  317. cirq/testing/deprecation.py +1 -1
  318. cirq/testing/devices.py +3 -2
  319. cirq/testing/equals_tester.py +4 -3
  320. cirq/testing/equivalent_basis_map.py +4 -2
  321. cirq/testing/json.py +3 -2
  322. cirq/testing/lin_alg_utils.py +1 -1
  323. cirq/testing/logs.py +1 -1
  324. cirq/testing/op_tree.py +1 -1
  325. cirq/testing/order_tester.py +2 -2
  326. cirq/testing/pytest_utils.py +2 -1
  327. cirq/testing/random_circuit.py +2 -1
  328. cirq/testing/random_circuit_test.py +2 -1
  329. cirq/testing/repr_pretty_tester.py +3 -3
  330. cirq/transformers/__init__.py +1 -0
  331. cirq/transformers/_connected_component.py +231 -0
  332. cirq/transformers/_connected_component_test.py +200 -0
  333. cirq/transformers/align_test.py +13 -13
  334. cirq/transformers/analytical_decompositions/clifford_decomposition.py +8 -7
  335. cirq/transformers/analytical_decompositions/clifford_decomposition_test.py +5 -5
  336. cirq/transformers/analytical_decompositions/controlled_gate_decomposition.py +11 -10
  337. cirq/transformers/analytical_decompositions/controlled_gate_decomposition_test.py +6 -6
  338. cirq/transformers/analytical_decompositions/cphase_to_fsim.py +3 -2
  339. cirq/transformers/analytical_decompositions/cphase_to_fsim_test.py +11 -10
  340. cirq/transformers/analytical_decompositions/quantum_shannon_decomposition.py +8 -7
  341. cirq/transformers/analytical_decompositions/quantum_shannon_decomposition_test.py +17 -20
  342. cirq/transformers/analytical_decompositions/single_qubit_decompositions_test.py +33 -27
  343. cirq/transformers/analytical_decompositions/single_to_two_qubit_isometry_test.py +1 -1
  344. cirq/transformers/analytical_decompositions/three_qubit_decomposition.py +1 -1
  345. cirq/transformers/analytical_decompositions/two_qubit_state_preparation_test.py +12 -11
  346. cirq/transformers/analytical_decompositions/two_qubit_to_cz.py +5 -2
  347. cirq/transformers/analytical_decompositions/two_qubit_to_cz_test.py +3 -3
  348. cirq/transformers/analytical_decompositions/two_qubit_to_fsim.py +2 -1
  349. cirq/transformers/analytical_decompositions/two_qubit_to_ms.py +2 -1
  350. cirq/transformers/analytical_decompositions/two_qubit_to_ms_test.py +2 -2
  351. cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py +2 -1
  352. cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap_test.py +32 -30
  353. cirq/transformers/drop_negligible_operations_test.py +7 -7
  354. cirq/transformers/dynamical_decoupling.py +185 -112
  355. cirq/transformers/dynamical_decoupling_test.py +195 -201
  356. cirq/transformers/eject_phased_paulis.py +2 -1
  357. cirq/transformers/eject_phased_paulis_test.py +3 -2
  358. cirq/transformers/eject_z.py +5 -3
  359. cirq/transformers/eject_z_test.py +23 -25
  360. cirq/transformers/expand_composite.py +3 -2
  361. cirq/transformers/expand_composite_test.py +14 -14
  362. cirq/transformers/gauge_compiling/__init__.py +13 -0
  363. cirq/transformers/gauge_compiling/gauge_compiling.py +3 -2
  364. cirq/transformers/gauge_compiling/gauge_compiling_test.py +14 -12
  365. cirq/transformers/gauge_compiling/gauge_compiling_test_utils.py +3 -3
  366. cirq/transformers/gauge_compiling/idle_moments_gauge.py +225 -0
  367. cirq/transformers/gauge_compiling/idle_moments_gauge_test.py +193 -0
  368. cirq/transformers/gauge_compiling/multi_moment_cphase_gauge.py +242 -0
  369. cirq/transformers/gauge_compiling/multi_moment_cphase_gauge_test.py +243 -0
  370. cirq/transformers/gauge_compiling/multi_moment_gauge_compiling.py +151 -0
  371. cirq/transformers/gauge_compiling/sqrt_cz_gauge.py +2 -1
  372. cirq/transformers/heuristic_decompositions/gate_tabulation_math_utils.py +1 -1
  373. cirq/transformers/heuristic_decompositions/gate_tabulation_math_utils_test.py +6 -6
  374. cirq/transformers/heuristic_decompositions/two_qubit_gate_tabulation.py +3 -2
  375. cirq/transformers/measurement_transformers.py +2 -1
  376. cirq/transformers/measurement_transformers_test.py +45 -39
  377. cirq/transformers/merge_k_qubit_gates.py +2 -1
  378. cirq/transformers/merge_k_qubit_gates_test.py +1 -1
  379. cirq/transformers/merge_single_qubit_gates.py +9 -5
  380. cirq/transformers/merge_single_qubit_gates_test.py +22 -22
  381. cirq/transformers/noise_adding_test.py +2 -2
  382. cirq/transformers/optimize_for_target_gateset.py +2 -1
  383. cirq/transformers/optimize_for_target_gateset_test.py +11 -9
  384. cirq/transformers/qubit_management_transformers_test.py +6 -2
  385. cirq/transformers/routing/mapping_manager.py +2 -1
  386. cirq/transformers/routing/route_circuit_cqc.py +2 -1
  387. cirq/transformers/stratify.py +2 -1
  388. cirq/transformers/symbolize.py +2 -1
  389. cirq/transformers/tag_transformers.py +2 -1
  390. cirq/transformers/target_gatesets/compilation_target_gateset.py +2 -1
  391. cirq/transformers/target_gatesets/cz_gateset.py +2 -1
  392. cirq/transformers/target_gatesets/cz_gateset_test.py +1 -1
  393. cirq/transformers/target_gatesets/sqrt_iswap_gateset.py +2 -1
  394. cirq/transformers/transformer_api.py +2 -1
  395. cirq/transformers/transformer_primitives.py +271 -145
  396. cirq/transformers/transformer_primitives_test.py +185 -1
  397. cirq/value/abc_alt.py +2 -1
  398. cirq/value/classical_data.py +2 -1
  399. cirq/value/condition.py +2 -1
  400. cirq/value/digits.py +9 -2
  401. cirq/value/duration.py +6 -5
  402. cirq/value/linear_dict.py +4 -9
  403. cirq/value/measurement_key.py +2 -1
  404. cirq/value/periodic_value.py +3 -2
  405. cirq/value/product_state.py +2 -1
  406. cirq/value/value_equality_attr.py +2 -1
  407. cirq/vis/density_matrix.py +1 -1
  408. cirq/vis/heatmap.py +2 -1
  409. cirq/vis/histogram.py +2 -1
  410. cirq/vis/state_histogram.py +2 -1
  411. cirq/work/collector.py +2 -1
  412. cirq/work/observable_grouping.py +2 -1
  413. cirq/work/observable_measurement.py +2 -1
  414. cirq/work/observable_measurement_data.py +2 -1
  415. cirq/work/observable_measurement_test.py +1 -1
  416. cirq/work/observable_readout_calibration.py +2 -1
  417. cirq/work/observable_readout_calibration_test.py +1 -1
  418. cirq/work/observable_settings.py +2 -1
  419. cirq/work/sampler.py +2 -1
  420. cirq/work/sampler_test.py +1 -1
  421. {cirq_core-1.7.0.dev20250825174419.dist-info → cirq_core-1.7.0.dev20251203004401.dist-info}/METADATA +5 -6
  422. {cirq_core-1.7.0.dev20250825174419.dist-info → cirq_core-1.7.0.dev20251203004401.dist-info}/RECORD +425 -406
  423. cirq/contrib/json_test.py +0 -33
  424. {cirq_core-1.7.0.dev20250825174419.dist-info → cirq_core-1.7.0.dev20251203004401.dist-info}/WHEEL +0 -0
  425. {cirq_core-1.7.0.dev20250825174419.dist-info → cirq_core-1.7.0.dev20251203004401.dist-info}/licenses/LICENSE +0 -0
  426. {cirq_core-1.7.0.dev20250825174419.dist-info → cirq_core-1.7.0.dev20251203004401.dist-info}/top_level.txt +0 -0
@@ -72,7 +72,7 @@ def _get_testspecs_for_modules() -> list[ModuleJsonTestSpec]:
72
72
  MODULE_TEST_SPECS = _get_testspecs_for_modules()
73
73
 
74
74
 
75
- def test_deprecated_cirq_type_in_json_dict():
75
+ def test_deprecated_cirq_type_in_json_dict() -> None:
76
76
  class HasOldJsonDict:
77
77
  # Required for testing serialization of non-cirq objects.
78
78
  __module__ = 'test.noncirq.namespace'
@@ -99,7 +99,7 @@ def test_deprecated_cirq_type_in_json_dict():
99
99
  assert_json_roundtrip_works(HasOldJsonDict(), resolvers=test_resolvers)
100
100
 
101
101
 
102
- def test_line_qubit_roundtrip():
102
+ def test_line_qubit_roundtrip() -> None:
103
103
  q1 = cirq.LineQubit(12)
104
104
  assert_json_roundtrip_works(
105
105
  q1,
@@ -110,7 +110,7 @@ def test_line_qubit_roundtrip():
110
110
  )
111
111
 
112
112
 
113
- def test_gridqubit_roundtrip():
113
+ def test_gridqubit_roundtrip() -> None:
114
114
  q = cirq.GridQubit(15, 18)
115
115
  assert_json_roundtrip_works(
116
116
  q,
@@ -122,7 +122,7 @@ def test_gridqubit_roundtrip():
122
122
  )
123
123
 
124
124
 
125
- def test_op_roundtrip():
125
+ def test_op_roundtrip() -> None:
126
126
  q = cirq.LineQubit(5)
127
127
  op1 = cirq.rx(0.123).on(q)
128
128
  assert_json_roundtrip_works(
@@ -143,7 +143,7 @@ def test_op_roundtrip():
143
143
  )
144
144
 
145
145
 
146
- def test_op_roundtrip_filename(tmpdir):
146
+ def test_op_roundtrip_filename(tmpdir) -> None:
147
147
  filename = f'{tmpdir}/op.json'
148
148
  q = cirq.LineQubit(5)
149
149
  op1 = cirq.rx(0.123).on(q)
@@ -159,7 +159,7 @@ def test_op_roundtrip_filename(tmpdir):
159
159
  assert op1 == op3
160
160
 
161
161
 
162
- def test_op_roundtrip_file_obj(tmpdir):
162
+ def test_op_roundtrip_file_obj(tmpdir) -> None:
163
163
  filename = f'{tmpdir}/op.json'
164
164
  q = cirq.LineQubit(5)
165
165
  op1 = cirq.rx(0.123).on(q)
@@ -179,7 +179,7 @@ def test_op_roundtrip_file_obj(tmpdir):
179
179
  assert op1 == op3
180
180
 
181
181
 
182
- def test_fail_to_resolve():
182
+ def test_fail_to_resolve() -> None:
183
183
  buffer = io.StringIO()
184
184
  buffer.write(
185
185
  """
@@ -207,7 +207,7 @@ Q0, Q1, Q2, Q3, Q4 = QUBITS
207
207
  # deprecation error in testing. It is cleaner to just turn it off than to assert
208
208
  # deprecation for each submodule.
209
209
  @mock.patch.dict(os.environ, clear='CIRQ_TESTING')
210
- def test_shouldnt_be_serialized_no_superfluous(mod_spec: ModuleJsonTestSpec):
210
+ def test_shouldnt_be_serialized_no_superfluous(mod_spec: ModuleJsonTestSpec) -> None:
211
211
  # everything in the list should be ignored for a reason
212
212
  names = set(mod_spec.get_all_names())
213
213
  missing_names = set(mod_spec.should_not_be_serialized).difference(names)
@@ -223,7 +223,7 @@ def test_shouldnt_be_serialized_no_superfluous(mod_spec: ModuleJsonTestSpec):
223
223
  # deprecation error in testing. It is cleaner to just turn it off than to assert
224
224
  # deprecation for each submodule.
225
225
  @mock.patch.dict(os.environ, clear='CIRQ_TESTING')
226
- def test_not_yet_serializable_no_superfluous(mod_spec: ModuleJsonTestSpec):
226
+ def test_not_yet_serializable_no_superfluous(mod_spec: ModuleJsonTestSpec) -> None:
227
227
  # everything in the list should be ignored for a reason
228
228
  names = set(mod_spec.get_all_names())
229
229
  missing_names = set(mod_spec.not_yet_serializable).difference(names)
@@ -233,7 +233,7 @@ def test_not_yet_serializable_no_superfluous(mod_spec: ModuleJsonTestSpec):
233
233
 
234
234
 
235
235
  @pytest.mark.parametrize('mod_spec', MODULE_TEST_SPECS, ids=repr)
236
- def test_mutually_exclusive_not_serialize_lists(mod_spec: ModuleJsonTestSpec):
236
+ def test_mutually_exclusive_not_serialize_lists(mod_spec: ModuleJsonTestSpec) -> None:
237
237
  common = set(mod_spec.should_not_be_serialized) & set(mod_spec.not_yet_serializable)
238
238
  assert len(common) == 0, (
239
239
  f"Defined in both {mod_spec.name} 'Not yet serializable' "
@@ -242,7 +242,7 @@ def test_mutually_exclusive_not_serialize_lists(mod_spec: ModuleJsonTestSpec):
242
242
 
243
243
 
244
244
  @pytest.mark.parametrize('mod_spec', MODULE_TEST_SPECS, ids=repr)
245
- def test_resolver_cache_vs_should_not_serialize(mod_spec: ModuleJsonTestSpec):
245
+ def test_resolver_cache_vs_should_not_serialize(mod_spec: ModuleJsonTestSpec) -> None:
246
246
  resolver_cache_types = set([n for (n, _) in mod_spec.get_resolver_cache_types()])
247
247
  common = set(mod_spec.should_not_be_serialized) & resolver_cache_types
248
248
 
@@ -254,7 +254,7 @@ def test_resolver_cache_vs_should_not_serialize(mod_spec: ModuleJsonTestSpec):
254
254
 
255
255
 
256
256
  @pytest.mark.parametrize('mod_spec', MODULE_TEST_SPECS, ids=repr)
257
- def test_resolver_cache_vs_not_yet_serializable(mod_spec: ModuleJsonTestSpec):
257
+ def test_resolver_cache_vs_not_yet_serializable(mod_spec: ModuleJsonTestSpec) -> None:
258
258
  resolver_cache_types = set([n for (n, _) in mod_spec.get_resolver_cache_types()])
259
259
  common = set(mod_spec.not_yet_serializable) & resolver_cache_types
260
260
 
@@ -267,14 +267,14 @@ def test_resolver_cache_vs_not_yet_serializable(mod_spec: ModuleJsonTestSpec):
267
267
  )
268
268
 
269
269
 
270
- def test_builtins():
270
+ def test_builtins() -> None:
271
271
  assert_json_roundtrip_works(True)
272
272
  assert_json_roundtrip_works(1)
273
273
  assert_json_roundtrip_works(1 + 2j)
274
274
  assert_json_roundtrip_works({'test': [123, 5.5], 'key2': 'asdf', '3': None, '0.0': []})
275
275
 
276
276
 
277
- def test_numpy():
277
+ def test_numpy() -> None:
278
278
  x = np.ones(1)[0]
279
279
 
280
280
  assert_json_roundtrip_works(np.bool_(True))
@@ -295,7 +295,7 @@ def test_numpy():
295
295
  assert_json_roundtrip_works(np.arange(3))
296
296
 
297
297
 
298
- def test_pandas():
298
+ def test_pandas() -> None:
299
299
  assert_json_roundtrip_works(
300
300
  pd.DataFrame(data=[[1, 2, 3], [4, 5, 6]], columns=['x', 'y', 'z'], index=[2, 5])
301
301
  )
@@ -320,7 +320,7 @@ def test_pandas():
320
320
  )
321
321
 
322
322
 
323
- def test_sympy():
323
+ def test_sympy() -> None:
324
324
  # Raw values.
325
325
  assert_json_roundtrip_works(sympy.Symbol('theta'))
326
326
  assert_json_roundtrip_works(sympy.Integer(5))
@@ -388,7 +388,7 @@ class SBKImpl(cirq.SerializableByKey):
388
388
  return cls(name, data_list, tuple(data_tuple), data_dict)
389
389
 
390
390
 
391
- def test_serializable_by_key():
391
+ def test_serializable_by_key() -> None:
392
392
  def custom_resolver(name):
393
393
  if name == 'SBKImpl':
394
394
  return SBKImpl
@@ -443,12 +443,12 @@ def _list_public_classes_for_tested_modules():
443
443
 
444
444
 
445
445
  @pytest.mark.parametrize('mod_spec,cirq_obj_name,cls', _list_public_classes_for_tested_modules())
446
- def test_json_test_data_coverage(mod_spec: ModuleJsonTestSpec, cirq_obj_name: str, cls):
446
+ def test_json_test_data_coverage(mod_spec: ModuleJsonTestSpec, cirq_obj_name: str, cls) -> None:
447
447
  if cirq_obj_name in mod_spec.tested_elsewhere:
448
448
  pytest.skip("Tested elsewhere.")
449
449
 
450
450
  if cirq_obj_name in mod_spec.not_yet_serializable:
451
- return pytest.xfail(reason="Not serializable (yet)")
451
+ pytest.xfail(reason="Not serializable (yet)")
452
452
 
453
453
  test_data_path = mod_spec.test_data_path
454
454
  rel_path = test_data_path.relative_to(REPO_ROOT)
@@ -529,12 +529,12 @@ class SerializableTypeObject:
529
529
 
530
530
 
531
531
  @pytest.mark.parametrize('mod_spec,cirq_obj_name,cls', _list_public_classes_for_tested_modules())
532
- def test_type_serialization(mod_spec: ModuleJsonTestSpec, cirq_obj_name: str, cls):
532
+ def test_type_serialization(mod_spec: ModuleJsonTestSpec, cirq_obj_name: str, cls) -> None:
533
533
  if cirq_obj_name in mod_spec.tested_elsewhere:
534
534
  pytest.skip("Tested elsewhere.")
535
535
 
536
536
  if cirq_obj_name in mod_spec.not_yet_serializable:
537
- return pytest.xfail(reason="Not serializable (yet)")
537
+ pytest.xfail(reason="Not serializable (yet)")
538
538
 
539
539
  if cls is None:
540
540
  pytest.skip(f'No serialization for None-mapped type: {cirq_obj_name}') # pragma: no cover
@@ -556,7 +556,7 @@ def test_type_serialization(mod_spec: ModuleJsonTestSpec, cirq_obj_name: str, cl
556
556
  assert_json_roundtrip_works(sto, resolvers=test_resolvers)
557
557
 
558
558
 
559
- def test_invalid_type_deserialize():
559
+ def test_invalid_type_deserialize() -> None:
560
560
  def custom_resolver(name):
561
561
  if name == 'SerializableTypeObject':
562
562
  return SerializableTypeObject
@@ -571,7 +571,7 @@ def test_invalid_type_deserialize():
571
571
  _ = cirq.read_json(json_text=factory_json, resolvers=test_resolvers)
572
572
 
573
573
 
574
- def test_to_from_strings():
574
+ def test_to_from_strings() -> None:
575
575
  x_json_text = """{
576
576
  "cirq_type": "_PauliX",
577
577
  "exponent": 1.0,
@@ -584,7 +584,7 @@ def test_to_from_strings():
584
584
  cirq.read_json(io.StringIO(), json_text=x_json_text)
585
585
 
586
586
 
587
- def test_to_from_json_gzip():
587
+ def test_to_from_json_gzip() -> None:
588
588
  a, b = cirq.LineQubit.range(2)
589
589
  test_circuit = cirq.Circuit(cirq.H(a), cirq.CX(a, b))
590
590
  gzip_data = cirq.to_json_gzip(test_circuit)
@@ -631,7 +631,7 @@ def assert_repr_and_json_test_data_agree(
631
631
  json_path: pathlib.Path,
632
632
  inward_only: bool,
633
633
  deprecation_deadline: str | None,
634
- ):
634
+ ) -> None:
635
635
  if not repr_path.exists() and not json_path.exists():
636
636
  return
637
637
 
@@ -701,7 +701,7 @@ def assert_repr_and_json_test_data_agree(
701
701
  'mod_spec, abs_path',
702
702
  [(m, abs_path) for m in MODULE_TEST_SPECS for abs_path in m.all_test_data_keys()],
703
703
  )
704
- def test_json_and_repr_data(mod_spec: ModuleJsonTestSpec, abs_path: str):
704
+ def test_json_and_repr_data(mod_spec: ModuleJsonTestSpec, abs_path: str) -> None:
705
705
  assert_repr_and_json_test_data_agree(
706
706
  mod_spec=mod_spec,
707
707
  repr_path=pathlib.Path(f'{abs_path}.repr'),
@@ -718,7 +718,7 @@ def test_json_and_repr_data(mod_spec: ModuleJsonTestSpec, abs_path: str):
718
718
  )
719
719
 
720
720
 
721
- def test_pathlib_paths(tmpdir):
721
+ def test_pathlib_paths(tmpdir) -> None:
722
722
  path = pathlib.Path(tmpdir) / 'op.json'
723
723
  cirq.to_json(cirq.X, path)
724
724
  assert cirq.read_json(path) == cirq.X
@@ -746,7 +746,7 @@ def test_dataclass_json_dict() -> None:
746
746
  assert_json_roundtrip_works(my_dc, resolvers=[custom_resolver, *cirq.DEFAULT_RESOLVERS])
747
747
 
748
748
 
749
- def test_numpy_values():
749
+ def test_numpy_values() -> None:
750
750
  assert (
751
751
  cirq.to_json({'value': np.array(1)})
752
752
  == """{
@@ -755,7 +755,7 @@ def test_numpy_values():
755
755
  )
756
756
 
757
757
 
758
- def test_basic_time_assertions():
758
+ def test_basic_time_assertions() -> None:
759
759
  naive_dt = datetime.datetime.now()
760
760
  utc_dt = naive_dt.astimezone(datetime.timezone.utc)
761
761
  assert naive_dt.timestamp() == utc_dt.timestamp()
@@ -768,7 +768,7 @@ def test_basic_time_assertions():
768
768
  assert naive_dt == re_naive, 'works, as long as you called fromtimestamp from the same timezone'
769
769
 
770
770
 
771
- def test_datetime():
771
+ def test_datetime() -> None:
772
772
  naive_dt = datetime.datetime.now()
773
773
 
774
774
  re_naive_dt = cirq.read_json(json_text=cirq.to_json(naive_dt))
@@ -793,7 +793,7 @@ class _TestAttrsClas:
793
793
  x: int
794
794
 
795
795
 
796
- def test_attrs_json_dict():
796
+ def test_attrs_json_dict() -> None:
797
797
  obj = _TestAttrsClas('test', x=123)
798
798
  js = json_serialization.attrs_json_dict(obj)
799
799
  assert js == {'name': 'test', 'x': 123}
@@ -17,8 +17,9 @@
17
17
  from __future__ import annotations
18
18
 
19
19
  import warnings
20
+ from collections.abc import Iterable
20
21
  from types import NotImplementedType
21
- from typing import Any, Protocol, Sequence, TypeVar
22
+ from typing import Any, Protocol, TypeVar
22
23
 
23
24
  import numpy as np
24
25
 
@@ -31,7 +32,7 @@ from cirq.protocols.unitary_protocol import unitary
31
32
 
32
33
  # This is a special indicator value used by the channel method to determine
33
34
  # whether or not the caller provided a 'default' argument. It must be of type
34
- # Sequence[np.ndarray] to ensure the method has the correct type signature in
35
+ # Iterable[np.ndarray] to ensure the method has the correct type signature in
35
36
  # that case. It is checked for using `is`, so it won't have a false positive
36
37
  # if the user provides a different (np.array([]),) value.
37
38
  RaiseTypeErrorIfNotProvided: tuple[np.ndarray] = (np.array([]),)
@@ -44,7 +45,7 @@ class SupportsKraus(Protocol):
44
45
  """An object that may be describable as a quantum channel."""
45
46
 
46
47
  @doc_private
47
- def _kraus_(self) -> Sequence[np.ndarray] | NotImplementedType:
48
+ def _kraus_(self) -> Iterable[np.ndarray] | NotImplementedType:
48
49
  r"""A list of Kraus matrices describing the quantum channel.
49
50
 
50
51
  These matrices are the terms in the operator sum representation of a
@@ -16,7 +16,7 @@
16
16
 
17
17
  from __future__ import annotations
18
18
 
19
- from typing import Iterable, Sequence
19
+ from collections.abc import Iterable
20
20
 
21
21
  import numpy as np
22
22
  import pytest
@@ -42,7 +42,7 @@ def test_kraus_no_methods() -> None:
42
42
  assert not cirq.has_kraus(NoMethod())
43
43
 
44
44
 
45
- def assert_not_implemented(val):
45
+ def assert_not_implemented(val) -> None:
46
46
  with pytest.raises(TypeError, match='returned NotImplemented'):
47
47
  _ = cirq.kraus(val)
48
48
 
@@ -89,7 +89,7 @@ def test_explicit_kraus() -> None:
89
89
  c = (a0, a1)
90
90
 
91
91
  class ReturnsKraus:
92
- def _kraus_(self) -> Sequence[np.ndarray]:
92
+ def _kraus_(self) -> Iterable[np.ndarray]:
93
93
  return c
94
94
 
95
95
  assert cirq.kraus(ReturnsKraus()) is c
@@ -174,7 +174,7 @@ def test_has_kraus_when_decomposed(decomposed_cls) -> None:
174
174
  assert not cirq.has_kraus(op, allow_decompose=False)
175
175
 
176
176
 
177
- def test_strat_kraus_from_apply_channel_returns_none():
177
+ def test_strat_kraus_from_apply_channel_returns_none() -> None:
178
178
  # Remove _kraus_ and _apply_channel_ methods
179
179
  class NoApplyChannelReset(cirq.ResetChannel):
180
180
  def _kraus_(self):
@@ -228,7 +228,7 @@ def test_kraus_fallback_to_apply_channel(channel_cls, params) -> None:
228
228
  np.testing.assert_allclose(actual_super, expected_super, atol=1e-8)
229
229
 
230
230
 
231
- def test_reset_channel_kraus_apply_channel_consistency():
231
+ def test_reset_channel_kraus_apply_channel_consistency() -> None:
232
232
  Reset = cirq.ResetChannel
233
233
  # Original gate
234
234
  gate = Reset()
@@ -236,7 +236,7 @@ def test_reset_channel_kraus_apply_channel_consistency():
236
236
  cirq.testing.assert_consistent_channel(gate)
237
237
 
238
238
  # Remove _kraus_ method
239
- class NoKrausReset(Reset):
239
+ class NoKrausReset(cirq.ResetChannel):
240
240
  def _kraus_(self):
241
241
  return NotImplemented
242
242
 
@@ -245,7 +245,7 @@ def test_reset_channel_kraus_apply_channel_consistency():
245
245
  np.testing.assert_allclose(cirq.kraus(gate), cirq.kraus(gate_no_kraus), atol=1e-8)
246
246
 
247
247
 
248
- def test_kraus_channel_with_has_unitary():
248
+ def test_kraus_channel_with_has_unitary() -> None:
249
249
  """CZSWAP has no unitary dunder method but has_unitary returns True."""
250
250
  op = cirq.CZSWAP.on(cirq.q(1), cirq.q(2))
251
251
  channels = cirq.kraus(op)
@@ -16,8 +16,9 @@
16
16
 
17
17
  from __future__ import annotations
18
18
 
19
+ from collections.abc import Mapping
19
20
  from types import NotImplementedType
20
- from typing import Any, Mapping, Protocol, TYPE_CHECKING
21
+ from typing import Any, overload, Protocol, TYPE_CHECKING, TypeVar
21
22
 
22
23
  from cirq import value
23
24
  from cirq._doc import doc_private
@@ -25,6 +26,9 @@ from cirq._doc import doc_private
25
26
  if TYPE_CHECKING:
26
27
  import cirq
27
28
 
29
+ T = TypeVar('T')
30
+ TDefault = TypeVar('TDefault')
31
+
28
32
  # This is a special indicator value used by the inverse method to determine
29
33
  # whether or not the caller provided a 'default' argument.
30
34
  RaiseTypeErrorIfNotProvided: Any = ([],)
@@ -104,7 +108,17 @@ class SupportsMeasurementKey(Protocol):
104
108
  """
105
109
 
106
110
 
107
- def measurement_key_obj(val: Any, default: Any = RaiseTypeErrorIfNotProvided):
111
+ @overload
112
+ def measurement_key_obj(val: Any) -> cirq.MeasurementKey:
113
+ pass
114
+
115
+
116
+ @overload
117
+ def measurement_key_obj(val: Any, default: TDefault) -> cirq.MeasurementKey | TDefault:
118
+ pass
119
+
120
+
121
+ def measurement_key_obj(val, default=RaiseTypeErrorIfNotProvided):
108
122
  """Get the single measurement key object for the given value.
109
123
 
110
124
  Args:
@@ -138,7 +152,17 @@ def measurement_key_obj(val: Any, default: Any = RaiseTypeErrorIfNotProvided):
138
152
  raise TypeError(f"Object of type '{type(val)}' had no measurement keys.")
139
153
 
140
154
 
141
- def measurement_key_name(val: Any, default: Any = RaiseTypeErrorIfNotProvided):
155
+ @overload
156
+ def measurement_key_name(val: Any) -> str:
157
+ pass
158
+
159
+
160
+ @overload
161
+ def measurement_key_name(val: Any, default: TDefault) -> str | TDefault:
162
+ pass
163
+
164
+
165
+ def measurement_key_name(val, default=RaiseTypeErrorIfNotProvided):
142
166
  """Get the single measurement key for the given value.
143
167
 
144
168
  Args:
@@ -278,7 +302,7 @@ def is_measurement(val: Any) -> bool:
278
302
  return keys is not NotImplemented and bool(keys)
279
303
 
280
304
 
281
- def with_measurement_key_mapping(val: Any, key_map: Mapping[str, str]):
305
+ def with_measurement_key_mapping(val: T, key_map: Mapping[str, str]) -> T:
282
306
  """Remaps the target's measurement keys according to the provided key_map.
283
307
 
284
308
  This method can be used to reassign measurement keys at runtime, or to
@@ -288,7 +312,7 @@ def with_measurement_key_mapping(val: Any, key_map: Mapping[str, str]):
288
312
  return NotImplemented if getter is None else getter(key_map)
289
313
 
290
314
 
291
- def with_key_path(val: Any, path: tuple[str, ...]):
315
+ def with_key_path(val: T, path: tuple[str, ...]) -> T:
292
316
  """Adds the path to the target's measurement keys.
293
317
 
294
318
  The path usually refers to an identifier or a list of identifiers from a subcircuit that
@@ -299,7 +323,7 @@ def with_key_path(val: Any, path: tuple[str, ...]):
299
323
  return NotImplemented if getter is None else getter(path)
300
324
 
301
325
 
302
- def with_key_path_prefix(val: Any, prefix: tuple[str, ...]):
326
+ def with_key_path_prefix(val: T, prefix: tuple[str, ...]) -> T:
303
327
  """Prefixes the path to the target's measurement keys.
304
328
 
305
329
  The path usually refers to an identifier or a list of identifiers from a subcircuit that
@@ -315,8 +339,8 @@ def with_key_path_prefix(val: Any, prefix: tuple[str, ...]):
315
339
 
316
340
 
317
341
  def with_rescoped_keys(
318
- val: Any, path: tuple[str, ...], bindable_keys: frozenset[cirq.MeasurementKey] | None = None
319
- ):
342
+ val: T, path: tuple[str, ...], bindable_keys: frozenset[cirq.MeasurementKey] | None = None
343
+ ) -> T:
320
344
  """Rescopes any measurement and control keys to the provided path, given the existing keys.
321
345
 
322
346
  The path usually refers to an identifier or a list of identifiers from a subcircuit that
@@ -16,8 +16,9 @@
16
16
 
17
17
  from __future__ import annotations
18
18
 
19
+ from collections.abc import Sequence
19
20
  from types import NotImplementedType
20
- from typing import Any, Protocol, Sequence
21
+ from typing import Any, Protocol
21
22
 
22
23
  import numpy as np
23
24
 
@@ -148,7 +149,7 @@ def has_mixture(val: Any, *, allow_decompose: bool = True) -> bool:
148
149
  return mixture(val, None) is not None
149
150
 
150
151
 
151
- def validate_mixture(supports_mixture: SupportsMixture):
152
+ def validate_mixture(supports_mixture: SupportsMixture) -> None:
152
153
  """Validates that the mixture's tuple are valid probabilities."""
153
154
  mixture_tuple = mixture(supports_mixture, None)
154
155
  if mixture_tuple is None:
@@ -93,7 +93,7 @@ class ReturnsMixtureOfReturnsUnitary:
93
93
  (ReturnsMixtureOfReturnsUnitary(), ((0.4, np.eye(2)), (0.6, np.eye(2)))),
94
94
  ),
95
95
  )
96
- def test_objects_with_mixture(val, mixture):
96
+ def test_objects_with_mixture(val, mixture) -> None:
97
97
  expected_keys, expected_values = zip(*mixture)
98
98
  keys, values = zip(*cirq.mixture(val))
99
99
  np.testing.assert_almost_equal(keys, expected_keys)
@@ -107,7 +107,7 @@ def test_objects_with_mixture(val, mixture):
107
107
  @pytest.mark.parametrize(
108
108
  'val', (NoMethod(), ReturnsNotImplemented(), ReturnsNotImplementedUnitary())
109
109
  )
110
- def test_objects_with_no_mixture(val):
110
+ def test_objects_with_no_mixture(val) -> None:
111
111
  with pytest.raises(TypeError, match="mixture"):
112
112
  _ = cirq.mixture(val)
113
113
  assert cirq.mixture(val, None) is None
@@ -116,7 +116,7 @@ def test_objects_with_no_mixture(val):
116
116
  assert cirq.mixture(val, default) == default
117
117
 
118
118
 
119
- def test_has_mixture():
119
+ def test_has_mixture() -> None:
120
120
  assert cirq.has_mixture(ReturnsValidTuple())
121
121
  assert not cirq.has_mixture(ReturnsNotImplemented())
122
122
  assert cirq.has_mixture(ReturnsMixtureButNoHasMixture())
@@ -124,7 +124,7 @@ def test_has_mixture():
124
124
  assert not cirq.has_mixture(ReturnsNotImplementedUnitary())
125
125
 
126
126
 
127
- def test_valid_mixture():
127
+ def test_valid_mixture() -> None:
128
128
  cirq.validate_mixture(ReturnsValidTuple())
129
129
 
130
130
 
@@ -136,11 +136,11 @@ def test_valid_mixture():
136
136
  (ReturnsGreaterThanUnityProbability(), 'greater than 1'),
137
137
  ),
138
138
  )
139
- def test_invalid_mixture(val, message):
139
+ def test_invalid_mixture(val, message) -> None:
140
140
  with pytest.raises(ValueError, match=message):
141
141
  cirq.validate_mixture(val)
142
142
 
143
143
 
144
- def test_missing_mixture():
144
+ def test_missing_mixture() -> None:
145
145
  with pytest.raises(TypeError, match='_mixture_'):
146
- cirq.validate_mixture(NoMethod)
146
+ cirq.validate_mixture(NoMethod) # type: ignore[arg-type]
@@ -52,7 +52,7 @@ class MulSevenRMulEight:
52
52
  return 8
53
53
 
54
54
 
55
- def test_equivalent_to_builtin_mul():
55
+ def test_equivalent_to_builtin_mul() -> None:
56
56
  test_vals = [
57
57
  0,
58
58
  1,
@@ -76,14 +76,14 @@ def test_equivalent_to_builtin_mul():
76
76
  c = cirq.mul(a, b, default=None)
77
77
  if c is None:
78
78
  with pytest.raises(TypeError):
79
- _ = a * b
79
+ _ = a * b # type: ignore[operator]
80
80
  with pytest.raises(TypeError):
81
81
  _ = cirq.mul(a, b)
82
82
  else:
83
- assert c == a * b
83
+ assert c == a * b # type: ignore[operator]
84
84
 
85
85
 
86
- def test_symbol_special_case():
86
+ def test_symbol_special_case() -> None:
87
87
  x = sympy.Symbol('x')
88
88
  assert cirq.mul(x, 1.0) is x
89
89
  assert cirq.mul(1.0, x) is x
@@ -14,7 +14,7 @@
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
- from typing import Any, Protocol, TypeVar
17
+ from typing import Any, overload, Protocol, TypeVar
18
18
 
19
19
  # This is a special value to indicate that a type error should be returned.
20
20
  # This is used within phase_by to raise an error if no underlying
@@ -24,6 +24,7 @@ from cirq._doc import doc_private
24
24
  RaiseTypeErrorIfNotProvided: Any = ([],)
25
25
 
26
26
  TDefault = TypeVar('TDefault')
27
+ T = TypeVar('T')
27
28
 
28
29
 
29
30
  class SupportsPhase(Protocol):
@@ -47,9 +48,17 @@ class SupportsPhase(Protocol):
47
48
  """
48
49
 
49
50
 
50
- def phase_by(
51
- val: Any, phase_turns: float, qubit_index: int, default: TDefault = RaiseTypeErrorIfNotProvided
52
- ):
51
+ @overload
52
+ def phase_by(val: T, phase_turns: float, qubit_index: int) -> T:
53
+ pass
54
+
55
+
56
+ @overload
57
+ def phase_by(val: T, phase_turns: float, qubit_index: int, default: TDefault) -> T | TDefault:
58
+ pass
59
+
60
+
61
+ def phase_by(val, phase_turns, qubit_index, default=RaiseTypeErrorIfNotProvided):
53
62
  """Returns a phased version of the effect.
54
63
 
55
64
  For example, an X gate phased by 90 degrees would be a Y gate.
@@ -16,7 +16,8 @@
16
16
 
17
17
  from __future__ import annotations
18
18
 
19
- from typing import Any, Callable, overload, TYPE_CHECKING, TypeVar
19
+ from collections.abc import Callable
20
+ from typing import Any, overload, TYPE_CHECKING, TypeVar
20
21
 
21
22
  if TYPE_CHECKING:
22
23
  import cirq
@@ -34,7 +34,7 @@ class ReturnsExponent:
34
34
 
35
35
 
36
36
  @pytest.mark.parametrize('val', (NoMethod(), 'text', object(), ReturnsNotImplemented()))
37
- def test_powerless(val):
37
+ def test_powerless(val) -> None:
38
38
  assert cirq.pow(val, 5, None) is None
39
39
  assert cirq.pow(val, 2, NotImplemented) is NotImplemented
40
40
 
@@ -42,13 +42,13 @@ def test_powerless(val):
42
42
  assert cirq.pow(val, 1, None) is None
43
43
 
44
44
 
45
- def test_pow_error():
45
+ def test_pow_error() -> None:
46
46
  with pytest.raises(TypeError, match="returned NotImplemented"):
47
- _ = cirq.pow(ReturnsNotImplemented(), 3)
47
+ _ = cirq.pow(ReturnsNotImplemented(), 3) # type: ignore[call-overload]
48
48
  with pytest.raises(TypeError, match="no __pow__ method"):
49
- _ = cirq.pow(NoMethod(), 3)
49
+ _ = cirq.pow(NoMethod(), 3) # type: ignore[call-overload]
50
50
 
51
51
 
52
52
  @pytest.mark.parametrize('val,exponent,out', ((ReturnsExponent(), 2, 2), (1, 2, 1), (2, 3, 8)))
53
- def test_pow_with_result(val, exponent, out):
53
+ def test_pow_with_result(val, exponent, out) -> None:
54
54
  assert cirq.pow(val, exponent) == cirq.pow(val, exponent, default=None) == val**exponent == out
cirq/protocols/qasm.py CHANGED
@@ -15,8 +15,9 @@
15
15
  from __future__ import annotations
16
16
 
17
17
  import string
18
+ from collections.abc import Iterable, Mapping
18
19
  from types import NotImplementedType
19
- from typing import Any, Iterable, Mapping, Protocol, TYPE_CHECKING, TypeVar
20
+ from typing import Any, Protocol, TYPE_CHECKING, TypeVar
20
21
 
21
22
  from cirq import ops
22
23
  from cirq._doc import doc_private
@@ -14,8 +14,9 @@
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
+ from collections.abc import Sequence
17
18
  from types import NotImplementedType
18
- from typing import Any, Protocol, Sequence, TypeVar
19
+ from typing import Any, Protocol, TypeVar
19
20
 
20
21
  from cirq import ops
21
22
  from cirq._doc import doc_private, document