cirq-core 1.1.0.dev20221219200817__py3-none-any.whl → 1.2.0__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 (229) hide show
  1. cirq/__init__.py +8 -0
  2. cirq/_compat.py +29 -4
  3. cirq/_compat_test.py +24 -26
  4. cirq/_version.py +32 -1
  5. cirq/_version_test.py +1 -1
  6. cirq/circuits/_block_diagram_drawer_test.py +4 -3
  7. cirq/circuits/circuit.py +109 -63
  8. cirq/circuits/circuit_operation.py +2 -3
  9. cirq/circuits/circuit_operation_test.py +4 -4
  10. cirq/circuits/circuit_test.py +11 -0
  11. cirq/circuits/frozen_circuit.py +13 -1
  12. cirq/circuits/frozen_circuit_test.py +5 -1
  13. cirq/circuits/moment.py +39 -14
  14. cirq/circuits/moment_test.py +7 -0
  15. cirq/circuits/text_diagram_drawer.py +1 -1
  16. cirq/circuits/text_diagram_drawer_test.py +3 -7
  17. cirq/conftest.py +8 -0
  18. cirq/contrib/acquaintance/bipartite.py +1 -1
  19. cirq/contrib/acquaintance/devices.py +2 -2
  20. cirq/contrib/acquaintance/executor.py +5 -2
  21. cirq/contrib/acquaintance/gates.py +3 -2
  22. cirq/contrib/acquaintance/permutation.py +13 -2
  23. cirq/contrib/acquaintance/testing.py +3 -5
  24. cirq/contrib/paulistring/recombine.py +3 -6
  25. cirq/contrib/qasm_import/_parser.py +17 -21
  26. cirq/contrib/qasm_import/_parser_test.py +30 -45
  27. cirq/contrib/qcircuit/qcircuit_test.py +3 -7
  28. cirq/contrib/quantum_volume/quantum_volume.py +3 -3
  29. cirq/contrib/quimb/mps_simulator.py +1 -1
  30. cirq/contrib/quimb/state_vector.py +2 -0
  31. cirq/contrib/quirk/quirk_gate.py +1 -0
  32. cirq/contrib/svg/svg.py +4 -7
  33. cirq/contrib/svg/svg_test.py +29 -1
  34. cirq/devices/grid_qubit.py +26 -28
  35. cirq/devices/grid_qubit_test.py +21 -5
  36. cirq/devices/line_qubit.py +10 -12
  37. cirq/devices/line_qubit_test.py +9 -2
  38. cirq/devices/named_topologies.py +1 -1
  39. cirq/devices/noise_model.py +4 -1
  40. cirq/devices/superconducting_qubits_noise_properties.py +1 -3
  41. cirq/experiments/n_qubit_tomography.py +1 -1
  42. cirq/experiments/qubit_characterizations.py +2 -2
  43. cirq/experiments/single_qubit_readout_calibration.py +1 -1
  44. cirq/experiments/t2_decay_experiment.py +1 -1
  45. cirq/experiments/xeb_simulation_test.py +2 -2
  46. cirq/interop/quirk/cells/testing.py +1 -1
  47. cirq/json_resolver_cache.py +1 -0
  48. cirq/linalg/__init__.py +2 -0
  49. cirq/linalg/decompositions_test.py +4 -4
  50. cirq/linalg/diagonalize_test.py +5 -6
  51. cirq/linalg/transformations.py +72 -9
  52. cirq/linalg/transformations_test.py +23 -7
  53. cirq/ops/__init__.py +4 -0
  54. cirq/ops/arithmetic_operation.py +4 -6
  55. cirq/ops/classically_controlled_operation.py +10 -3
  56. cirq/ops/clifford_gate.py +1 -7
  57. cirq/ops/common_channels.py +21 -15
  58. cirq/ops/common_gate_families.py +2 -3
  59. cirq/ops/common_gates.py +48 -11
  60. cirq/ops/common_gates_test.py +4 -0
  61. cirq/ops/controlled_gate.py +44 -18
  62. cirq/ops/controlled_operation.py +13 -5
  63. cirq/ops/dense_pauli_string.py +14 -19
  64. cirq/ops/diagonal_gate.py +3 -4
  65. cirq/ops/eigen_gate.py +8 -10
  66. cirq/ops/eigen_gate_test.py +6 -0
  67. cirq/ops/gate_operation.py +11 -6
  68. cirq/ops/gate_operation_test.py +11 -2
  69. cirq/ops/gateset.py +2 -1
  70. cirq/ops/gateset_test.py +38 -5
  71. cirq/ops/global_phase_op.py +28 -2
  72. cirq/ops/global_phase_op_test.py +21 -0
  73. cirq/ops/identity.py +1 -1
  74. cirq/ops/kraus_channel_test.py +2 -2
  75. cirq/ops/linear_combinations.py +7 -6
  76. cirq/ops/linear_combinations_test.py +26 -10
  77. cirq/ops/matrix_gates.py +8 -4
  78. cirq/ops/matrix_gates_test.py +25 -3
  79. cirq/ops/measure_util.py +13 -5
  80. cirq/ops/measure_util_test.py +8 -2
  81. cirq/ops/measurement_gate.py +1 -1
  82. cirq/ops/measurement_gate_test.py +9 -4
  83. cirq/ops/mixed_unitary_channel_test.py +4 -4
  84. cirq/ops/named_qubit.py +2 -4
  85. cirq/ops/parity_gates.py +5 -1
  86. cirq/ops/parity_gates_test.py +6 -0
  87. cirq/ops/pauli_gates.py +9 -9
  88. cirq/ops/pauli_string.py +4 -2
  89. cirq/ops/pauli_string_raw_types.py +4 -11
  90. cirq/ops/pauli_string_test.py +13 -13
  91. cirq/ops/pauli_sum_exponential.py +6 -1
  92. cirq/ops/qubit_manager.py +97 -0
  93. cirq/ops/qubit_manager_test.py +66 -0
  94. cirq/ops/raw_types.py +75 -33
  95. cirq/ops/raw_types_test.py +34 -0
  96. cirq/ops/three_qubit_gates.py +16 -10
  97. cirq/ops/three_qubit_gates_test.py +4 -2
  98. cirq/ops/two_qubit_diagonal_gate.py +3 -3
  99. cirq/ops/wait_gate.py +1 -1
  100. cirq/protocols/__init__.py +1 -0
  101. cirq/protocols/act_on_protocol.py +3 -3
  102. cirq/protocols/act_on_protocol_test.py +5 -5
  103. cirq/protocols/apply_channel_protocol.py +9 -8
  104. cirq/protocols/apply_mixture_protocol.py +8 -8
  105. cirq/protocols/apply_mixture_protocol_test.py +1 -1
  106. cirq/protocols/apply_unitary_protocol.py +66 -19
  107. cirq/protocols/apply_unitary_protocol_test.py +50 -0
  108. cirq/protocols/circuit_diagram_info_protocol.py +7 -9
  109. cirq/protocols/decompose_protocol.py +167 -125
  110. cirq/protocols/decompose_protocol_test.py +132 -2
  111. cirq/protocols/has_stabilizer_effect_protocol.py +2 -1
  112. cirq/protocols/inverse_protocol.py +2 -2
  113. cirq/protocols/json_serialization_test.py +3 -3
  114. cirq/protocols/json_test_data/Linspace.json +20 -7
  115. cirq/protocols/json_test_data/Linspace.repr +4 -1
  116. cirq/protocols/json_test_data/Points.json +19 -8
  117. cirq/protocols/json_test_data/Points.repr +4 -1
  118. cirq/protocols/json_test_data/Result.repr_inward +1 -1
  119. cirq/protocols/json_test_data/ResultDict.repr +1 -1
  120. cirq/protocols/json_test_data/ResultDict.repr_inward +1 -1
  121. cirq/protocols/json_test_data/TrialResult.repr_inward +1 -1
  122. cirq/protocols/json_test_data/XPowGate.json +13 -5
  123. cirq/protocols/json_test_data/XPowGate.repr +1 -1
  124. cirq/protocols/json_test_data/ZPowGate.json +13 -5
  125. cirq/protocols/json_test_data/ZPowGate.repr +1 -1
  126. cirq/protocols/json_test_data/ZipLongest.json +19 -0
  127. cirq/protocols/json_test_data/ZipLongest.repr +1 -0
  128. cirq/protocols/json_test_data/spec.py +1 -0
  129. cirq/protocols/kraus_protocol.py +3 -4
  130. cirq/protocols/measurement_key_protocol.py +3 -1
  131. cirq/protocols/mixture_protocol.py +3 -2
  132. cirq/protocols/phase_protocol.py +3 -3
  133. cirq/protocols/pow_protocol.py +1 -2
  134. cirq/protocols/qasm.py +4 -4
  135. cirq/protocols/qid_shape_protocol.py +8 -8
  136. cirq/protocols/resolve_parameters.py +8 -3
  137. cirq/protocols/resolve_parameters_test.py +3 -3
  138. cirq/protocols/unitary_protocol.py +19 -11
  139. cirq/protocols/unitary_protocol_test.py +37 -0
  140. cirq/qis/channels.py +1 -1
  141. cirq/qis/clifford_tableau.py +4 -5
  142. cirq/qis/quantum_state_representation.py +7 -9
  143. cirq/qis/states.py +21 -13
  144. cirq/qis/states_test.py +7 -0
  145. cirq/sim/clifford/clifford_simulator.py +3 -3
  146. cirq/sim/density_matrix_simulation_state.py +2 -1
  147. cirq/sim/density_matrix_simulator.py +1 -1
  148. cirq/sim/density_matrix_simulator_test.py +9 -5
  149. cirq/sim/density_matrix_utils.py +7 -32
  150. cirq/sim/mux.py +2 -2
  151. cirq/sim/simulation_state.py +58 -18
  152. cirq/sim/simulation_state_base.py +5 -2
  153. cirq/sim/simulation_state_test.py +121 -9
  154. cirq/sim/simulation_utils.py +59 -0
  155. cirq/sim/simulation_utils_test.py +32 -0
  156. cirq/sim/simulator.py +2 -1
  157. cirq/sim/simulator_base_test.py +3 -3
  158. cirq/sim/sparse_simulator.py +1 -1
  159. cirq/sim/sparse_simulator_test.py +5 -5
  160. cirq/sim/state_vector.py +7 -36
  161. cirq/sim/state_vector_simulation_state.py +18 -1
  162. cirq/sim/state_vector_simulator.py +3 -2
  163. cirq/sim/state_vector_simulator_test.py +24 -2
  164. cirq/sim/state_vector_test.py +46 -15
  165. cirq/study/__init__.py +1 -0
  166. cirq/study/flatten_expressions.py +2 -2
  167. cirq/study/resolver.py +2 -0
  168. cirq/study/resolver_test.py +1 -1
  169. cirq/study/result.py +1 -1
  170. cirq/study/sweeps.py +103 -9
  171. cirq/study/sweeps_test.py +64 -0
  172. cirq/testing/__init__.py +4 -0
  173. cirq/testing/circuit_compare.py +15 -18
  174. cirq/testing/consistent_act_on.py +4 -4
  175. cirq/testing/consistent_controlled_gate_op_test.py +1 -1
  176. cirq/testing/consistent_decomposition.py +11 -2
  177. cirq/testing/consistent_decomposition_test.py +8 -1
  178. cirq/testing/consistent_protocols.py +2 -0
  179. cirq/testing/consistent_protocols_test.py +8 -4
  180. cirq/testing/consistent_qasm.py +8 -15
  181. cirq/testing/consistent_specified_has_unitary.py +1 -1
  182. cirq/testing/consistent_unitary.py +85 -0
  183. cirq/testing/consistent_unitary_test.py +96 -0
  184. cirq/testing/equivalent_repr_eval.py +10 -10
  185. cirq/testing/json.py +3 -3
  186. cirq/testing/logs.py +1 -1
  187. cirq/testing/order_tester.py +4 -5
  188. cirq/testing/random_circuit.py +3 -5
  189. cirq/testing/sample_gates.py +79 -0
  190. cirq/testing/sample_gates_test.py +59 -0
  191. cirq/transformers/__init__.py +2 -0
  192. cirq/transformers/analytical_decompositions/__init__.py +8 -0
  193. cirq/transformers/analytical_decompositions/pauli_string_decomposition.py +130 -0
  194. cirq/transformers/analytical_decompositions/pauli_string_decomposition_test.py +58 -0
  195. cirq/transformers/analytical_decompositions/quantum_shannon_decomposition.py +230 -0
  196. cirq/transformers/analytical_decompositions/quantum_shannon_decomposition_test.py +112 -0
  197. cirq/transformers/analytical_decompositions/three_qubit_decomposition_test.py +1 -3
  198. cirq/transformers/analytical_decompositions/two_qubit_to_fsim.py +1 -1
  199. cirq/transformers/expand_composite.py +1 -1
  200. cirq/transformers/heuristic_decompositions/gate_tabulation_math_utils.py +4 -4
  201. cirq/transformers/measurement_transformers.py +4 -4
  202. cirq/transformers/merge_single_qubit_gates.py +17 -4
  203. cirq/transformers/routing/route_circuit_cqc.py +2 -2
  204. cirq/transformers/stratify.py +125 -62
  205. cirq/transformers/stratify_test.py +20 -16
  206. cirq/transformers/transformer_api.py +1 -1
  207. cirq/transformers/transformer_primitives.py +3 -2
  208. cirq/transformers/transformer_primitives_test.py +11 -0
  209. cirq/value/abc_alt.py +3 -2
  210. cirq/value/abc_alt_test.py +1 -0
  211. cirq/value/classical_data.py +10 -10
  212. cirq/value/digits.py +2 -2
  213. cirq/value/linear_dict.py +18 -19
  214. cirq/value/product_state.py +7 -6
  215. cirq/value/value_equality_attr.py +2 -2
  216. cirq/vis/heatmap.py +1 -1
  217. cirq/vis/heatmap_test.py +2 -2
  218. cirq/work/collector.py +2 -2
  219. cirq/work/observable_measurement_data.py +5 -5
  220. cirq/work/observable_readout_calibration.py +3 -1
  221. cirq/work/observable_settings.py +1 -1
  222. cirq/work/pauli_sum_collector.py +9 -8
  223. cirq/work/sampler.py +2 -0
  224. cirq/work/zeros_sampler.py +2 -2
  225. {cirq_core-1.1.0.dev20221219200817.dist-info → cirq_core-1.2.0.dist-info}/METADATA +7 -15
  226. {cirq_core-1.1.0.dev20221219200817.dist-info → cirq_core-1.2.0.dist-info}/RECORD +229 -215
  227. {cirq_core-1.1.0.dev20221219200817.dist-info → cirq_core-1.2.0.dist-info}/WHEEL +1 -1
  228. {cirq_core-1.1.0.dev20221219200817.dist-info → cirq_core-1.2.0.dist-info}/LICENSE +0 -0
  229. {cirq_core-1.1.0.dev20221219200817.dist-info → cirq_core-1.2.0.dist-info}/top_level.txt +0 -0
@@ -1 +1,4 @@
1
- cirq.Points('a', [0, 0.4])
1
+ [
2
+ cirq.Points('a', [0, 0.4]),
3
+ cirq.Points('amp', [0, 1], metadata='used to turn amp on or off'),
4
+ ]
@@ -1 +1 @@
1
- [cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[True, True, False, True, False], [False, True, True, False, False], [True, False, True, False, True]], dtype=bool)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.uint8), 'n': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int64)})]
1
+ [cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[True, True, False, True, False], [False, True, True, False, False], [True, False, True, False, True]], dtype=np.dtype('bool'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.uint8), 'n': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int64)})]
@@ -1 +1 @@
1
- [cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[True, True, False, True, False]], [[False, True, True, False, False]], [[True, False, True, False, True]]], dtype=bool)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[1, 1, 0, 1, 0]], [[0, 1, 1, 0, 0]], [[1, 0, 1, 0, 1]]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.int8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.int16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.int32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.int64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.uint16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.uint32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.uint64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[1, 1, 0, 1, 0]], [[0, 1, 1, 0, 0]], [[1, 0, 1, 0, 1]]], dtype=np.uint8), 'n': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.int64)})]
1
+ [cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[True, True, False, True, False]], [[False, True, True, False, False]], [[True, False, True, False, True]]], dtype=np.dtype('bool'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[1, 1, 0, 1, 0]], [[0, 1, 1, 0, 0]], [[1, 0, 1, 0, 1]]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.int8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.int16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.int32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.int64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.uint16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.uint32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.uint64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[1, 1, 0, 1, 0]], [[0, 1, 1, 0, 0]], [[1, 0, 1, 0, 1]]], dtype=np.uint8), 'n': np.array([[[0, 1, 2]], [[3, 4, 5]], [[6, 7, 8]]], dtype=np.int64)})]
@@ -1 +1 @@
1
- [cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[True, True, False, True, False], [False, True, True, False, False], [True, False, True, False, True]], dtype=bool)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.uint8), 'n': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int64)})]
1
+ [cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[True, True, False, True, False], [False, True, True, False, False], [True, False, True, False, True]], dtype=np.dtype('bool'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.uint8), 'n': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int64)})]
@@ -1 +1 @@
1
- [cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[True, True, False, True, False], [False, True, True, False, False], [True, False, True, False, True]], dtype=np.bool)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint8)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint16)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint32)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.uint64)}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.uint8), 'n': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int64)})]
1
+ [cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[True, True, False, True, False], [False, True, True, False, False], [True, False, True, False, True]], dtype=np.dtype('bool'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.dtype('uint8'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.dtype('int8'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.dtype('int16'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.dtype('int32'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.dtype('int64'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.dtype('uint8'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.dtype('uint16'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.dtype('uint32'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.dtype('uint64'))}), cirq.ResultDict(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), measurements={'m': np.array([[1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1]], dtype=np.dtype('uint8')), 'n': np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.dtype('int64'))})]
@@ -1,5 +1,13 @@
1
- {
2
- "cirq_type": "XPowGate",
3
- "exponent": 0.123,
4
- "global_shift": 0.0
5
- }
1
+ [
2
+ {
3
+ "cirq_type": "XPowGate",
4
+ "exponent": 0.123,
5
+ "global_shift": 0.0
6
+ },
7
+ {
8
+ "cirq_type": "XPowGate",
9
+ "exponent": 0.123,
10
+ "global_shift": 0.0,
11
+ "dimension": 3
12
+ }
13
+ ]
@@ -1 +1 @@
1
- (cirq.X**0.123)
1
+ [(cirq.X**0.123), cirq.XPowGate(exponent=0.123, dimension=3)]
@@ -1,5 +1,13 @@
1
- {
2
- "cirq_type": "ZPowGate",
3
- "exponent": 0.789,
4
- "global_shift": 0.0
5
- }
1
+ [
2
+ {
3
+ "cirq_type": "ZPowGate",
4
+ "exponent": 0.789,
5
+ "global_shift": 0.0
6
+ },
7
+ {
8
+ "cirq_type": "ZPowGate",
9
+ "exponent": 0.789,
10
+ "global_shift": 0.0,
11
+ "dimension": 3
12
+ }
13
+ ]
@@ -1 +1 @@
1
- (cirq.Z**0.789)
1
+ [(cirq.Z**0.789), cirq.ZPowGate(exponent=0.789, dimension=3)]
@@ -0,0 +1,19 @@
1
+ {
2
+ "cirq_type": "ZipLongest",
3
+ "sweeps": [
4
+ {
5
+ "cirq_type": "Linspace",
6
+ "key": "a",
7
+ "start": 0,
8
+ "stop": 1,
9
+ "length": 2
10
+ },
11
+ {
12
+ "cirq_type": "Linspace",
13
+ "key": "b",
14
+ "start": 0,
15
+ "stop": 2,
16
+ "length": 4
17
+ }
18
+ ]
19
+ }
@@ -0,0 +1 @@
1
+ cirq.ZipLongest(cirq.Linspace('a', start=0, stop=1, length=2), cirq.Linspace('b', start=0, stop=2, length=4))
@@ -81,6 +81,7 @@ TestSpec = ModuleJsonTestSpec(
81
81
  'MEASUREMENT_KEY_SEPARATOR',
82
82
  'PointOptimizer',
83
83
  # Transformers
84
+ 'DecompositionContext',
84
85
  'TransformerLogger',
85
86
  'TransformerContext',
86
87
  # Routing utilities
@@ -164,13 +164,12 @@ def kraus(
164
164
 
165
165
  if kraus_getter is None and unitary_getter is None and mixture_getter is None:
166
166
  raise TypeError(
167
- "object of type '{}' has no _kraus_ or _mixture_ or "
168
- "_unitary_ method.".format(type(val))
167
+ f"object of type '{type(val)}' has no _kraus_ or _mixture_ or _unitary_ method."
169
168
  )
170
169
 
171
170
  raise TypeError(
172
- "object of type '{}' does have a _kraus_, _mixture_ or "
173
- "_unitary_ method, but it returned NotImplemented.".format(type(val))
171
+ f"object of type '{type(val)}' does have a _kraus_, _mixture_ or "
172
+ "_unitary_ method, but it returned NotImplemented."
174
173
  )
175
174
 
176
175
 
@@ -316,7 +316,9 @@ def with_key_path_prefix(val: Any, prefix: Tuple[str, ...]):
316
316
 
317
317
 
318
318
  def with_rescoped_keys(
319
- val: Any, path: Tuple[str, ...], bindable_keys: FrozenSet['cirq.MeasurementKey'] = None
319
+ val: Any,
320
+ path: Tuple[str, ...],
321
+ bindable_keys: Optional[FrozenSet['cirq.MeasurementKey']] = None,
320
322
  ):
321
323
  """Rescopes any measurement and control keys to the provided path, given the existing keys.
322
324
 
@@ -11,6 +11,7 @@
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
  """Protocol for objects that are mixtures (probabilistic combinations)."""
15
16
  from typing import Any, Sequence, Tuple, Union
16
17
 
@@ -103,8 +104,8 @@ def mixture(
103
104
  raise TypeError(f"object of type '{type(val)}' has no _mixture_ or _unitary_ method.")
104
105
 
105
106
  raise TypeError(
106
- "object of type '{}' does have a _mixture_ or _unitary_ "
107
- "method, but it returned NotImplemented.".format(type(val))
107
+ f"object of type '{type(val)}' does have a _mixture_ or _unitary_ "
108
+ "method, but it returned NotImplemented."
108
109
  )
109
110
 
110
111
 
@@ -30,7 +30,7 @@ class SupportsPhase(Protocol):
30
30
  """An effect that can be phased around the Z axis of target qubits."""
31
31
 
32
32
  @doc_private
33
- def _phase_by_(self: Any, phase_turns: float, qubit_index: int):
33
+ def _phase_by_(self, phase_turns: float, qubit_index: int):
34
34
  """Returns a phased version of the effect.
35
35
 
36
36
  Specifically, returns an object with matrix P U P^-1 (up to global
@@ -88,6 +88,6 @@ def phase_by(
88
88
  if getter is None:
89
89
  raise TypeError(f"object of type '{type(val)}' has no _phase_by_ method.")
90
90
  raise TypeError(
91
- "object of type '{}' does have a _phase_by_ method, "
92
- "but it returned NotImplemented.".format(type(val))
91
+ f"object of type '{type(val)}' does have a _phase_by_ method, "
92
+ "but it returned NotImplemented."
93
93
  )
@@ -94,8 +94,7 @@ def pow(val: Any, exponent: Any, default: Any = RaiseTypeErrorIfNotProvided) ->
94
94
  if raiser is None:
95
95
  raise TypeError(f"object of type '{type(val)}' has no __pow__ method.")
96
96
  raise TypeError(
97
- "object of type '{}' does have a __pow__ method, "
98
- "but it returned NotImplemented.".format(type(val))
97
+ f"object of type '{type(val)}' does have a __pow__ method, but it returned NotImplemented."
99
98
  )
100
99
 
101
100
 
cirq/protocols/qasm.py CHANGED
@@ -36,8 +36,8 @@ class QasmArgs(string.Formatter):
36
36
  self,
37
37
  precision: int = 10,
38
38
  version: str = '2.0',
39
- qubit_id_map: Dict['cirq.Qid', str] = None,
40
- meas_key_id_map: Dict[str, str] = None,
39
+ qubit_id_map: Optional[Dict['cirq.Qid', str]] = None,
40
+ meas_key_id_map: Optional[Dict[str, str]] = None,
41
41
  ) -> None:
42
42
  """Inits QasmArgs.
43
43
 
@@ -172,8 +172,8 @@ def qasm(
172
172
  if method is None:
173
173
  raise TypeError(f"object of type '{type(val)}' has no _qasm_ method.")
174
174
  raise TypeError(
175
- "object of type '{}' does have a _qasm_ method, "
176
- "but it returned NotImplemented or None.".format(type(val))
175
+ f"object of type '{type(val)}' does have a _qasm_ method, "
176
+ "but it returned NotImplemented or None."
177
177
  )
178
178
 
179
179
 
@@ -123,13 +123,13 @@ def qid_shape(
123
123
 
124
124
  if getter is not None:
125
125
  raise TypeError(
126
- "object of type '{}' does have a _qid_shape_ method, "
127
- "but it returned NotImplemented.".format(type(val))
126
+ f"object of type '{type(val)}' does have a _qid_shape_ method, "
127
+ "but it returned NotImplemented."
128
128
  )
129
129
  if num_getter is not None:
130
130
  raise TypeError(
131
- "object of type '{}' does have a _num_qubits_ method, "
132
- "but it returned NotImplemented.".format(type(val))
131
+ f"object of type '{type(val)}' does have a _num_qubits_ method, "
132
+ "but it returned NotImplemented."
133
133
  )
134
134
  raise TypeError(f"object of type '{type(val)}' has no _num_qubits_ or _qid_shape_ methods.")
135
135
 
@@ -178,12 +178,12 @@ def num_qubits(
178
178
 
179
179
  if num_getter is not None:
180
180
  raise TypeError(
181
- "object of type '{}' does have a _num_qubits_ method, "
182
- "but it returned NotImplemented.".format(type(val))
181
+ f"object of type '{type(val)}' does have a _num_qubits_ method, "
182
+ "but it returned NotImplemented."
183
183
  )
184
184
  if getter is not None:
185
185
  raise TypeError(
186
- "object of type '{}' does have a _qid_shape_ method, "
187
- "but it returned NotImplemented.".format(type(val))
186
+ f"object of type '{type(val)}' does have a _qid_shape_ method, "
187
+ "but it returned NotImplemented."
188
188
  )
189
189
  raise TypeError(f"object of type '{type(val)}' has no _num_qubits_ or _qid_shape_ methods.")
@@ -14,6 +14,7 @@
14
14
 
15
15
  import numbers
16
16
  from typing import AbstractSet, Any, cast, TYPE_CHECKING, TypeVar
17
+ from typing_extensions import Self
17
18
 
18
19
  import sympy
19
20
  from typing_extensions import Protocol
@@ -33,13 +34,13 @@ class SupportsParameterization(Protocol):
33
34
  via a ParamResolver"""
34
35
 
35
36
  @doc_private
36
- def _is_parameterized_(self: Any) -> bool:
37
+ def _is_parameterized_(self) -> bool:
37
38
  """Whether the object is parameterized by any Symbols that require
38
39
  resolution. Returns True if the object has any unresolved Symbols
39
40
  and False otherwise."""
40
41
 
41
42
  @doc_private
42
- def _parameter_names_(self: Any) -> AbstractSet[str]:
43
+ def _parameter_names_(self) -> AbstractSet[str]:
43
44
  """Returns a collection of string names of parameters that require
44
45
  resolution. If _is_parameterized_ is False, the collection is empty.
45
46
  The converse is not necessarily true, because some objects may report
@@ -48,7 +49,7 @@ class SupportsParameterization(Protocol):
48
49
  """
49
50
 
50
51
  @doc_private
51
- def _resolve_parameters_(self: T, resolver: 'cirq.ParamResolver', recursive: bool) -> T:
52
+ def _resolve_parameters_(self, resolver: 'cirq.ParamResolver', recursive: bool) -> Self:
52
53
  """Resolve the parameters in the effect."""
53
54
 
54
55
 
@@ -177,6 +178,10 @@ def resolve_parameters(
177
178
  if isinstance(val, (list, tuple)):
178
179
  return cast(T, type(val)(resolve_parameters(e, param_resolver, recursive) for e in val))
179
180
 
181
+ is_parameterized = getattr(val, '_is_parameterized_', None)
182
+ if is_parameterized is not None and not is_parameterized():
183
+ return val
184
+
180
185
  getter = getattr(val, '_resolve_parameters_', None)
181
186
  if getter is None:
182
187
  result = NotImplemented
@@ -35,7 +35,7 @@ def test_resolve_parameters(resolve_fn):
35
35
  self.parameter = var
36
36
 
37
37
  def _is_parameterized_(self) -> bool:
38
- return self.parameter == 0
38
+ return self.parameter != 0
39
39
 
40
40
  def _resolve_parameters_(self, resolver: ParamResolver, recursive: bool):
41
41
  self.parameter = resolver.value_of(self.parameter, recursive)
@@ -43,8 +43,8 @@ def test_resolve_parameters(resolve_fn):
43
43
 
44
44
  assert not cirq.is_parameterized(NoMethod())
45
45
  assert not cirq.is_parameterized(ReturnsNotImplemented())
46
- assert not cirq.is_parameterized(SimpleParameterSwitch('a'))
47
- assert cirq.is_parameterized(SimpleParameterSwitch(0))
46
+ assert cirq.is_parameterized(SimpleParameterSwitch('a'))
47
+ assert not cirq.is_parameterized(SimpleParameterSwitch(0))
48
48
 
49
49
  ni = ReturnsNotImplemented()
50
50
  d = {'a': 0}
@@ -17,7 +17,6 @@ from typing import Any, TypeVar, Union, Optional
17
17
  import numpy as np
18
18
  from typing_extensions import Protocol
19
19
 
20
- from cirq import qis
21
20
  from cirq._doc import doc_private
22
21
  from cirq.protocols import qid_shape_protocol
23
22
  from cirq.protocols.apply_unitary_protocol import ApplyUnitaryArgs, apply_unitaries
@@ -128,8 +127,8 @@ def unitary(
128
127
  "cirq.unitary failed. "
129
128
  "Value doesn't have a (non-parameterized) unitary effect.\n"
130
129
  "\n"
131
- "type: {}\n"
132
- "value: {!r}\n"
130
+ f"type: {type(val)}\n"
131
+ f"value: {val!r}\n"
133
132
  "\n"
134
133
  "The value failed to satisfy any of the following criteria:\n"
135
134
  "- A `_unitary_(self)` method that returned a value "
@@ -137,7 +136,7 @@ def unitary(
137
136
  "- A `_decompose_(self)` method that returned a "
138
137
  "list of unitary operations.\n"
139
138
  "- An `_apply_unitary_(self, args) method that returned a value "
140
- "besides None or NotImplemented.".format(type(val), val)
139
+ "besides None or NotImplemented."
141
140
  )
142
141
 
143
142
 
@@ -162,9 +161,7 @@ def _strat_unitary_from_apply_unitary(val: Any) -> Optional[np.ndarray]:
162
161
  return NotImplemented
163
162
 
164
163
  # Apply unitary effect to an identity matrix.
165
- state = qis.eye_tensor(val_qid_shape, dtype=np.complex128)
166
- buffer = np.empty_like(state)
167
- result = method(ApplyUnitaryArgs(state, buffer, range(len(val_qid_shape))))
164
+ result = method(ApplyUnitaryArgs.for_unitary(qid_shape=val_qid_shape))
168
165
 
169
166
  if result is NotImplemented or result is None:
170
167
  return result
@@ -179,15 +176,26 @@ def _strat_unitary_from_decompose(val: Any) -> Optional[np.ndarray]:
179
176
  if operations is None:
180
177
  return NotImplemented
181
178
 
179
+ all_qubits = frozenset(q for op in operations for q in op.qubits)
180
+ work_qubits = frozenset(qubits)
181
+ ancillas = tuple(sorted(all_qubits.difference(work_qubits)))
182
+
183
+ ordered_qubits = ancillas + tuple(qubits)
184
+ val_qid_shape = qid_shape_protocol.qid_shape(ancillas) + val_qid_shape
185
+
182
186
  # Apply sub-operations' unitary effects to an identity matrix.
183
- state = qis.eye_tensor(val_qid_shape, dtype=np.complex128)
184
- buffer = np.empty_like(state)
185
187
  result = apply_unitaries(
186
- operations, qubits, ApplyUnitaryArgs(state, buffer, range(len(val_qid_shape))), None
188
+ operations, ordered_qubits, ApplyUnitaryArgs.for_unitary(qid_shape=val_qid_shape), None
187
189
  )
188
190
 
189
191
  # Package result.
190
192
  if result is None:
191
193
  return None
194
+
192
195
  state_len = np.prod(val_qid_shape, dtype=np.int64)
193
- return result.reshape((state_len, state_len))
196
+ result = result.reshape((state_len, state_len))
197
+ # Assuming borrowable qubits are restored to their original state and
198
+ # clean qubits restord to the zero state then the desired unitary is
199
+ # the upper left square.
200
+ work_state_len = np.prod(val_qid_shape[len(ancillas) :], dtype=np.int64)
201
+ return result[:work_state_len, :work_state_len]
@@ -17,6 +17,7 @@ import numpy as np
17
17
  import pytest
18
18
 
19
19
  import cirq
20
+ from cirq import testing
20
21
 
21
22
  m0: np.ndarray = np.array([])
22
23
  # yapf: disable
@@ -188,6 +189,42 @@ def test_has_unitary():
188
189
  assert not cirq.has_unitary(FullyImplemented(False))
189
190
 
190
191
 
192
+ def _test_gate_that_allocates_qubits(gate):
193
+ from cirq.protocols.unitary_protocol import _strat_unitary_from_decompose
194
+
195
+ op = gate.on(*cirq.LineQubit.range(cirq.num_qubits(gate)))
196
+ moment = cirq.Moment(op)
197
+ circuit = cirq.FrozenCircuit(op)
198
+ circuit_op = cirq.CircuitOperation(circuit)
199
+ for val in [gate, op, moment, circuit, circuit_op]:
200
+ unitary_from_strat = _strat_unitary_from_decompose(val)
201
+ assert unitary_from_strat is not None
202
+ np.testing.assert_allclose(unitary_from_strat, gate.narrow_unitary())
203
+
204
+
205
+ @pytest.mark.parametrize('theta', np.linspace(0, 2 * np.pi, 10))
206
+ @pytest.mark.parametrize('phase_state', [0, 1])
207
+ @pytest.mark.parametrize('target_bitsize', [1, 2, 3])
208
+ @pytest.mark.parametrize('ancilla_bitsize', [1, 4])
209
+ def test_decompose_gate_that_allocates_clean_qubits(
210
+ theta: float, phase_state: int, target_bitsize: int, ancilla_bitsize: int
211
+ ):
212
+
213
+ gate = testing.PhaseUsingCleanAncilla(theta, phase_state, target_bitsize, ancilla_bitsize)
214
+ _test_gate_that_allocates_qubits(gate)
215
+
216
+
217
+ @pytest.mark.parametrize('phase_state', [0, 1])
218
+ @pytest.mark.parametrize('target_bitsize', [1, 2, 3])
219
+ @pytest.mark.parametrize('ancilla_bitsize', [1, 4])
220
+ def test_decompose_gate_that_allocates_dirty_qubits(
221
+ phase_state: int, target_bitsize: int, ancilla_bitsize: int
222
+ ):
223
+
224
+ gate = testing.PhaseUsingDirtyAncilla(phase_state, target_bitsize, ancilla_bitsize)
225
+ _test_gate_that_allocates_qubits(gate)
226
+
227
+
191
228
  def test_decompose_and_get_unitary():
192
229
  from cirq.protocols.unitary_protocol import _strat_unitary_from_decompose
193
230
 
cirq/qis/channels.py CHANGED
@@ -51,7 +51,7 @@ def kraus_to_choi(kraus_operators: Sequence[np.ndarray]) -> np.ndarray:
51
51
  """
52
52
  d = np.prod(kraus_operators[0].shape, dtype=np.int64)
53
53
  choi_rank = len(kraus_operators)
54
- k = np.reshape(kraus_operators, (choi_rank, d))
54
+ k = np.reshape(np.asarray(kraus_operators), (choi_rank, d))
55
55
  return np.einsum('bi,bj->ij', k, k.conj())
56
56
 
57
57
 
@@ -164,7 +164,7 @@ class CliffordTableau(StabilizerState):
164
164
  def _reconstruct_rs(self, rs: Optional[np.ndarray]) -> np.ndarray:
165
165
  if rs is None:
166
166
  new_rs = np.zeros(2 * self.n + 1, dtype=bool)
167
- for (i, val) in enumerate(
167
+ for i, val in enumerate(
168
168
  big_endian_int_to_digits(self.initial_state, digit_count=self.n, base=2)
169
169
  ):
170
170
  new_rs[self.n + i] = bool(val)
@@ -203,7 +203,6 @@ class CliffordTableau(StabilizerState):
203
203
  return new_xs
204
204
 
205
205
  def _reconstruct_zs(self, zs: Optional[np.ndarray]) -> np.ndarray:
206
-
207
206
  if zs is None:
208
207
  new_zs = np.zeros((2 * self.n + 1, self.n), dtype=bool)
209
208
  for i in range(self.n):
@@ -338,11 +337,11 @@ class CliffordTableau(StabilizerState):
338
337
 
339
338
  for k in range(self.n):
340
339
  if self.xs[i, k] & (not self.zs[i, k]):
341
- string += 'X%d' % k
340
+ string += f'X{k}'
342
341
  elif (not self.xs[i, k]) & self.zs[i, k]:
343
- string += 'Z%d' % k
342
+ string += f'Z{k}'
344
343
  elif self.xs[i, k] & self.zs[i, k]:
345
- string += 'Y%d' % k
344
+ string += f'Y{k}'
346
345
  else:
347
346
  string += ' '
348
347
 
@@ -13,7 +13,9 @@
13
13
  # limitations under the License.
14
14
 
15
15
  import abc
16
- from typing import List, Sequence, Tuple, TYPE_CHECKING, TypeVar
16
+ from typing import List, Sequence, Tuple, TYPE_CHECKING
17
+ from typing_extensions import Self
18
+
17
19
  import numpy as np
18
20
 
19
21
  from cirq import value
@@ -21,12 +23,10 @@ from cirq import value
21
23
  if TYPE_CHECKING:
22
24
  import cirq
23
25
 
24
- TSelf = TypeVar('TSelf', bound='QuantumStateRepresentation')
25
-
26
26
 
27
27
  class QuantumStateRepresentation(metaclass=abc.ABCMeta):
28
28
  @abc.abstractmethod
29
- def copy(self: TSelf, deep_copy_buffers: bool = True) -> TSelf:
29
+ def copy(self, deep_copy_buffers: bool = True) -> Self:
30
30
  """Creates a copy of the object.
31
31
  Args:
32
32
  deep_copy_buffers: If True, buffers will also be deep-copied.
@@ -71,17 +71,15 @@ class QuantumStateRepresentation(metaclass=abc.ABCMeta):
71
71
  measurements.append(state.measure(axes, prng))
72
72
  return np.array(measurements, dtype=np.uint8)
73
73
 
74
- def kron(self: TSelf, other: TSelf) -> TSelf:
74
+ def kron(self, other: Self) -> Self:
75
75
  """Joins two state spaces together."""
76
76
  raise NotImplementedError()
77
77
 
78
- def factor(
79
- self: TSelf, axes: Sequence[int], *, validate=True, atol=1e-07
80
- ) -> Tuple[TSelf, TSelf]:
78
+ def factor(self, axes: Sequence[int], *, validate=True, atol=1e-07) -> Tuple[Self, Self]:
81
79
  """Splits two state spaces after a measurement or reset."""
82
80
  raise NotImplementedError()
83
81
 
84
- def reindex(self: TSelf, axes: Sequence[int]) -> TSelf:
82
+ def reindex(self, axes: Sequence[int]) -> Self:
85
83
  """Physically reindexes the state by the new basis.
86
84
  Args:
87
85
  axes: The desired axis order.
cirq/qis/states.py CHANGED
@@ -11,6 +11,7 @@
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
  """Classes and methods for quantum states."""
15
16
 
16
17
  from typing import Any, cast, Iterable, List, Optional, Sequence, Set, TYPE_CHECKING, Tuple, Union
@@ -714,10 +715,21 @@ def dirac_notation(
714
715
  Returns:
715
716
  A pretty string consisting of a sum of computational basis kets
716
717
  and non-zero floats of the specified accuracy.
718
+
719
+ Raises:
720
+ ValueError: If there is a shape mismatch between state_vector and qid_shape.
721
+ Otherwise, when qid_shape is not mentioned and length of state_vector
722
+ is not a power of 2.
717
723
  """
718
724
  if qid_shape is None:
719
725
  qid_shape = (2,) * (len(state_vector).bit_length() - 1)
720
726
 
727
+ if len(state_vector) != np.prod(qid_shape, dtype=np.int64):
728
+ raise ValueError(
729
+ 'state_vector has incorrect size. '
730
+ f'Expected {np.prod(qid_shape, dtype=np.int64)} but was {len(state_vector)}.'
731
+ )
732
+
721
733
  digit_separator = '' if max(qid_shape, default=0) < 10 else ','
722
734
  perm_list = [
723
735
  digit_separator.join(seq)
@@ -808,8 +820,8 @@ def to_valid_state_vector(
808
820
  num_qubits = len(qid_shape)
809
821
  if num_qubits != len(qid_shape):
810
822
  raise ValueError(
811
- 'num_qubits != len(qid_shape). num_qubits is <{!r}>. '
812
- 'qid_shape is <{!r}>.'.format(num_qubits, qid_shape)
823
+ f'num_qubits != len(qid_shape). num_qubits is <{num_qubits!r}>. '
824
+ f'qid_shape is <{qid_shape!r}>.'
813
825
  )
814
826
 
815
827
  if isinstance(state_rep, np.ndarray):
@@ -821,7 +833,6 @@ def to_valid_state_vector(
821
833
  def _qudit_values_to_state_tensor(
822
834
  *, state_vector: np.ndarray, qid_shape: Tuple[int, ...], dtype: Optional['DTypeLike']
823
835
  ) -> np.ndarray:
824
-
825
836
  for i in range(len(qid_shape)):
826
837
  s = state_vector[i]
827
838
  q = qid_shape[i]
@@ -871,15 +882,12 @@ def validate_normalized_state_vector(
871
882
  """
872
883
  if dtype and state_vector.dtype != dtype:
873
884
  raise ValueError(
874
- 'state_vector has invalid dtype. Expected {} but was {}'.format(
875
- dtype, state_vector.dtype
876
- )
885
+ f'state_vector has invalid dtype. Expected {dtype} but was {state_vector.dtype}'
877
886
  )
878
887
  if state_vector.size != np.prod(qid_shape, dtype=np.int64):
879
888
  raise ValueError(
880
- 'state_vector has incorrect size. Expected {} but was {}.'.format(
881
- np.prod(qid_shape, dtype=np.int64), state_vector.size
882
- )
889
+ 'state_vector has incorrect size. '
890
+ f'Expected {np.prod(qid_shape, dtype=np.int64)} but was {state_vector.size}.'
883
891
  )
884
892
  norm = np.sum(np.abs(state_vector) ** 2)
885
893
  if not np.isclose(norm, 1, atol=atol):
@@ -904,8 +912,8 @@ def validate_qid_shape(
904
912
  qid_shape = (2,) * (size.bit_length() - 1)
905
913
  if size != np.prod(qid_shape, dtype=np.int64):
906
914
  raise ValueError(
907
- 'state_vector.size ({}) is not a power of two or is not a product '
908
- 'of the qid shape {!r}.'.format(size, qid_shape)
915
+ f'state_vector.size ({size}) is not a power of two or is not a product '
916
+ f'of the qid shape {qid_shape!r}.'
909
917
  )
910
918
  return qid_shape
911
919
 
@@ -1031,8 +1039,8 @@ def _qid_shape_from_args(
1031
1039
  return (2,) * num_qubits
1032
1040
  if len(qid_shape) != num_qubits:
1033
1041
  raise ValueError(
1034
- 'num_qubits != len(qid_shape). num_qubits was {!r}. '
1035
- 'qid_shape was {!r}.'.format(num_qubits, qid_shape)
1042
+ f'num_qubits != len(qid_shape). num_qubits was {num_qubits!r}. '
1043
+ f'qid_shape was {qid_shape!r}.'
1036
1044
  )
1037
1045
  return qid_shape
1038
1046