qiskit 2.0.3__cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.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 (690) hide show
  1. qiskit/VERSION.txt +1 -0
  2. qiskit/__init__.py +141 -0
  3. qiskit/_accelerate.abi3.so +0 -0
  4. qiskit/_numpy_compat.py +73 -0
  5. qiskit/circuit/__init__.py +1343 -0
  6. qiskit/circuit/_add_control.py +312 -0
  7. qiskit/circuit/_classical_resource_map.py +150 -0
  8. qiskit/circuit/_standard_gates_commutations.py +3849 -0
  9. qiskit/circuit/_utils.py +167 -0
  10. qiskit/circuit/annotated_operation.py +279 -0
  11. qiskit/circuit/barrier.py +46 -0
  12. qiskit/circuit/classical/__init__.py +41 -0
  13. qiskit/circuit/classical/expr/__init__.py +266 -0
  14. qiskit/circuit/classical/expr/constructors.py +764 -0
  15. qiskit/circuit/classical/expr/expr.py +498 -0
  16. qiskit/circuit/classical/expr/visitors.py +375 -0
  17. qiskit/circuit/classical/types/__init__.py +113 -0
  18. qiskit/circuit/classical/types/ordering.py +229 -0
  19. qiskit/circuit/classical/types/types.py +153 -0
  20. qiskit/circuit/commutation_checker.py +133 -0
  21. qiskit/circuit/commutation_library.py +20 -0
  22. qiskit/circuit/controlflow/__init__.py +59 -0
  23. qiskit/circuit/controlflow/_builder_utils.py +211 -0
  24. qiskit/circuit/controlflow/box.py +163 -0
  25. qiskit/circuit/controlflow/break_loop.py +56 -0
  26. qiskit/circuit/controlflow/builder.py +791 -0
  27. qiskit/circuit/controlflow/continue_loop.py +56 -0
  28. qiskit/circuit/controlflow/control_flow.py +94 -0
  29. qiskit/circuit/controlflow/for_loop.py +218 -0
  30. qiskit/circuit/controlflow/if_else.py +498 -0
  31. qiskit/circuit/controlflow/switch_case.py +411 -0
  32. qiskit/circuit/controlflow/while_loop.py +166 -0
  33. qiskit/circuit/controlledgate.py +274 -0
  34. qiskit/circuit/delay.py +157 -0
  35. qiskit/circuit/duration.py +80 -0
  36. qiskit/circuit/equivalence.py +94 -0
  37. qiskit/circuit/equivalence_library.py +18 -0
  38. qiskit/circuit/exceptions.py +19 -0
  39. qiskit/circuit/gate.py +261 -0
  40. qiskit/circuit/instruction.py +564 -0
  41. qiskit/circuit/instructionset.py +132 -0
  42. qiskit/circuit/library/__init__.py +984 -0
  43. qiskit/circuit/library/arithmetic/__init__.py +40 -0
  44. qiskit/circuit/library/arithmetic/adders/__init__.py +18 -0
  45. qiskit/circuit/library/arithmetic/adders/adder.py +235 -0
  46. qiskit/circuit/library/arithmetic/adders/cdkm_ripple_carry_adder.py +123 -0
  47. qiskit/circuit/library/arithmetic/adders/draper_qft_adder.py +129 -0
  48. qiskit/circuit/library/arithmetic/adders/vbe_ripple_carry_adder.py +95 -0
  49. qiskit/circuit/library/arithmetic/exact_reciprocal.py +131 -0
  50. qiskit/circuit/library/arithmetic/functional_pauli_rotations.py +114 -0
  51. qiskit/circuit/library/arithmetic/integer_comparator.py +200 -0
  52. qiskit/circuit/library/arithmetic/linear_amplitude_function.py +363 -0
  53. qiskit/circuit/library/arithmetic/linear_pauli_rotations.py +243 -0
  54. qiskit/circuit/library/arithmetic/multipliers/__init__.py +17 -0
  55. qiskit/circuit/library/arithmetic/multipliers/hrs_cumulative_multiplier.py +145 -0
  56. qiskit/circuit/library/arithmetic/multipliers/multiplier.py +201 -0
  57. qiskit/circuit/library/arithmetic/multipliers/rg_qft_multiplier.py +108 -0
  58. qiskit/circuit/library/arithmetic/piecewise_chebyshev.py +502 -0
  59. qiskit/circuit/library/arithmetic/piecewise_linear_pauli_rotations.py +387 -0
  60. qiskit/circuit/library/arithmetic/piecewise_polynomial_pauli_rotations.py +493 -0
  61. qiskit/circuit/library/arithmetic/polynomial_pauli_rotations.py +389 -0
  62. qiskit/circuit/library/arithmetic/quadratic_form.py +364 -0
  63. qiskit/circuit/library/arithmetic/weighted_adder.py +409 -0
  64. qiskit/circuit/library/basis_change/__init__.py +15 -0
  65. qiskit/circuit/library/basis_change/qft.py +316 -0
  66. qiskit/circuit/library/bit_flip_oracle.py +130 -0
  67. qiskit/circuit/library/blueprintcircuit.py +316 -0
  68. qiskit/circuit/library/boolean_logic/__init__.py +18 -0
  69. qiskit/circuit/library/boolean_logic/inner_product.py +157 -0
  70. qiskit/circuit/library/boolean_logic/quantum_and.py +204 -0
  71. qiskit/circuit/library/boolean_logic/quantum_or.py +206 -0
  72. qiskit/circuit/library/boolean_logic/quantum_xor.py +167 -0
  73. qiskit/circuit/library/data_preparation/__init__.py +57 -0
  74. qiskit/circuit/library/data_preparation/_z_feature_map.py +115 -0
  75. qiskit/circuit/library/data_preparation/_zz_feature_map.py +150 -0
  76. qiskit/circuit/library/data_preparation/initializer.py +107 -0
  77. qiskit/circuit/library/data_preparation/pauli_feature_map.py +656 -0
  78. qiskit/circuit/library/data_preparation/state_preparation.py +336 -0
  79. qiskit/circuit/library/fourier_checking.py +160 -0
  80. qiskit/circuit/library/generalized_gates/__init__.py +30 -0
  81. qiskit/circuit/library/generalized_gates/diagonal.py +159 -0
  82. qiskit/circuit/library/generalized_gates/gms.py +175 -0
  83. qiskit/circuit/library/generalized_gates/gr.py +219 -0
  84. qiskit/circuit/library/generalized_gates/isometry.py +370 -0
  85. qiskit/circuit/library/generalized_gates/linear_function.py +318 -0
  86. qiskit/circuit/library/generalized_gates/mcg_up_to_diagonal.py +143 -0
  87. qiskit/circuit/library/generalized_gates/mcmt.py +316 -0
  88. qiskit/circuit/library/generalized_gates/pauli.py +84 -0
  89. qiskit/circuit/library/generalized_gates/permutation.py +198 -0
  90. qiskit/circuit/library/generalized_gates/rv.py +96 -0
  91. qiskit/circuit/library/generalized_gates/uc.py +303 -0
  92. qiskit/circuit/library/generalized_gates/uc_pauli_rot.py +164 -0
  93. qiskit/circuit/library/generalized_gates/ucrx.py +32 -0
  94. qiskit/circuit/library/generalized_gates/ucry.py +32 -0
  95. qiskit/circuit/library/generalized_gates/ucrz.py +32 -0
  96. qiskit/circuit/library/generalized_gates/unitary.py +217 -0
  97. qiskit/circuit/library/graph_state.py +172 -0
  98. qiskit/circuit/library/grover_operator.py +583 -0
  99. qiskit/circuit/library/hamiltonian_gate.py +142 -0
  100. qiskit/circuit/library/hidden_linear_function.py +163 -0
  101. qiskit/circuit/library/iqp.py +180 -0
  102. qiskit/circuit/library/n_local/__init__.py +45 -0
  103. qiskit/circuit/library/n_local/efficient_su2.py +282 -0
  104. qiskit/circuit/library/n_local/evolved_operator_ansatz.py +520 -0
  105. qiskit/circuit/library/n_local/excitation_preserving.py +303 -0
  106. qiskit/circuit/library/n_local/n_local.py +1477 -0
  107. qiskit/circuit/library/n_local/pauli_two_design.py +246 -0
  108. qiskit/circuit/library/n_local/qaoa_ansatz.py +367 -0
  109. qiskit/circuit/library/n_local/real_amplitudes.py +312 -0
  110. qiskit/circuit/library/n_local/two_local.py +289 -0
  111. qiskit/circuit/library/overlap.py +183 -0
  112. qiskit/circuit/library/pauli_evolution.py +201 -0
  113. qiskit/circuit/library/phase_estimation.py +177 -0
  114. qiskit/circuit/library/phase_oracle.py +239 -0
  115. qiskit/circuit/library/quantum_volume.py +180 -0
  116. qiskit/circuit/library/standard_gates/__init__.py +141 -0
  117. qiskit/circuit/library/standard_gates/dcx.py +77 -0
  118. qiskit/circuit/library/standard_gates/ecr.py +129 -0
  119. qiskit/circuit/library/standard_gates/equivalence_library.py +1800 -0
  120. qiskit/circuit/library/standard_gates/global_phase.py +84 -0
  121. qiskit/circuit/library/standard_gates/h.py +253 -0
  122. qiskit/circuit/library/standard_gates/i.py +76 -0
  123. qiskit/circuit/library/standard_gates/iswap.py +133 -0
  124. qiskit/circuit/library/standard_gates/p.py +422 -0
  125. qiskit/circuit/library/standard_gates/r.py +114 -0
  126. qiskit/circuit/library/standard_gates/rx.py +293 -0
  127. qiskit/circuit/library/standard_gates/rxx.py +180 -0
  128. qiskit/circuit/library/standard_gates/ry.py +286 -0
  129. qiskit/circuit/library/standard_gates/ryy.py +180 -0
  130. qiskit/circuit/library/standard_gates/rz.py +307 -0
  131. qiskit/circuit/library/standard_gates/rzx.py +226 -0
  132. qiskit/circuit/library/standard_gates/rzz.py +193 -0
  133. qiskit/circuit/library/standard_gates/s.py +419 -0
  134. qiskit/circuit/library/standard_gates/swap.py +281 -0
  135. qiskit/circuit/library/standard_gates/sx.py +310 -0
  136. qiskit/circuit/library/standard_gates/t.py +178 -0
  137. qiskit/circuit/library/standard_gates/u.py +395 -0
  138. qiskit/circuit/library/standard_gates/u1.py +490 -0
  139. qiskit/circuit/library/standard_gates/u2.py +145 -0
  140. qiskit/circuit/library/standard_gates/u3.py +428 -0
  141. qiskit/circuit/library/standard_gates/x.py +1481 -0
  142. qiskit/circuit/library/standard_gates/xx_minus_yy.py +202 -0
  143. qiskit/circuit/library/standard_gates/xx_plus_yy.py +236 -0
  144. qiskit/circuit/library/standard_gates/y.py +257 -0
  145. qiskit/circuit/library/standard_gates/z.py +338 -0
  146. qiskit/circuit/library/templates/__init__.py +92 -0
  147. qiskit/circuit/library/templates/clifford/__init__.py +33 -0
  148. qiskit/circuit/library/templates/clifford/clifford_2_1.py +34 -0
  149. qiskit/circuit/library/templates/clifford/clifford_2_2.py +35 -0
  150. qiskit/circuit/library/templates/clifford/clifford_2_3.py +34 -0
  151. qiskit/circuit/library/templates/clifford/clifford_2_4.py +34 -0
  152. qiskit/circuit/library/templates/clifford/clifford_3_1.py +35 -0
  153. qiskit/circuit/library/templates/clifford/clifford_4_1.py +38 -0
  154. qiskit/circuit/library/templates/clifford/clifford_4_2.py +37 -0
  155. qiskit/circuit/library/templates/clifford/clifford_4_3.py +38 -0
  156. qiskit/circuit/library/templates/clifford/clifford_4_4.py +37 -0
  157. qiskit/circuit/library/templates/clifford/clifford_5_1.py +40 -0
  158. qiskit/circuit/library/templates/clifford/clifford_6_1.py +40 -0
  159. qiskit/circuit/library/templates/clifford/clifford_6_2.py +40 -0
  160. qiskit/circuit/library/templates/clifford/clifford_6_3.py +40 -0
  161. qiskit/circuit/library/templates/clifford/clifford_6_4.py +38 -0
  162. qiskit/circuit/library/templates/clifford/clifford_6_5.py +40 -0
  163. qiskit/circuit/library/templates/clifford/clifford_8_1.py +42 -0
  164. qiskit/circuit/library/templates/clifford/clifford_8_2.py +42 -0
  165. qiskit/circuit/library/templates/clifford/clifford_8_3.py +41 -0
  166. qiskit/circuit/library/templates/nct/__init__.py +67 -0
  167. qiskit/circuit/library/templates/nct/template_nct_2a_1.py +34 -0
  168. qiskit/circuit/library/templates/nct/template_nct_2a_2.py +35 -0
  169. qiskit/circuit/library/templates/nct/template_nct_2a_3.py +37 -0
  170. qiskit/circuit/library/templates/nct/template_nct_4a_1.py +43 -0
  171. qiskit/circuit/library/templates/nct/template_nct_4a_2.py +41 -0
  172. qiskit/circuit/library/templates/nct/template_nct_4a_3.py +39 -0
  173. qiskit/circuit/library/templates/nct/template_nct_4b_1.py +41 -0
  174. qiskit/circuit/library/templates/nct/template_nct_4b_2.py +39 -0
  175. qiskit/circuit/library/templates/nct/template_nct_5a_1.py +40 -0
  176. qiskit/circuit/library/templates/nct/template_nct_5a_2.py +40 -0
  177. qiskit/circuit/library/templates/nct/template_nct_5a_3.py +40 -0
  178. qiskit/circuit/library/templates/nct/template_nct_5a_4.py +39 -0
  179. qiskit/circuit/library/templates/nct/template_nct_6a_1.py +40 -0
  180. qiskit/circuit/library/templates/nct/template_nct_6a_2.py +41 -0
  181. qiskit/circuit/library/templates/nct/template_nct_6a_3.py +41 -0
  182. qiskit/circuit/library/templates/nct/template_nct_6a_4.py +41 -0
  183. qiskit/circuit/library/templates/nct/template_nct_6b_1.py +41 -0
  184. qiskit/circuit/library/templates/nct/template_nct_6b_2.py +41 -0
  185. qiskit/circuit/library/templates/nct/template_nct_6c_1.py +41 -0
  186. qiskit/circuit/library/templates/nct/template_nct_7a_1.py +43 -0
  187. qiskit/circuit/library/templates/nct/template_nct_7b_1.py +43 -0
  188. qiskit/circuit/library/templates/nct/template_nct_7c_1.py +43 -0
  189. qiskit/circuit/library/templates/nct/template_nct_7d_1.py +43 -0
  190. qiskit/circuit/library/templates/nct/template_nct_7e_1.py +43 -0
  191. qiskit/circuit/library/templates/nct/template_nct_9a_1.py +45 -0
  192. qiskit/circuit/library/templates/nct/template_nct_9c_1.py +43 -0
  193. qiskit/circuit/library/templates/nct/template_nct_9c_10.py +44 -0
  194. qiskit/circuit/library/templates/nct/template_nct_9c_11.py +44 -0
  195. qiskit/circuit/library/templates/nct/template_nct_9c_12.py +44 -0
  196. qiskit/circuit/library/templates/nct/template_nct_9c_2.py +44 -0
  197. qiskit/circuit/library/templates/nct/template_nct_9c_3.py +44 -0
  198. qiskit/circuit/library/templates/nct/template_nct_9c_4.py +44 -0
  199. qiskit/circuit/library/templates/nct/template_nct_9c_5.py +44 -0
  200. qiskit/circuit/library/templates/nct/template_nct_9c_6.py +44 -0
  201. qiskit/circuit/library/templates/nct/template_nct_9c_7.py +44 -0
  202. qiskit/circuit/library/templates/nct/template_nct_9c_8.py +44 -0
  203. qiskit/circuit/library/templates/nct/template_nct_9c_9.py +44 -0
  204. qiskit/circuit/library/templates/nct/template_nct_9d_1.py +43 -0
  205. qiskit/circuit/library/templates/nct/template_nct_9d_10.py +44 -0
  206. qiskit/circuit/library/templates/nct/template_nct_9d_2.py +44 -0
  207. qiskit/circuit/library/templates/nct/template_nct_9d_3.py +44 -0
  208. qiskit/circuit/library/templates/nct/template_nct_9d_4.py +44 -0
  209. qiskit/circuit/library/templates/nct/template_nct_9d_5.py +44 -0
  210. qiskit/circuit/library/templates/nct/template_nct_9d_6.py +44 -0
  211. qiskit/circuit/library/templates/nct/template_nct_9d_7.py +44 -0
  212. qiskit/circuit/library/templates/nct/template_nct_9d_8.py +44 -0
  213. qiskit/circuit/library/templates/nct/template_nct_9d_9.py +44 -0
  214. qiskit/circuit/library/templates/rzx/__init__.py +25 -0
  215. qiskit/circuit/library/templates/rzx/rzx_cy.py +47 -0
  216. qiskit/circuit/library/templates/rzx/rzx_xz.py +54 -0
  217. qiskit/circuit/library/templates/rzx/rzx_yz.py +45 -0
  218. qiskit/circuit/library/templates/rzx/rzx_zz1.py +69 -0
  219. qiskit/circuit/library/templates/rzx/rzx_zz2.py +59 -0
  220. qiskit/circuit/library/templates/rzx/rzx_zz3.py +59 -0
  221. qiskit/circuit/measure.py +53 -0
  222. qiskit/circuit/operation.py +68 -0
  223. qiskit/circuit/parameter.py +179 -0
  224. qiskit/circuit/parameterexpression.py +703 -0
  225. qiskit/circuit/parametertable.py +119 -0
  226. qiskit/circuit/parametervector.py +140 -0
  227. qiskit/circuit/quantumcircuit.py +7540 -0
  228. qiskit/circuit/quantumcircuitdata.py +136 -0
  229. qiskit/circuit/random/__init__.py +15 -0
  230. qiskit/circuit/random/utils.py +366 -0
  231. qiskit/circuit/reset.py +37 -0
  232. qiskit/circuit/singleton.py +600 -0
  233. qiskit/circuit/store.py +89 -0
  234. qiskit/circuit/tools/__init__.py +16 -0
  235. qiskit/circuit/tools/pi_check.py +193 -0
  236. qiskit/circuit/twirling.py +145 -0
  237. qiskit/compiler/__init__.py +27 -0
  238. qiskit/compiler/transpiler.py +375 -0
  239. qiskit/converters/__init__.py +74 -0
  240. qiskit/converters/circuit_to_dag.py +80 -0
  241. qiskit/converters/circuit_to_dagdependency.py +49 -0
  242. qiskit/converters/circuit_to_dagdependency_v2.py +46 -0
  243. qiskit/converters/circuit_to_gate.py +107 -0
  244. qiskit/converters/circuit_to_instruction.py +142 -0
  245. qiskit/converters/dag_to_circuit.py +79 -0
  246. qiskit/converters/dag_to_dagdependency.py +54 -0
  247. qiskit/converters/dag_to_dagdependency_v2.py +43 -0
  248. qiskit/converters/dagdependency_to_circuit.py +40 -0
  249. qiskit/converters/dagdependency_to_dag.py +48 -0
  250. qiskit/dagcircuit/__init__.py +55 -0
  251. qiskit/dagcircuit/collect_blocks.py +407 -0
  252. qiskit/dagcircuit/dagcircuit.py +24 -0
  253. qiskit/dagcircuit/dagdependency.py +612 -0
  254. qiskit/dagcircuit/dagdependency_v2.py +566 -0
  255. qiskit/dagcircuit/dagdepnode.py +160 -0
  256. qiskit/dagcircuit/dagnode.py +188 -0
  257. qiskit/dagcircuit/exceptions.py +42 -0
  258. qiskit/exceptions.py +153 -0
  259. qiskit/passmanager/__init__.py +258 -0
  260. qiskit/passmanager/base_tasks.py +230 -0
  261. qiskit/passmanager/compilation_status.py +74 -0
  262. qiskit/passmanager/exceptions.py +19 -0
  263. qiskit/passmanager/flow_controllers.py +116 -0
  264. qiskit/passmanager/passmanager.py +353 -0
  265. qiskit/primitives/__init__.py +490 -0
  266. qiskit/primitives/backend_estimator_v2.py +530 -0
  267. qiskit/primitives/backend_sampler_v2.py +339 -0
  268. qiskit/primitives/base/__init__.py +20 -0
  269. qiskit/primitives/base/base_estimator.py +247 -0
  270. qiskit/primitives/base/base_primitive_job.py +78 -0
  271. qiskit/primitives/base/base_primitive_v1.py +45 -0
  272. qiskit/primitives/base/base_result_v1.py +65 -0
  273. qiskit/primitives/base/base_sampler.py +196 -0
  274. qiskit/primitives/base/estimator_result_v1.py +46 -0
  275. qiskit/primitives/base/sampler_result_v1.py +45 -0
  276. qiskit/primitives/base/validation_v1.py +250 -0
  277. qiskit/primitives/containers/__init__.py +26 -0
  278. qiskit/primitives/containers/bindings_array.py +391 -0
  279. qiskit/primitives/containers/bit_array.py +764 -0
  280. qiskit/primitives/containers/data_bin.py +175 -0
  281. qiskit/primitives/containers/estimator_pub.py +222 -0
  282. qiskit/primitives/containers/object_array.py +94 -0
  283. qiskit/primitives/containers/observables_array.py +296 -0
  284. qiskit/primitives/containers/primitive_result.py +53 -0
  285. qiskit/primitives/containers/pub_result.py +51 -0
  286. qiskit/primitives/containers/sampler_pub.py +193 -0
  287. qiskit/primitives/containers/sampler_pub_result.py +74 -0
  288. qiskit/primitives/containers/shape.py +129 -0
  289. qiskit/primitives/primitive_job.py +81 -0
  290. qiskit/primitives/statevector_estimator.py +175 -0
  291. qiskit/primitives/statevector_sampler.py +290 -0
  292. qiskit/primitives/utils.py +72 -0
  293. qiskit/providers/__init__.py +677 -0
  294. qiskit/providers/backend.py +364 -0
  295. qiskit/providers/basic_provider/__init__.py +47 -0
  296. qiskit/providers/basic_provider/basic_provider.py +121 -0
  297. qiskit/providers/basic_provider/basic_provider_job.py +65 -0
  298. qiskit/providers/basic_provider/basic_provider_tools.py +218 -0
  299. qiskit/providers/basic_provider/basic_simulator.py +693 -0
  300. qiskit/providers/basic_provider/exceptions.py +30 -0
  301. qiskit/providers/exceptions.py +33 -0
  302. qiskit/providers/fake_provider/__init__.py +69 -0
  303. qiskit/providers/fake_provider/generic_backend_v2.py +374 -0
  304. qiskit/providers/fake_provider/utils/__init__.py +15 -0
  305. qiskit/providers/job.py +147 -0
  306. qiskit/providers/jobstatus.py +30 -0
  307. qiskit/providers/options.py +273 -0
  308. qiskit/providers/providerutils.py +110 -0
  309. qiskit/qasm/libs/dummy/stdgates.inc +75 -0
  310. qiskit/qasm/libs/qelib1.inc +266 -0
  311. qiskit/qasm/libs/stdgates.inc +82 -0
  312. qiskit/qasm2/__init__.py +669 -0
  313. qiskit/qasm2/exceptions.py +27 -0
  314. qiskit/qasm2/export.py +364 -0
  315. qiskit/qasm2/parse.py +438 -0
  316. qiskit/qasm3/__init__.py +372 -0
  317. qiskit/qasm3/ast.py +782 -0
  318. qiskit/qasm3/exceptions.py +27 -0
  319. qiskit/qasm3/experimental.py +70 -0
  320. qiskit/qasm3/exporter.py +1340 -0
  321. qiskit/qasm3/printer.py +608 -0
  322. qiskit/qpy/__init__.py +1965 -0
  323. qiskit/qpy/binary_io/__init__.py +35 -0
  324. qiskit/qpy/binary_io/circuits.py +1455 -0
  325. qiskit/qpy/binary_io/parse_sympy_repr.py +121 -0
  326. qiskit/qpy/binary_io/schedules.py +308 -0
  327. qiskit/qpy/binary_io/value.py +1165 -0
  328. qiskit/qpy/common.py +353 -0
  329. qiskit/qpy/exceptions.py +53 -0
  330. qiskit/qpy/formats.py +442 -0
  331. qiskit/qpy/interface.py +344 -0
  332. qiskit/qpy/type_keys.py +409 -0
  333. qiskit/quantum_info/__init__.py +162 -0
  334. qiskit/quantum_info/analysis/__init__.py +17 -0
  335. qiskit/quantum_info/analysis/average.py +47 -0
  336. qiskit/quantum_info/analysis/distance.py +104 -0
  337. qiskit/quantum_info/analysis/make_observable.py +44 -0
  338. qiskit/quantum_info/analysis/z2_symmetries.py +484 -0
  339. qiskit/quantum_info/operators/__init__.py +28 -0
  340. qiskit/quantum_info/operators/base_operator.py +145 -0
  341. qiskit/quantum_info/operators/channel/__init__.py +29 -0
  342. qiskit/quantum_info/operators/channel/chi.py +191 -0
  343. qiskit/quantum_info/operators/channel/choi.py +218 -0
  344. qiskit/quantum_info/operators/channel/kraus.py +337 -0
  345. qiskit/quantum_info/operators/channel/ptm.py +204 -0
  346. qiskit/quantum_info/operators/channel/quantum_channel.py +348 -0
  347. qiskit/quantum_info/operators/channel/stinespring.py +296 -0
  348. qiskit/quantum_info/operators/channel/superop.py +373 -0
  349. qiskit/quantum_info/operators/channel/transformations.py +490 -0
  350. qiskit/quantum_info/operators/custom_iterator.py +48 -0
  351. qiskit/quantum_info/operators/dihedral/__init__.py +18 -0
  352. qiskit/quantum_info/operators/dihedral/dihedral.py +511 -0
  353. qiskit/quantum_info/operators/dihedral/dihedral_circuits.py +216 -0
  354. qiskit/quantum_info/operators/dihedral/polynomial.py +313 -0
  355. qiskit/quantum_info/operators/dihedral/random.py +64 -0
  356. qiskit/quantum_info/operators/linear_op.py +25 -0
  357. qiskit/quantum_info/operators/measures.py +418 -0
  358. qiskit/quantum_info/operators/mixins/__init__.py +52 -0
  359. qiskit/quantum_info/operators/mixins/adjoint.py +52 -0
  360. qiskit/quantum_info/operators/mixins/group.py +171 -0
  361. qiskit/quantum_info/operators/mixins/linear.py +84 -0
  362. qiskit/quantum_info/operators/mixins/multiply.py +62 -0
  363. qiskit/quantum_info/operators/mixins/tolerances.py +72 -0
  364. qiskit/quantum_info/operators/op_shape.py +525 -0
  365. qiskit/quantum_info/operators/operator.py +869 -0
  366. qiskit/quantum_info/operators/operator_utils.py +76 -0
  367. qiskit/quantum_info/operators/predicates.py +183 -0
  368. qiskit/quantum_info/operators/random.py +154 -0
  369. qiskit/quantum_info/operators/scalar_op.py +254 -0
  370. qiskit/quantum_info/operators/symplectic/__init__.py +23 -0
  371. qiskit/quantum_info/operators/symplectic/base_pauli.py +719 -0
  372. qiskit/quantum_info/operators/symplectic/clifford.py +1032 -0
  373. qiskit/quantum_info/operators/symplectic/clifford_circuits.py +558 -0
  374. qiskit/quantum_info/operators/symplectic/pauli.py +755 -0
  375. qiskit/quantum_info/operators/symplectic/pauli_list.py +1242 -0
  376. qiskit/quantum_info/operators/symplectic/pauli_utils.py +40 -0
  377. qiskit/quantum_info/operators/symplectic/random.py +117 -0
  378. qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py +1239 -0
  379. qiskit/quantum_info/operators/utils/__init__.py +20 -0
  380. qiskit/quantum_info/operators/utils/anti_commutator.py +36 -0
  381. qiskit/quantum_info/operators/utils/commutator.py +36 -0
  382. qiskit/quantum_info/operators/utils/double_commutator.py +76 -0
  383. qiskit/quantum_info/quaternion.py +156 -0
  384. qiskit/quantum_info/random.py +26 -0
  385. qiskit/quantum_info/states/__init__.py +28 -0
  386. qiskit/quantum_info/states/densitymatrix.py +857 -0
  387. qiskit/quantum_info/states/measures.py +288 -0
  388. qiskit/quantum_info/states/quantum_state.py +503 -0
  389. qiskit/quantum_info/states/random.py +157 -0
  390. qiskit/quantum_info/states/stabilizerstate.py +805 -0
  391. qiskit/quantum_info/states/statevector.py +977 -0
  392. qiskit/quantum_info/states/utils.py +247 -0
  393. qiskit/result/__init__.py +61 -0
  394. qiskit/result/counts.py +189 -0
  395. qiskit/result/distributions/__init__.py +17 -0
  396. qiskit/result/distributions/probability.py +100 -0
  397. qiskit/result/distributions/quasi.py +154 -0
  398. qiskit/result/exceptions.py +40 -0
  399. qiskit/result/models.py +241 -0
  400. qiskit/result/postprocess.py +239 -0
  401. qiskit/result/result.py +385 -0
  402. qiskit/result/sampled_expval.py +74 -0
  403. qiskit/result/utils.py +294 -0
  404. qiskit/synthesis/__init__.py +240 -0
  405. qiskit/synthesis/arithmetic/__init__.py +18 -0
  406. qiskit/synthesis/arithmetic/adders/__init__.py +17 -0
  407. qiskit/synthesis/arithmetic/adders/cdkm_ripple_carry_adder.py +154 -0
  408. qiskit/synthesis/arithmetic/adders/draper_qft_adder.py +103 -0
  409. qiskit/synthesis/arithmetic/adders/vbe_ripple_carry_adder.py +161 -0
  410. qiskit/synthesis/arithmetic/comparators/__init__.py +16 -0
  411. qiskit/synthesis/arithmetic/comparators/compare_2s.py +112 -0
  412. qiskit/synthesis/arithmetic/comparators/compare_greedy.py +66 -0
  413. qiskit/synthesis/arithmetic/multipliers/__init__.py +16 -0
  414. qiskit/synthesis/arithmetic/multipliers/hrs_cumulative_multiplier.py +103 -0
  415. qiskit/synthesis/arithmetic/multipliers/rg_qft_multiplier.py +100 -0
  416. qiskit/synthesis/arithmetic/weighted_sum.py +155 -0
  417. qiskit/synthesis/boolean/__init__.py +13 -0
  418. qiskit/synthesis/boolean/boolean_expression.py +231 -0
  419. qiskit/synthesis/boolean/boolean_expression_synth.py +124 -0
  420. qiskit/synthesis/boolean/boolean_expression_visitor.py +96 -0
  421. qiskit/synthesis/clifford/__init__.py +19 -0
  422. qiskit/synthesis/clifford/clifford_decompose_ag.py +178 -0
  423. qiskit/synthesis/clifford/clifford_decompose_bm.py +46 -0
  424. qiskit/synthesis/clifford/clifford_decompose_full.py +64 -0
  425. qiskit/synthesis/clifford/clifford_decompose_greedy.py +58 -0
  426. qiskit/synthesis/clifford/clifford_decompose_layers.py +447 -0
  427. qiskit/synthesis/cnotdihedral/__init__.py +17 -0
  428. qiskit/synthesis/cnotdihedral/cnotdihedral_decompose_full.py +52 -0
  429. qiskit/synthesis/cnotdihedral/cnotdihedral_decompose_general.py +141 -0
  430. qiskit/synthesis/cnotdihedral/cnotdihedral_decompose_two_qubits.py +266 -0
  431. qiskit/synthesis/discrete_basis/__init__.py +16 -0
  432. qiskit/synthesis/discrete_basis/commutator_decompose.py +265 -0
  433. qiskit/synthesis/discrete_basis/gate_sequence.py +421 -0
  434. qiskit/synthesis/discrete_basis/generate_basis_approximations.py +165 -0
  435. qiskit/synthesis/discrete_basis/solovay_kitaev.py +240 -0
  436. qiskit/synthesis/evolution/__init__.py +21 -0
  437. qiskit/synthesis/evolution/evolution_synthesis.py +48 -0
  438. qiskit/synthesis/evolution/lie_trotter.py +120 -0
  439. qiskit/synthesis/evolution/matrix_synthesis.py +47 -0
  440. qiskit/synthesis/evolution/pauli_network.py +80 -0
  441. qiskit/synthesis/evolution/product_formula.py +313 -0
  442. qiskit/synthesis/evolution/qdrift.py +130 -0
  443. qiskit/synthesis/evolution/suzuki_trotter.py +224 -0
  444. qiskit/synthesis/linear/__init__.py +26 -0
  445. qiskit/synthesis/linear/cnot_synth.py +69 -0
  446. qiskit/synthesis/linear/linear_circuits_utils.py +128 -0
  447. qiskit/synthesis/linear/linear_depth_lnn.py +61 -0
  448. qiskit/synthesis/linear/linear_matrix_utils.py +27 -0
  449. qiskit/synthesis/linear_phase/__init__.py +17 -0
  450. qiskit/synthesis/linear_phase/cnot_phase_synth.py +206 -0
  451. qiskit/synthesis/linear_phase/cx_cz_depth_lnn.py +61 -0
  452. qiskit/synthesis/linear_phase/cz_depth_lnn.py +58 -0
  453. qiskit/synthesis/multi_controlled/__init__.py +25 -0
  454. qiskit/synthesis/multi_controlled/mcmt_vchain.py +52 -0
  455. qiskit/synthesis/multi_controlled/mcx_synthesis.py +359 -0
  456. qiskit/synthesis/multi_controlled/multi_control_rotation_gates.py +206 -0
  457. qiskit/synthesis/one_qubit/__init__.py +15 -0
  458. qiskit/synthesis/one_qubit/one_qubit_decompose.py +288 -0
  459. qiskit/synthesis/permutation/__init__.py +18 -0
  460. qiskit/synthesis/permutation/permutation_full.py +78 -0
  461. qiskit/synthesis/permutation/permutation_lnn.py +54 -0
  462. qiskit/synthesis/permutation/permutation_reverse_lnn.py +93 -0
  463. qiskit/synthesis/permutation/permutation_utils.py +16 -0
  464. qiskit/synthesis/qft/__init__.py +16 -0
  465. qiskit/synthesis/qft/qft_decompose_full.py +97 -0
  466. qiskit/synthesis/qft/qft_decompose_lnn.py +79 -0
  467. qiskit/synthesis/stabilizer/__init__.py +16 -0
  468. qiskit/synthesis/stabilizer/stabilizer_circuit.py +149 -0
  469. qiskit/synthesis/stabilizer/stabilizer_decompose.py +194 -0
  470. qiskit/synthesis/two_qubit/__init__.py +20 -0
  471. qiskit/synthesis/two_qubit/local_invariance.py +63 -0
  472. qiskit/synthesis/two_qubit/two_qubit_decompose.py +583 -0
  473. qiskit/synthesis/two_qubit/xx_decompose/__init__.py +19 -0
  474. qiskit/synthesis/two_qubit/xx_decompose/circuits.py +300 -0
  475. qiskit/synthesis/two_qubit/xx_decompose/decomposer.py +324 -0
  476. qiskit/synthesis/two_qubit/xx_decompose/embodiments.py +163 -0
  477. qiskit/synthesis/two_qubit/xx_decompose/paths.py +412 -0
  478. qiskit/synthesis/two_qubit/xx_decompose/polytopes.py +262 -0
  479. qiskit/synthesis/two_qubit/xx_decompose/utilities.py +40 -0
  480. qiskit/synthesis/two_qubit/xx_decompose/weyl.py +133 -0
  481. qiskit/synthesis/unitary/__init__.py +13 -0
  482. qiskit/synthesis/unitary/aqc/__init__.py +177 -0
  483. qiskit/synthesis/unitary/aqc/approximate.py +116 -0
  484. qiskit/synthesis/unitary/aqc/aqc.py +175 -0
  485. qiskit/synthesis/unitary/aqc/cnot_structures.py +300 -0
  486. qiskit/synthesis/unitary/aqc/cnot_unit_circuit.py +103 -0
  487. qiskit/synthesis/unitary/aqc/cnot_unit_objective.py +299 -0
  488. qiskit/synthesis/unitary/aqc/elementary_operations.py +108 -0
  489. qiskit/synthesis/unitary/aqc/fast_gradient/__init__.py +164 -0
  490. qiskit/synthesis/unitary/aqc/fast_gradient/fast_grad_utils.py +237 -0
  491. qiskit/synthesis/unitary/aqc/fast_gradient/fast_gradient.py +226 -0
  492. qiskit/synthesis/unitary/aqc/fast_gradient/layer.py +370 -0
  493. qiskit/synthesis/unitary/aqc/fast_gradient/pmatrix.py +312 -0
  494. qiskit/synthesis/unitary/qsd.py +288 -0
  495. qiskit/transpiler/__init__.py +1345 -0
  496. qiskit/transpiler/basepasses.py +190 -0
  497. qiskit/transpiler/coupling.py +500 -0
  498. qiskit/transpiler/exceptions.py +59 -0
  499. qiskit/transpiler/instruction_durations.py +281 -0
  500. qiskit/transpiler/layout.py +740 -0
  501. qiskit/transpiler/passes/__init__.py +276 -0
  502. qiskit/transpiler/passes/analysis/__init__.py +23 -0
  503. qiskit/transpiler/passes/analysis/count_ops.py +30 -0
  504. qiskit/transpiler/passes/analysis/count_ops_longest_path.py +26 -0
  505. qiskit/transpiler/passes/analysis/dag_longest_path.py +24 -0
  506. qiskit/transpiler/passes/analysis/depth.py +33 -0
  507. qiskit/transpiler/passes/analysis/num_qubits.py +26 -0
  508. qiskit/transpiler/passes/analysis/num_tensor_factors.py +26 -0
  509. qiskit/transpiler/passes/analysis/resource_estimation.py +41 -0
  510. qiskit/transpiler/passes/analysis/size.py +36 -0
  511. qiskit/transpiler/passes/analysis/width.py +27 -0
  512. qiskit/transpiler/passes/basis/__init__.py +19 -0
  513. qiskit/transpiler/passes/basis/basis_translator.py +138 -0
  514. qiskit/transpiler/passes/basis/decompose.py +137 -0
  515. qiskit/transpiler/passes/basis/translate_parameterized.py +175 -0
  516. qiskit/transpiler/passes/basis/unroll_3q_or_more.py +84 -0
  517. qiskit/transpiler/passes/basis/unroll_custom_definitions.py +110 -0
  518. qiskit/transpiler/passes/layout/__init__.py +26 -0
  519. qiskit/transpiler/passes/layout/_csp_custom_solver.py +65 -0
  520. qiskit/transpiler/passes/layout/apply_layout.py +128 -0
  521. qiskit/transpiler/passes/layout/csp_layout.py +132 -0
  522. qiskit/transpiler/passes/layout/dense_layout.py +177 -0
  523. qiskit/transpiler/passes/layout/disjoint_utils.py +219 -0
  524. qiskit/transpiler/passes/layout/enlarge_with_ancilla.py +49 -0
  525. qiskit/transpiler/passes/layout/full_ancilla_allocation.py +116 -0
  526. qiskit/transpiler/passes/layout/layout_2q_distance.py +77 -0
  527. qiskit/transpiler/passes/layout/sabre_layout.py +506 -0
  528. qiskit/transpiler/passes/layout/sabre_pre_layout.py +225 -0
  529. qiskit/transpiler/passes/layout/set_layout.py +69 -0
  530. qiskit/transpiler/passes/layout/trivial_layout.py +66 -0
  531. qiskit/transpiler/passes/layout/vf2_layout.py +256 -0
  532. qiskit/transpiler/passes/layout/vf2_post_layout.py +376 -0
  533. qiskit/transpiler/passes/layout/vf2_utils.py +235 -0
  534. qiskit/transpiler/passes/optimization/__init__.py +42 -0
  535. qiskit/transpiler/passes/optimization/_gate_extension.py +80 -0
  536. qiskit/transpiler/passes/optimization/collect_1q_runs.py +31 -0
  537. qiskit/transpiler/passes/optimization/collect_2q_blocks.py +35 -0
  538. qiskit/transpiler/passes/optimization/collect_and_collapse.py +117 -0
  539. qiskit/transpiler/passes/optimization/collect_cliffords.py +109 -0
  540. qiskit/transpiler/passes/optimization/collect_linear_functions.py +85 -0
  541. qiskit/transpiler/passes/optimization/collect_multiqubit_blocks.py +242 -0
  542. qiskit/transpiler/passes/optimization/commutation_analysis.py +44 -0
  543. qiskit/transpiler/passes/optimization/commutative_cancellation.py +82 -0
  544. qiskit/transpiler/passes/optimization/commutative_inverse_cancellation.py +140 -0
  545. qiskit/transpiler/passes/optimization/consolidate_blocks.py +176 -0
  546. qiskit/transpiler/passes/optimization/contract_idle_wires_in_control_flow.py +104 -0
  547. qiskit/transpiler/passes/optimization/elide_permutations.py +91 -0
  548. qiskit/transpiler/passes/optimization/hoare_opt.py +420 -0
  549. qiskit/transpiler/passes/optimization/inverse_cancellation.py +95 -0
  550. qiskit/transpiler/passes/optimization/light_cone.py +135 -0
  551. qiskit/transpiler/passes/optimization/optimize_1q_commutation.py +267 -0
  552. qiskit/transpiler/passes/optimization/optimize_1q_decomposition.py +250 -0
  553. qiskit/transpiler/passes/optimization/optimize_1q_gates.py +384 -0
  554. qiskit/transpiler/passes/optimization/optimize_annotated.py +449 -0
  555. qiskit/transpiler/passes/optimization/optimize_cliffords.py +89 -0
  556. qiskit/transpiler/passes/optimization/optimize_swap_before_measure.py +71 -0
  557. qiskit/transpiler/passes/optimization/remove_diagonal_gates_before_measure.py +41 -0
  558. qiskit/transpiler/passes/optimization/remove_final_reset.py +37 -0
  559. qiskit/transpiler/passes/optimization/remove_identity_equiv.py +70 -0
  560. qiskit/transpiler/passes/optimization/remove_reset_in_zero_state.py +37 -0
  561. qiskit/transpiler/passes/optimization/reset_after_measure_simplification.py +50 -0
  562. qiskit/transpiler/passes/optimization/split_2q_unitaries.py +63 -0
  563. qiskit/transpiler/passes/optimization/template_matching/__init__.py +19 -0
  564. qiskit/transpiler/passes/optimization/template_matching/backward_match.py +749 -0
  565. qiskit/transpiler/passes/optimization/template_matching/forward_match.py +452 -0
  566. qiskit/transpiler/passes/optimization/template_matching/maximal_matches.py +77 -0
  567. qiskit/transpiler/passes/optimization/template_matching/template_matching.py +370 -0
  568. qiskit/transpiler/passes/optimization/template_matching/template_substitution.py +639 -0
  569. qiskit/transpiler/passes/optimization/template_optimization.py +158 -0
  570. qiskit/transpiler/passes/routing/__init__.py +21 -0
  571. qiskit/transpiler/passes/routing/algorithms/__init__.py +33 -0
  572. qiskit/transpiler/passes/routing/algorithms/token_swapper.py +105 -0
  573. qiskit/transpiler/passes/routing/algorithms/types.py +46 -0
  574. qiskit/transpiler/passes/routing/algorithms/util.py +103 -0
  575. qiskit/transpiler/passes/routing/basic_swap.py +166 -0
  576. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/__init__.py +25 -0
  577. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_block.py +60 -0
  578. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py +397 -0
  579. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py +145 -0
  580. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py +306 -0
  581. qiskit/transpiler/passes/routing/layout_transformation.py +119 -0
  582. qiskit/transpiler/passes/routing/lookahead_swap.py +390 -0
  583. qiskit/transpiler/passes/routing/sabre_swap.py +463 -0
  584. qiskit/transpiler/passes/routing/star_prerouting.py +408 -0
  585. qiskit/transpiler/passes/routing/utils.py +35 -0
  586. qiskit/transpiler/passes/scheduling/__init__.py +21 -0
  587. qiskit/transpiler/passes/scheduling/alignments/__init__.py +79 -0
  588. qiskit/transpiler/passes/scheduling/alignments/check_durations.py +70 -0
  589. qiskit/transpiler/passes/scheduling/alignments/reschedule.py +251 -0
  590. qiskit/transpiler/passes/scheduling/padding/__init__.py +16 -0
  591. qiskit/transpiler/passes/scheduling/padding/base_padding.py +284 -0
  592. qiskit/transpiler/passes/scheduling/padding/dynamical_decoupling.py +415 -0
  593. qiskit/transpiler/passes/scheduling/padding/pad_delay.py +90 -0
  594. qiskit/transpiler/passes/scheduling/scheduling/__init__.py +17 -0
  595. qiskit/transpiler/passes/scheduling/scheduling/alap.py +93 -0
  596. qiskit/transpiler/passes/scheduling/scheduling/asap.py +100 -0
  597. qiskit/transpiler/passes/scheduling/scheduling/base_scheduler.py +88 -0
  598. qiskit/transpiler/passes/scheduling/scheduling/set_io_latency.py +64 -0
  599. qiskit/transpiler/passes/scheduling/time_unit_conversion.py +237 -0
  600. qiskit/transpiler/passes/synthesis/__init__.py +20 -0
  601. qiskit/transpiler/passes/synthesis/aqc_plugin.py +153 -0
  602. qiskit/transpiler/passes/synthesis/default_unitary_synth_plugin.py +653 -0
  603. qiskit/transpiler/passes/synthesis/high_level_synthesis.py +429 -0
  604. qiskit/transpiler/passes/synthesis/hls_plugins.py +1963 -0
  605. qiskit/transpiler/passes/synthesis/linear_functions_synthesis.py +41 -0
  606. qiskit/transpiler/passes/synthesis/plugin.py +738 -0
  607. qiskit/transpiler/passes/synthesis/solovay_kitaev_synthesis.py +313 -0
  608. qiskit/transpiler/passes/synthesis/unitary_synthesis.py +425 -0
  609. qiskit/transpiler/passes/utils/__init__.py +32 -0
  610. qiskit/transpiler/passes/utils/barrier_before_final_measurements.py +41 -0
  611. qiskit/transpiler/passes/utils/check_gate_direction.py +60 -0
  612. qiskit/transpiler/passes/utils/check_map.py +78 -0
  613. qiskit/transpiler/passes/utils/contains_instruction.py +45 -0
  614. qiskit/transpiler/passes/utils/control_flow.py +61 -0
  615. qiskit/transpiler/passes/utils/dag_fixed_point.py +36 -0
  616. qiskit/transpiler/passes/utils/error.py +69 -0
  617. qiskit/transpiler/passes/utils/filter_op_nodes.py +66 -0
  618. qiskit/transpiler/passes/utils/fixed_point.py +48 -0
  619. qiskit/transpiler/passes/utils/gate_direction.py +93 -0
  620. qiskit/transpiler/passes/utils/gates_basis.py +51 -0
  621. qiskit/transpiler/passes/utils/merge_adjacent_barriers.py +163 -0
  622. qiskit/transpiler/passes/utils/minimum_point.py +118 -0
  623. qiskit/transpiler/passes/utils/remove_barriers.py +50 -0
  624. qiskit/transpiler/passes/utils/remove_final_measurements.py +121 -0
  625. qiskit/transpiler/passes/utils/unroll_forloops.py +81 -0
  626. qiskit/transpiler/passmanager.py +503 -0
  627. qiskit/transpiler/passmanager_config.py +151 -0
  628. qiskit/transpiler/preset_passmanagers/__init__.py +93 -0
  629. qiskit/transpiler/preset_passmanagers/builtin_plugins.py +993 -0
  630. qiskit/transpiler/preset_passmanagers/common.py +672 -0
  631. qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py +437 -0
  632. qiskit/transpiler/preset_passmanagers/level0.py +104 -0
  633. qiskit/transpiler/preset_passmanagers/level1.py +108 -0
  634. qiskit/transpiler/preset_passmanagers/level2.py +109 -0
  635. qiskit/transpiler/preset_passmanagers/level3.py +110 -0
  636. qiskit/transpiler/preset_passmanagers/plugin.py +346 -0
  637. qiskit/transpiler/target.py +905 -0
  638. qiskit/transpiler/timing_constraints.py +59 -0
  639. qiskit/user_config.py +266 -0
  640. qiskit/utils/__init__.py +90 -0
  641. qiskit/utils/classtools.py +146 -0
  642. qiskit/utils/deprecation.py +382 -0
  643. qiskit/utils/lazy_tester.py +363 -0
  644. qiskit/utils/optionals.py +354 -0
  645. qiskit/utils/parallel.py +318 -0
  646. qiskit/utils/units.py +146 -0
  647. qiskit/version.py +84 -0
  648. qiskit/visualization/__init__.py +290 -0
  649. qiskit/visualization/array.py +207 -0
  650. qiskit/visualization/bloch.py +778 -0
  651. qiskit/visualization/circuit/__init__.py +15 -0
  652. qiskit/visualization/circuit/_utils.py +675 -0
  653. qiskit/visualization/circuit/circuit_visualization.py +735 -0
  654. qiskit/visualization/circuit/latex.py +661 -0
  655. qiskit/visualization/circuit/matplotlib.py +2019 -0
  656. qiskit/visualization/circuit/qcstyle.py +278 -0
  657. qiskit/visualization/circuit/styles/__init__.py +13 -0
  658. qiskit/visualization/circuit/styles/bw.json +202 -0
  659. qiskit/visualization/circuit/styles/clifford.json +202 -0
  660. qiskit/visualization/circuit/styles/iqp-dark.json +214 -0
  661. qiskit/visualization/circuit/styles/iqp.json +214 -0
  662. qiskit/visualization/circuit/styles/textbook.json +202 -0
  663. qiskit/visualization/circuit/text.py +1849 -0
  664. qiskit/visualization/circuit_visualization.py +19 -0
  665. qiskit/visualization/counts_visualization.py +487 -0
  666. qiskit/visualization/dag_visualization.py +318 -0
  667. qiskit/visualization/exceptions.py +21 -0
  668. qiskit/visualization/gate_map.py +1424 -0
  669. qiskit/visualization/library.py +40 -0
  670. qiskit/visualization/pass_manager_visualization.py +312 -0
  671. qiskit/visualization/state_visualization.py +1546 -0
  672. qiskit/visualization/timeline/__init__.py +21 -0
  673. qiskit/visualization/timeline/core.py +495 -0
  674. qiskit/visualization/timeline/drawings.py +260 -0
  675. qiskit/visualization/timeline/generators.py +506 -0
  676. qiskit/visualization/timeline/interface.py +444 -0
  677. qiskit/visualization/timeline/layouts.py +115 -0
  678. qiskit/visualization/timeline/plotters/__init__.py +16 -0
  679. qiskit/visualization/timeline/plotters/base_plotter.py +58 -0
  680. qiskit/visualization/timeline/plotters/matplotlib.py +195 -0
  681. qiskit/visualization/timeline/stylesheet.py +301 -0
  682. qiskit/visualization/timeline/types.py +148 -0
  683. qiskit/visualization/transition_visualization.py +369 -0
  684. qiskit/visualization/utils.py +49 -0
  685. qiskit-2.0.3.dist-info/METADATA +220 -0
  686. qiskit-2.0.3.dist-info/RECORD +690 -0
  687. qiskit-2.0.3.dist-info/WHEEL +6 -0
  688. qiskit-2.0.3.dist-info/entry_points.txt +82 -0
  689. qiskit-2.0.3.dist-info/licenses/LICENSE.txt +203 -0
  690. qiskit-2.0.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1340 @@
1
+ # This code is part of Qiskit.
2
+ #
3
+ # (C) Copyright IBM 2021.
4
+ #
5
+ # This code is licensed under the Apache License, Version 2.0. You may
6
+ # obtain a copy of this license in the LICENSE.txt file in the root directory
7
+ # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
+ #
9
+ # Any modifications or derivative works of this code must retain this
10
+ # copyright notice, and modified files need to carry a notice indicating
11
+ # that they have been altered from the originals.
12
+
13
+ """QASM3 Exporter"""
14
+
15
+ from __future__ import annotations
16
+
17
+ import collections
18
+ import contextlib
19
+ import dataclasses
20
+ import io
21
+ import itertools
22
+ import math
23
+ import numbers
24
+ import re
25
+ from typing import Iterable, List, Sequence, Union
26
+
27
+ from qiskit._accelerate.circuit import StandardGate
28
+ from qiskit.circuit import (
29
+ library,
30
+ Barrier,
31
+ CircuitInstruction,
32
+ Clbit,
33
+ Gate,
34
+ Measure,
35
+ Parameter,
36
+ ParameterExpression,
37
+ QuantumCircuit,
38
+ Qubit,
39
+ Reset,
40
+ Delay,
41
+ Store,
42
+ Bit,
43
+ Register,
44
+ )
45
+ from qiskit.circuit.classical import expr, types
46
+ from qiskit.circuit.controlflow import (
47
+ BoxOp,
48
+ IfElseOp,
49
+ ForLoopOp,
50
+ WhileLoopOp,
51
+ SwitchCaseOp,
52
+ ControlFlowOp,
53
+ BreakLoopOp,
54
+ ContinueLoopOp,
55
+ CASE_DEFAULT,
56
+ )
57
+ from qiskit.circuit.tools import pi_check
58
+
59
+ from . import ast
60
+ from .experimental import ExperimentalFeatures
61
+ from .exceptions import QASM3ExporterError
62
+ from .printer import BasicPrinter
63
+
64
+ # Reserved keywords that gates and variables cannot be named. It is possible that some of these
65
+ # _could_ be accepted as variable names by OpenQASM 3 parsers, but it's safer for us to just be very
66
+ # conservative.
67
+ _RESERVED_KEYWORDS = frozenset(
68
+ {
69
+ "OPENQASM",
70
+ "angle",
71
+ "array",
72
+ "barrier",
73
+ "bit",
74
+ "bool",
75
+ "box",
76
+ "break",
77
+ "cal",
78
+ "complex",
79
+ "const",
80
+ "continue",
81
+ "creg",
82
+ "ctrl",
83
+ "def",
84
+ "defcal",
85
+ "defcalgrammar",
86
+ "delay",
87
+ "duration",
88
+ "durationof",
89
+ "else",
90
+ "end",
91
+ "extern",
92
+ "float",
93
+ "for",
94
+ "gate",
95
+ "gphase",
96
+ "if",
97
+ "in",
98
+ "include",
99
+ "input",
100
+ "int",
101
+ "inv",
102
+ "let",
103
+ "measure",
104
+ "mutable",
105
+ "negctrl",
106
+ "output",
107
+ "pow",
108
+ "qreg",
109
+ "qubit",
110
+ "reset",
111
+ "return",
112
+ "sizeof",
113
+ "stretch",
114
+ "uint",
115
+ "while",
116
+ }
117
+ )
118
+
119
+ # This probably isn't precisely the same as the OQ3 spec, but we'd need an extra dependency to fully
120
+ # handle all Unicode character classes, and this should be close enough for users who aren't
121
+ # actively _trying_ to break us (fingers crossed).
122
+ _VALID_DECLARABLE_IDENTIFIER = re.compile(r"([\w][\w\d]*)", flags=re.U)
123
+ _VALID_HARDWARE_QUBIT = re.compile(r"\$[\d]+", flags=re.U)
124
+ _BAD_IDENTIFIER_CHARACTERS = re.compile(r"[^\w\d]", flags=re.U)
125
+
126
+
127
+ class Exporter:
128
+ """QASM3 exporter main class."""
129
+
130
+ def __init__(
131
+ self,
132
+ includes: Sequence[str] = ("stdgates.inc",),
133
+ basis_gates: Sequence[str] = ("U",),
134
+ disable_constants: bool = False,
135
+ alias_classical_registers: bool = None,
136
+ allow_aliasing: bool = None,
137
+ indent: str = " ",
138
+ experimental: ExperimentalFeatures = ExperimentalFeatures(0),
139
+ ):
140
+ """
141
+ Args:
142
+ includes: the filenames that should be emitted as includes.
143
+
144
+ .. note::
145
+
146
+ At present, only the standard-library file ``stdgates.inc`` is properly
147
+ understood by the exporter, in the sense that it knows the gates it defines.
148
+ You can specify other includes, but you will need to pass the names of the gates
149
+ they define in the ``basis_gates`` argument to avoid the exporter outputting a
150
+ separate ``gate`` definition.
151
+
152
+ basis_gates: the basic defined gate set of the backend.
153
+ disable_constants: if ``True``, always emit floating-point constants for numeric
154
+ parameter values. If ``False`` (the default), then values close to multiples of
155
+ OpenQASM 3 constants (``pi``, ``euler``, and ``tau``) will be emitted in terms of those
156
+ constants instead, potentially improving accuracy in the output.
157
+ alias_classical_registers: If ``True``, then bits may be contained in more than one
158
+ register. If so, the registers will be emitted using "alias" definitions, which
159
+ might not be well supported by consumers of OpenQASM 3.
160
+
161
+ .. seealso::
162
+ Parameter ``allow_aliasing``
163
+ A value for ``allow_aliasing`` overrides any value given here, and
164
+ supersedes this parameter.
165
+ allow_aliasing: If ``True``, then bits may be contained in more than one register. If
166
+ so, the registers will be emitted using "alias" definitions, which might not be
167
+ well supported by consumers of OpenQASM 3. Defaults to ``False`` or the value of
168
+ ``alias_classical_registers``.
169
+
170
+ .. versionadded:: 0.25.0
171
+ indent: the indentation string to use for each level within an indented block. Can be
172
+ set to the empty string to disable indentation.
173
+ experimental: any experimental features to enable during the export. See
174
+ :class:`ExperimentalFeatures` for more details.
175
+ """
176
+ self.basis_gates = basis_gates
177
+ self.disable_constants = disable_constants
178
+ self.allow_aliasing = (
179
+ allow_aliasing if allow_aliasing is not None else (alias_classical_registers or False)
180
+ )
181
+ self.includes = list(includes)
182
+ self.indent = indent
183
+ self.experimental = experimental
184
+
185
+ def dumps(self, circuit):
186
+ """Convert the circuit to OpenQASM 3, returning the result as a string."""
187
+ with io.StringIO() as stream:
188
+ self.dump(circuit, stream)
189
+ return stream.getvalue()
190
+
191
+ def dump(self, circuit, stream):
192
+ """Convert the circuit to OpenQASM 3, dumping the result to a file or text stream."""
193
+ builder = QASM3Builder(
194
+ circuit,
195
+ includeslist=self.includes,
196
+ basis_gates=self.basis_gates,
197
+ disable_constants=self.disable_constants,
198
+ allow_aliasing=self.allow_aliasing,
199
+ experimental=self.experimental,
200
+ )
201
+ BasicPrinter(stream, indent=self.indent, experimental=self.experimental).visit(
202
+ builder.build_program()
203
+ )
204
+
205
+
206
+ # Just needs to have enough parameters to support the largest standard (non-controlled) gate in our
207
+ # standard library. We have to use the same `Parameter` instances each time so the equality
208
+ # comparisons will work.
209
+ _FIXED_PARAMETERS = (Parameter("p0"), Parameter("p1"), Parameter("p2"), Parameter("p3"))
210
+
211
+ _CANONICAL_STANDARD_GATES = {
212
+ standard: standard.gate_class(*_FIXED_PARAMETERS[: standard.num_params])
213
+ for standard in StandardGate.all_gates()
214
+ if not standard.is_controlled_gate
215
+ }
216
+ _CANONICAL_CONTROLLED_STANDARD_GATES = {
217
+ standard: [
218
+ standard.gate_class(*_FIXED_PARAMETERS[: standard.num_params], ctrl_state=ctrl_state)
219
+ for ctrl_state in range(1 << standard.num_ctrl_qubits)
220
+ ]
221
+ for standard in StandardGate.all_gates()
222
+ if standard.is_controlled_gate
223
+ }
224
+
225
+ # Mapping of symbols defined by `stdgates.inc` to their gate definition source.
226
+ _KNOWN_INCLUDES = {
227
+ "stdgates.inc": {
228
+ "p": _CANONICAL_STANDARD_GATES[StandardGate.PhaseGate],
229
+ "x": _CANONICAL_STANDARD_GATES[StandardGate.XGate],
230
+ "y": _CANONICAL_STANDARD_GATES[StandardGate.YGate],
231
+ "z": _CANONICAL_STANDARD_GATES[StandardGate.ZGate],
232
+ "h": _CANONICAL_STANDARD_GATES[StandardGate.HGate],
233
+ "s": _CANONICAL_STANDARD_GATES[StandardGate.SGate],
234
+ "sdg": _CANONICAL_STANDARD_GATES[StandardGate.SdgGate],
235
+ "t": _CANONICAL_STANDARD_GATES[StandardGate.TGate],
236
+ "tdg": _CANONICAL_STANDARD_GATES[StandardGate.TdgGate],
237
+ "sx": _CANONICAL_STANDARD_GATES[StandardGate.SXGate],
238
+ "rx": _CANONICAL_STANDARD_GATES[StandardGate.RXGate],
239
+ "ry": _CANONICAL_STANDARD_GATES[StandardGate.RYGate],
240
+ "rz": _CANONICAL_STANDARD_GATES[StandardGate.RZGate],
241
+ "cx": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CXGate][1],
242
+ "cy": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CYGate][1],
243
+ "cz": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CZGate][1],
244
+ "cp": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CPhaseGate][1],
245
+ "crx": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CRXGate][1],
246
+ "cry": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CRYGate][1],
247
+ "crz": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CRZGate][1],
248
+ "ch": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CHGate][1],
249
+ "swap": _CANONICAL_STANDARD_GATES[StandardGate.SwapGate],
250
+ "ccx": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CCXGate][3],
251
+ "cswap": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CSwapGate][1],
252
+ "cu": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CUGate][1],
253
+ "CX": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CXGate][1],
254
+ "phase": _CANONICAL_STANDARD_GATES[StandardGate.PhaseGate],
255
+ "cphase": _CANONICAL_CONTROLLED_STANDARD_GATES[StandardGate.CPhaseGate][1],
256
+ "id": _CANONICAL_STANDARD_GATES[StandardGate.IGate],
257
+ "u1": _CANONICAL_STANDARD_GATES[StandardGate.U1Gate],
258
+ "u2": _CANONICAL_STANDARD_GATES[StandardGate.U2Gate],
259
+ "u3": _CANONICAL_STANDARD_GATES[StandardGate.U3Gate],
260
+ },
261
+ }
262
+
263
+ _BUILTIN_GATES = {
264
+ "U": _CANONICAL_STANDARD_GATES[StandardGate.UGate],
265
+ }
266
+
267
+
268
+ @dataclasses.dataclass
269
+ class GateInfo:
270
+ """Symbol-table information on a gate."""
271
+
272
+ canonical: Gate | None
273
+ """The canonical object for the gate. This is a Qiskit object that is not necessarily equal to
274
+ any usage, but is the canonical form in terms of its parameter usage, such as a standard-library
275
+ gate being defined in terms of the `_FIXED_PARAMETERS` objects. A call-site gate whose
276
+ canonical form equals this can use the corresponding symbol as the callee.
277
+
278
+ This can be ``None`` if the gate was an overridden "basis gate" for this export, so no canonical
279
+ form is known."""
280
+ node: ast.QuantumGateDefinition | None
281
+ """An AST node containing the gate definition. This can be ``None`` if the gate came from an
282
+ included file, or is an overridden "basis gate" of the export."""
283
+
284
+
285
+ class SymbolTable:
286
+ """Track Qiskit objects and the OQ3 identifiers used to refer to them."""
287
+
288
+ def __init__(self):
289
+ self.gates: collections.OrderedDict[str, GateInfo | None] = {}
290
+ """Mapping of the symbol name to the "definition source" of the gate, which provides its
291
+ signature and decomposition. The definition source can be `None` if the user set the gate
292
+ as a custom "basis gate".
293
+
294
+ Gates can only be declared in the global scope, so there is just a single look-up for this.
295
+
296
+ This is insertion ordered, and that can be relied on for iteration later."""
297
+ self.standard_gate_idents: dict[StandardGate, ast.Identifier] = {}
298
+ """Mapping of standard gate enumeration values to the identifier we represent that as."""
299
+ self.user_gate_idents: dict[int, ast.Identifier] = {}
300
+ """Mapping of `id`s of user gates to the identifier we use for it."""
301
+
302
+ self.variables: list[dict[str, object]] = [{}]
303
+ """Stack of mappings of variable names to the Qiskit object that represents them.
304
+
305
+ The zeroth index corresponds to the global scope, the highest index to the current scope."""
306
+ self.objects: list[dict[object, ast.Identifier]] = [{}]
307
+ """Stack of mappings of Qiskit objects to the identifier (or subscripted identifier) that
308
+ refers to them. This is similar to the inverse mapping of ``variables``.
309
+
310
+ The zeroth index corresponds to the global scope, the highest index to the current scope."""
311
+
312
+ # Quick-and-dirty method of getting unique salts for names.
313
+ self._counter = itertools.count()
314
+
315
+ def push_scope(self):
316
+ """Enter a new variable scope."""
317
+ self.variables.append({})
318
+ self.objects.append({})
319
+
320
+ def pop_scope(self):
321
+ """Exit the current scope, returning to a previous scope."""
322
+ self.objects.pop()
323
+ self.variables.pop()
324
+
325
+ def new_context(self) -> SymbolTable:
326
+ """Create a new context, such as for a gate definition.
327
+
328
+ Contexts share the same set of globally defined gates, but have no access to other variables
329
+ defined in any scope."""
330
+ out = SymbolTable()
331
+ out.gates = self.gates
332
+ out.standard_gate_idents = self.standard_gate_idents
333
+ out.user_gate_idents = self.user_gate_idents
334
+ return out
335
+
336
+ def symbol_defined(self, name: str) -> bool:
337
+ """Whether this identifier has a defined meaning already."""
338
+ return (
339
+ name in _RESERVED_KEYWORDS
340
+ or name in self.gates
341
+ or name in itertools.chain.from_iterable(reversed(self.variables))
342
+ )
343
+
344
+ def can_shadow_symbol(self, name: str) -> bool:
345
+ """Whether a new definition of this symbol can be made within the OpenQASM 3 shadowing
346
+ rules."""
347
+ return (
348
+ name not in self.variables[-1]
349
+ and name not in self.gates
350
+ and name not in _RESERVED_KEYWORDS
351
+ )
352
+
353
+ def escaped_declarable_name(self, name: str, *, allow_rename: bool, unique: bool = False):
354
+ """Get an identifier based on ``name`` that can be safely shadowed within this scope.
355
+
356
+ If ``unique`` is ``True``, then the name is required to be unique across all live scopes,
357
+ not just able to be redefined."""
358
+ name_allowed = (
359
+ (lambda name: not self.symbol_defined(name)) if unique else self.can_shadow_symbol
360
+ )
361
+ valid_identifier = _VALID_DECLARABLE_IDENTIFIER
362
+ if allow_rename:
363
+ if not valid_identifier.fullmatch(name):
364
+ name = "_" + _BAD_IDENTIFIER_CHARACTERS.sub("_", name)
365
+ base = name
366
+ while not name_allowed(name):
367
+ name = f"{base}_{next(self._counter)}"
368
+ return name
369
+ if not valid_identifier.fullmatch(name):
370
+ raise QASM3ExporterError(f"cannot use '{name}' as a name; it is not a valid identifier")
371
+ if name in _RESERVED_KEYWORDS:
372
+ raise QASM3ExporterError(f"cannot use the keyword '{name}' as a variable name")
373
+ if not name_allowed(name):
374
+ if self.gates.get(name) is not None:
375
+ raise QASM3ExporterError(
376
+ f"cannot shadow variable '{name}', as it is already defined as a gate"
377
+ )
378
+ for scope in reversed(self.variables):
379
+ if (other := scope.get(name)) is not None:
380
+ break
381
+ else: # pragma: no cover
382
+ raise RuntimeError(f"internal error: could not locate unshadowable '{name}'")
383
+ raise QASM3ExporterError(
384
+ f"cannot shadow variable '{name}', as it is already defined as '{other}'"
385
+ )
386
+ return name
387
+
388
+ def register_variable(
389
+ self,
390
+ name: str,
391
+ variable: object,
392
+ *,
393
+ allow_rename: bool,
394
+ force_global: bool = False,
395
+ allow_hardware_qubit: bool = False,
396
+ ) -> ast.Identifier:
397
+ """Register a variable in the symbol table for the given scope, returning the name that
398
+ should be used to refer to the variable. The same name will be returned by subsequent calls
399
+ to :meth:`get_variable` within the same scope.
400
+
401
+ Args:
402
+ name: the name to base the identifier on.
403
+ variable: the Qiskit object this refers to. This can be ``None`` in the case of
404
+ reserving a dummy variable name that does not actually have a Qiskit object backing
405
+ it.
406
+ allow_rename: whether to allow the name to be mutated to escape it and/or make it safe
407
+ to define (avoiding keywords, subject to shadowing rules, etc).
408
+ force_global: force this declaration to be in the global scope.
409
+ allow_hardware_qubit: whether to allow hardware qubits to pass through as identifiers.
410
+ Hardware qubits are a dollar sign followed by a non-negative integer, and cannot be
411
+ declared, so are not suitable identifiers for most objects.
412
+ """
413
+ scope_index = 0 if force_global else -1
414
+ # We still need to do this escaping and shadow checking if `force_global`, because we don't
415
+ # want a previous variable declared in the currently active scope to shadow the global.
416
+ # This logic would be cleaner if we made the naming choices later, after AST generation
417
+ # (e.g. by using only indices as the identifiers until we're outputting the program).
418
+ if allow_hardware_qubit and _VALID_HARDWARE_QUBIT.fullmatch(name):
419
+ if self.symbol_defined(name): # pragma: no cover
420
+ raise QASM3ExporterError(f"internal error: cannot redeclare hardware qubit {name}")
421
+ else:
422
+ name = self.escaped_declarable_name(
423
+ name, allow_rename=allow_rename, unique=force_global
424
+ )
425
+ identifier = ast.Identifier(name)
426
+ self.variables[scope_index][name] = variable
427
+ if variable is not None:
428
+ self.objects[scope_index][variable] = identifier
429
+ return identifier
430
+
431
+ def set_object_ident(self, ident: ast.Identifier, variable: object):
432
+ """Set the identifier used to refer to a given object for this scope.
433
+
434
+ This overwrites any previously set identifier, such as during the original registration.
435
+
436
+ This is generally only useful for tracking "sub" objects, like bits out of a register, which
437
+ will have an `SubscriptedIdentifier` as their identifier."""
438
+ self.objects[-1][variable] = ident
439
+
440
+ def get_variable(self, variable: object) -> ast.Identifier:
441
+ """Lookup a non-gate variable in the symbol table."""
442
+ for scope in reversed(self.objects):
443
+ if (out := scope.get(variable)) is not None:
444
+ return out
445
+ raise KeyError(f"'{variable}' is not defined in the current context")
446
+
447
+ def register_gate_without_definition(self, name: str, gate: Gate | None) -> ast.Identifier:
448
+ """Register a gate that does not require an OQ3 definition.
449
+
450
+ If the ``gate`` is given, it will be used to validate that a call to it is compatible (such
451
+ as a known gate from an included file). If it is not given, it is treated as a user-defined
452
+ "basis gate" that assumes that all calling signatures are valid and that all gates of this
453
+ name are exactly compatible, which is somewhat dangerous."""
454
+ # Validate the name is usable.
455
+ name = self.escaped_declarable_name(name, allow_rename=False, unique=False)
456
+ ident = ast.Identifier(name)
457
+ if gate is None:
458
+ self.gates[name] = GateInfo(None, None)
459
+ else:
460
+ canonical = _gate_canonical_form(gate)
461
+ self.gates[name] = GateInfo(canonical, None)
462
+ if canonical._standard_gate is not None:
463
+ self.standard_gate_idents[canonical._standard_gate] = ident
464
+ else:
465
+ self.user_gate_idents[id(canonical)] = ident
466
+ return ident
467
+
468
+ def register_gate(
469
+ self,
470
+ name: str,
471
+ source: Gate,
472
+ params: Iterable[ast.Identifier],
473
+ qubits: Iterable[ast.Identifier],
474
+ body: ast.QuantumBlock,
475
+ ) -> ast.Identifier:
476
+ """Register the given gate in the symbol table, using the given components to build up the
477
+ full AST definition."""
478
+ name = self.escaped_declarable_name(name, allow_rename=True, unique=False)
479
+ ident = ast.Identifier(name)
480
+ self.gates[name] = GateInfo(
481
+ source, ast.QuantumGateDefinition(ident, tuple(params), tuple(qubits), body)
482
+ )
483
+ # Add the gate object with a magic lookup keep to the objects dictionary so we can retrieve
484
+ # it later. Standard gates are not guaranteed to have stable IDs (they're preferentially
485
+ # not even created in Python space), but user gates are.
486
+ if source._standard_gate is not None:
487
+ self.standard_gate_idents[source._standard_gate] = ident
488
+ else:
489
+ self.user_gate_idents[id(source)] = ident
490
+ return ident
491
+
492
+ def get_gate(self, gate: Gate) -> ast.Identifier | None:
493
+ """Lookup the identifier for a given `Gate`, if it exists."""
494
+ canonical = _gate_canonical_form(gate)
495
+ if (our_defn := self.gates.get(gate.name)) is not None and (
496
+ # We arrange things such that the known definitions for the vast majority of gates we
497
+ # will encounter are the exact same canonical instance, so an `is` check saves time.
498
+ our_defn.canonical is canonical
499
+ # `our_defn.canonical is None` means a basis gate that we should assume is always valid.
500
+ or our_defn.canonical is None
501
+ # The last catch, if the canonical form is some custom gate that compares equal to this.
502
+ or our_defn.canonical == canonical
503
+ ):
504
+ return ast.Identifier(gate.name)
505
+ if canonical._standard_gate is not None:
506
+ if (our_ident := self.standard_gate_idents.get(canonical._standard_gate)) is None:
507
+ return None
508
+ return our_ident if self.gates[our_ident.string].canonical == canonical else None
509
+ # No need to check equality if we're looking up by `id`; we must have the same object.
510
+ return self.user_gate_idents.get(id(canonical))
511
+
512
+
513
+ def _gate_canonical_form(gate: Gate) -> Gate:
514
+ """Get the canonical form of a gate.
515
+
516
+ This is the gate object that should be used to provide the OpenQASM 3 definition of a gate (but
517
+ not the call site; that's the input object). This lets us return a re-parametrised gate in
518
+ terms of general parameters, in cases where we can be sure that that is valid. This is
519
+ currently only Qiskit standard gates. This lets multiple call-site gates match the same symbol,
520
+ in the case of parametric gates.
521
+
522
+ The definition source provides the number of qubits, the parameter signature and the body of the
523
+ `gate` statement. It does not provide the name of the symbol being defined."""
524
+ # If a gate is part of the Qiskit standard-library gates, we know we can safely produce a
525
+ # reparameterised gate by passing the parameters positionally to the standard-gate constructor
526
+ # (and control state, if appropriate).
527
+ standard = gate._standard_gate
528
+ if standard is None:
529
+ return gate
530
+ return (
531
+ _CANONICAL_CONTROLLED_STANDARD_GATES[standard][gate.ctrl_state]
532
+ if standard.is_controlled_gate
533
+ else _CANONICAL_STANDARD_GATES[standard]
534
+ )
535
+
536
+
537
+ @dataclasses.dataclass
538
+ class BuildScope:
539
+ """The structure used in the builder to store the contexts and re-mappings of bits from the
540
+ top-level scope where the bits were actually defined."""
541
+
542
+ circuit: QuantumCircuit
543
+ """The circuit block that we're currently working on exporting."""
544
+ bit_map: dict[Bit, Bit]
545
+ """Mapping of bit objects in ``circuit`` to the bit objects in the global-scope program
546
+ :class:`.QuantumCircuit` that they are bound to."""
547
+
548
+
549
+ class QASM3Builder:
550
+ """QASM3 builder constructs an AST from a QuantumCircuit."""
551
+
552
+ builtins = (Barrier, Measure, Reset, Delay, BreakLoopOp, ContinueLoopOp, Store)
553
+ loose_bit_prefix = "_bit"
554
+ loose_qubit_prefix = "_qubit"
555
+ gate_parameter_prefix = "_gate_p"
556
+ gate_qubit_prefix = "_gate_q"
557
+
558
+ def __init__(
559
+ self,
560
+ quantumcircuit,
561
+ includeslist,
562
+ basis_gates,
563
+ disable_constants,
564
+ allow_aliasing,
565
+ experimental=ExperimentalFeatures(0),
566
+ ):
567
+ self.scope = BuildScope(
568
+ quantumcircuit,
569
+ {x: x for x in itertools.chain(quantumcircuit.qubits, quantumcircuit.clbits)},
570
+ )
571
+ self.symbols = SymbolTable()
572
+ # `_global_io_declarations` and `_global_classical_declarations` are stateful, and any
573
+ # operation that needs a parameter can append to them during the build. We make all
574
+ # classical declarations global because the IBM qe-compiler stack (our initial consumer of
575
+ # OQ3 strings) prefers declarations to all be global, and it's valid OQ3, so it's not vendor
576
+ # lock-in. It's possibly slightly memory inefficient, but that's not likely to be a problem
577
+ # in the near term.
578
+ self._global_io_declarations = []
579
+ self._global_classical_forward_declarations = []
580
+ self.disable_constants = disable_constants
581
+ self.allow_aliasing = allow_aliasing
582
+ self.includes = includeslist
583
+ self.basis_gates = basis_gates
584
+ self.experimental = experimental
585
+
586
+ @contextlib.contextmanager
587
+ def new_scope(self, circuit: QuantumCircuit, qubits: Iterable[Qubit], clbits: Iterable[Clbit]):
588
+ """Context manager that pushes a new scope (like a ``for`` or ``while`` loop body) onto the
589
+ current context stack."""
590
+ current_map = self.scope.bit_map
591
+ qubits = tuple(current_map[qubit] for qubit in qubits)
592
+ clbits = tuple(current_map[clbit] for clbit in clbits)
593
+ if circuit.num_qubits != len(qubits):
594
+ raise QASM3ExporterError( # pragma: no cover
595
+ f"Tried to push a scope whose circuit needs {circuit.num_qubits} qubits, but only"
596
+ f" provided {len(qubits)} qubits to create the mapping."
597
+ )
598
+ if circuit.num_clbits != len(clbits):
599
+ raise QASM3ExporterError( # pragma: no cover
600
+ f"Tried to push a scope whose circuit needs {circuit.num_clbits} clbits, but only"
601
+ f" provided {len(clbits)} clbits to create the mapping."
602
+ )
603
+ mapping = dict(itertools.chain(zip(circuit.qubits, qubits), zip(circuit.clbits, clbits)))
604
+ self.symbols.push_scope()
605
+ old_scope, self.scope = self.scope, BuildScope(circuit, mapping)
606
+ yield self.scope
607
+ self.scope = old_scope
608
+ self.symbols.pop_scope()
609
+
610
+ @contextlib.contextmanager
611
+ def new_context(self, body: QuantumCircuit):
612
+ """Push a new context (like for a ``gate`` or ``def`` body) onto the stack."""
613
+ mapping = {bit: bit for bit in itertools.chain(body.qubits, body.clbits)}
614
+
615
+ old_symbols, self.symbols = self.symbols, self.symbols.new_context()
616
+ old_scope, self.scope = self.scope, BuildScope(body, mapping)
617
+ yield self.scope
618
+ self.scope = old_scope
619
+ self.symbols = old_symbols
620
+
621
+ def _lookup_bit(self, bit) -> ast.Identifier:
622
+ """Lookup a Qiskit bit within the current context, and return the name that should be
623
+ used to represent it in OpenQASM 3 programmes."""
624
+ return self.symbols.get_variable(self.scope.bit_map[bit])
625
+
626
+ def build_program(self):
627
+ """Builds a Program"""
628
+ circuit = self.scope.circuit
629
+ if circuit.num_captured_vars or circuit.num_captured_stretches:
630
+ raise QASM3ExporterError(
631
+ "cannot export an inner scope with captured variables as a top-level program"
632
+ )
633
+
634
+ # The order we build parts of the AST has an effect on which names will get escaped to avoid
635
+ # collisions. The current ideas are:
636
+ #
637
+ # * standard-library include files _must_ define symbols of the correct name.
638
+ # * classical registers, IO variables and `Var` nodes are likely to be referred to by name
639
+ # by a user, so they get very high priority - we search for them before doing anything.
640
+ # * qubit registers are not typically referred to by name by users, so they get a lower
641
+ # priority than the classical variables.
642
+ # * we often have to escape user-defined gate names anyway because of our dodgy parameter
643
+ # handling, so they get the lowest priority; they get defined as they are encountered.
644
+ #
645
+ # An alternative approach would be to defer naming decisions until we are outputting the
646
+ # AST, and using some UUID for each symbol we're going to define in the interrim. This
647
+ # would require relatively large changes to the symbol-table and AST handling, however.
648
+
649
+ for builtin, gate in _BUILTIN_GATES.items():
650
+ self.symbols.register_gate_without_definition(builtin, gate)
651
+ for builtin in self.basis_gates:
652
+ if builtin in _BUILTIN_GATES:
653
+ # It's built into the langauge; we don't need to re-add it.
654
+ continue
655
+ try:
656
+ self.symbols.register_gate_without_definition(builtin, None)
657
+ except QASM3ExporterError as exc:
658
+ raise QASM3ExporterError(
659
+ f"Cannot use '{builtin}' as a basis gate for the reason in the prior exception."
660
+ " Consider renaming the gate if needed, or omitting this basis gate if not."
661
+ ) from exc
662
+
663
+ header = ast.Header(ast.Version("3.0"), list(self.build_includes()))
664
+
665
+ # Early IBM runtime parametrization uses unbound `Parameter` instances as `input` variables,
666
+ # not the explicit realtime `Var` variables, so we need this explicit scan.
667
+ self.hoist_global_parameter_declarations()
668
+ # Qiskit's clbits and classical registers need to get mapped to implicit OQ3 variables, but
669
+ # only if they're in the top-level circuit. The QuantumCircuit data model is that inner
670
+ # clbits are bound to outer bits, and inner registers must be closing over outer ones.
671
+ self.hoist_classical_register_declarations()
672
+ # We hoist registers before new-style vars because registers are an older part of the data
673
+ # model (and used implicitly in PrimitivesV2 outputs) so they get the first go at reserving
674
+ # names in the symbol table.
675
+ self.hoist_classical_io_var_declarations()
676
+
677
+ # Similarly, QuantumCircuit qubits/registers are only new variables in the global scope.
678
+ quantum_declarations = self.build_quantum_declarations()
679
+
680
+ # This call has side-effects - it can populate `self._global_io_declarations` and
681
+ # `self._global_classical_declarations` as a courtesy to the qe-compiler that prefers our
682
+ # hacky temporary `switch` target variables to be globally defined. It also populates the
683
+ # symbol table with encountered gates that weren't previously defined.
684
+ main_statements = self.build_current_scope()
685
+
686
+ statements = [
687
+ statement
688
+ for source in (
689
+ # In older versions of the reference OQ3 grammar, IO declarations had to come before
690
+ # anything else, so we keep doing that as a courtesy.
691
+ self._global_io_declarations,
692
+ (gate.node for gate in self.symbols.gates.values() if gate.node is not None),
693
+ self._global_classical_forward_declarations,
694
+ quantum_declarations,
695
+ main_statements,
696
+ )
697
+ for statement in source
698
+ ]
699
+ return ast.Program(header, statements)
700
+
701
+ def build_includes(self):
702
+ """Builds a list of included files."""
703
+ for filename in self.includes:
704
+ # Note: unknown include files have a corresponding `include` statement generated, but do
705
+ # not actually define any gates; we rely on the user to pass those in `basis_gates`.
706
+ for name, gate in _KNOWN_INCLUDES.get(filename, {}).items():
707
+ self.symbols.register_gate_without_definition(name, gate)
708
+ yield ast.Include(filename)
709
+
710
+ def define_gate(self, gate: Gate) -> ast.Identifier:
711
+ """Define a gate in the symbol table, including building the gate-definition statement for
712
+ it.
713
+
714
+ This recurses through gate-definition statements."""
715
+ if issubclass(gate.base_class, library.CXGate) and gate.ctrl_state == 1:
716
+ # CX gets super duper special treatment because it's the base of Qiskit's definition
717
+ # tree, but isn't an OQ3 built-in (it was in OQ2). We use `issubclass` because we
718
+ # haven't fully fixed what the name/class distinction is (there's a test from the
719
+ # original OQ3 exporter that tries a naming collision with 'cx').
720
+ control, target = ast.Identifier("c"), ast.Identifier("t")
721
+ body = ast.QuantumBlock(
722
+ [
723
+ ast.QuantumGateCall(
724
+ self.symbols.get_gate(library.UGate(math.pi, 0, math.pi)),
725
+ [control, target],
726
+ parameters=[ast.Constant.PI, ast.IntegerLiteral(0), ast.Constant.PI],
727
+ modifiers=[ast.QuantumGateModifier(ast.QuantumGateModifierName.CTRL)],
728
+ )
729
+ ]
730
+ )
731
+ return self.symbols.register_gate(gate.name, gate, (), (control, target), body)
732
+ if gate.definition is None:
733
+ raise QASM3ExporterError(f"failed to export gate '{gate.name}' that has no definition")
734
+ canonical = _gate_canonical_form(gate)
735
+ with self.new_context(canonical.definition):
736
+ defn = self.scope.circuit
737
+ # If `defn.num_parameters == 0` but `gate.params` is non-empty, we are likely in the
738
+ # case where the gate's circuit definition is fully bound (so we can't detect its inputs
739
+ # anymore). This is a problem in our data model - for arbitrary user gates, there's no
740
+ # way we can reliably get a parametric version of the gate through our interfaces. In
741
+ # this case, we output a gate that has dummy parameters, and rely on it being a
742
+ # different `id` each time to avoid duplication. We assume that the parametrisation
743
+ # order matches (which is a _big_ assumption).
744
+ #
745
+ # If `defn.num_parameters > 0`, we enforce that it must match how it's called.
746
+ if defn.num_parameters > 0:
747
+ if defn.num_parameters != len(gate.params):
748
+ raise QASM3ExporterError(
749
+ "parameter mismatch in definition of '{gate}':"
750
+ f" call has {len(gate.params)}, definition has {defn.num_parameters}"
751
+ )
752
+ params = [
753
+ self.symbols.register_variable(param.name, param, allow_rename=True)
754
+ for param in defn.parameters
755
+ ]
756
+ else:
757
+ # Fill with dummy parameters. The name is unimportant, because they're not actually
758
+ # used in the definition.
759
+ params = [
760
+ self.symbols.register_variable(
761
+ f"{self.gate_parameter_prefix}_{i}", None, allow_rename=True
762
+ )
763
+ for i in range(len(gate.params))
764
+ ]
765
+ qubits = [
766
+ self.symbols.register_variable(
767
+ f"{self.gate_qubit_prefix}_{i}", qubit, allow_rename=True
768
+ )
769
+ for i, qubit in enumerate(defn.qubits)
770
+ ]
771
+ body = ast.QuantumBlock(self.build_current_scope())
772
+ # We register the gate only after building its body so that any gates we needed for that in
773
+ # turn are registered in the correct order. Gates can't be recursive in OQ3, so there's no
774
+ # problem with delaying this.
775
+ return self.symbols.register_gate(canonical.name, canonical, params, qubits, body)
776
+
777
+ def assert_global_scope(self):
778
+ """Raise an error if we are not in the global scope, as a defensive measure."""
779
+ if len(self.symbols.variables) > 1: # pragma: no cover
780
+ raise RuntimeError("not currently in the global scope")
781
+
782
+ def hoist_global_parameter_declarations(self):
783
+ """Extend ``self._global_io_declarations`` and ``self._global_classical_declarations`` with
784
+ any implicit declarations used to support the early IBM efforts to use :class:`.Parameter`
785
+ as an input variable."""
786
+ self.assert_global_scope()
787
+ circuit = self.scope.circuit
788
+ for parameter in circuit.parameters:
789
+ parameter_name = self.symbols.register_variable(
790
+ parameter.name, parameter, allow_rename=True
791
+ )
792
+ declaration = _infer_variable_declaration(circuit, parameter, parameter_name)
793
+ if declaration is None:
794
+ continue
795
+ if isinstance(declaration, ast.IODeclaration):
796
+ self._global_io_declarations.append(declaration)
797
+ else:
798
+ self._global_classical_forward_declarations.append(declaration)
799
+
800
+ def hoist_classical_register_declarations(self):
801
+ """Extend the global classical declarations with AST nodes declaring all the global-scope
802
+ circuit :class:`.Clbit` and :class:`.ClassicalRegister` instances. Qiskit's data model
803
+ doesn't involve the declaration of *new* bits or registers in inner scopes; only the
804
+ :class:`.expr.Var` mechanism allows that.
805
+
806
+ The behavior of this function depends on the setting ``allow_aliasing``. If this
807
+ is ``True``, then the output will be in the same form as the output of
808
+ :meth:`.build_classical_declarations`, with the registers being aliases. If ``False``, it
809
+ will instead return a :obj:`.ast.ClassicalDeclaration` for each classical register, and one
810
+ for the loose :obj:`.Clbit` instances, and will raise :obj:`QASM3ExporterError` if any
811
+ registers overlap.
812
+ """
813
+ self.assert_global_scope()
814
+ circuit = self.scope.circuit
815
+ if any(len(circuit.find_bit(q).registers) > 1 for q in circuit.clbits):
816
+ # There are overlapping registers, so we need to use aliases to emit the structure.
817
+ if not self.allow_aliasing:
818
+ raise QASM3ExporterError(
819
+ "Some classical registers in this circuit overlap and need aliases to express,"
820
+ " but 'allow_aliasing' is false."
821
+ )
822
+ clbits = (
823
+ ast.ClassicalDeclaration(
824
+ ast.BitType(),
825
+ self.symbols.register_variable(
826
+ f"{self.loose_bit_prefix}{i}", clbit, allow_rename=True
827
+ ),
828
+ )
829
+ for i, clbit in enumerate(circuit.clbits)
830
+ )
831
+ self._global_classical_forward_declarations.extend(clbits)
832
+ self._global_classical_forward_declarations.extend(self.build_aliases(circuit.cregs))
833
+ return
834
+ # If we're here, we're in the clbit happy path where there are no clbits that are in more
835
+ # than one register. We can output things very naturally.
836
+ self._global_classical_forward_declarations.extend(
837
+ ast.ClassicalDeclaration(
838
+ ast.BitType(),
839
+ self.symbols.register_variable(
840
+ f"{self.loose_bit_prefix}{i}", clbit, allow_rename=True
841
+ ),
842
+ )
843
+ for i, clbit in enumerate(circuit.clbits)
844
+ if not circuit.find_bit(clbit).registers
845
+ )
846
+ for register in circuit.cregs:
847
+ name = self.symbols.register_variable(register.name, register, allow_rename=True)
848
+ for i, bit in enumerate(register):
849
+ self.symbols.set_object_ident(
850
+ ast.SubscriptedIdentifier(name.string, ast.IntegerLiteral(i)), bit
851
+ )
852
+ self._global_classical_forward_declarations.append(
853
+ ast.ClassicalDeclaration(ast.BitArrayType(len(register)), name)
854
+ )
855
+
856
+ def hoist_classical_io_var_declarations(self):
857
+ """Hoist the declarations of classical IO :class:`.expr.Var` nodes into the global state.
858
+
859
+ Local :class:`.expr.Var` declarations are handled by the regular local-block scope builder,
860
+ and the :class:`.QuantumCircuit` data model ensures that the only time an IO variable can
861
+ occur is in an outermost block."""
862
+ self.assert_global_scope()
863
+ circuit = self.scope.circuit
864
+ for var in circuit.iter_input_vars():
865
+ self._global_io_declarations.append(
866
+ ast.IODeclaration(
867
+ ast.IOModifier.INPUT,
868
+ _build_ast_type(var.type),
869
+ self.symbols.register_variable(var.name, var, allow_rename=True),
870
+ )
871
+ )
872
+
873
+ def build_quantum_declarations(self):
874
+ """Return a list of AST nodes declaring all the qubits in the current scope, and all the
875
+ alias declarations for these qubits."""
876
+ self.assert_global_scope()
877
+ circuit = self.scope.circuit
878
+ if circuit.layout is not None:
879
+ # We're referring to physical qubits. These can't be declared in OQ3, but we need to
880
+ # track the bit -> expression mapping in our symbol table.
881
+ for i, bit in enumerate(circuit.qubits):
882
+ self.symbols.register_variable(
883
+ f"${i}", bit, allow_rename=False, allow_hardware_qubit=True
884
+ )
885
+ return []
886
+ if any(len(circuit.find_bit(q).registers) > 1 for q in circuit.qubits):
887
+ # There are overlapping registers, so we need to use aliases to emit the structure.
888
+ if not self.allow_aliasing:
889
+ raise QASM3ExporterError(
890
+ "Some quantum registers in this circuit overlap and need aliases to express,"
891
+ " but 'allow_aliasing' is false."
892
+ )
893
+ qubits = [
894
+ ast.QuantumDeclaration(
895
+ self.symbols.register_variable(
896
+ f"{self.loose_qubit_prefix}{i}", qubit, allow_rename=True
897
+ )
898
+ )
899
+ for i, qubit in enumerate(circuit.qubits)
900
+ ]
901
+ return qubits + self.build_aliases(circuit.qregs)
902
+ # If we're here, we're in the virtual-qubit happy path where there are no qubits that are in
903
+ # more than one register. We can output things very naturally.
904
+ loose_qubits = [
905
+ ast.QuantumDeclaration(
906
+ self.symbols.register_variable(
907
+ f"{self.loose_qubit_prefix}{i}", qubit, allow_rename=True
908
+ )
909
+ )
910
+ for i, qubit in enumerate(circuit.qubits)
911
+ if not circuit.find_bit(qubit).registers
912
+ ]
913
+ registers = []
914
+ for register in circuit.qregs:
915
+ name = self.symbols.register_variable(register.name, register, allow_rename=True)
916
+ for i, bit in enumerate(register):
917
+ self.symbols.set_object_ident(
918
+ ast.SubscriptedIdentifier(name.string, ast.IntegerLiteral(i)), bit
919
+ )
920
+ registers.append(
921
+ ast.QuantumDeclaration(name, ast.Designator(ast.IntegerLiteral(len(register))))
922
+ )
923
+ return loose_qubits + registers
924
+
925
+ def build_aliases(self, registers: Iterable[Register]) -> List[ast.AliasStatement]:
926
+ """Return a list of alias declarations for the given registers. The registers can be either
927
+ classical or quantum."""
928
+ out = []
929
+ for register in registers:
930
+ name = self.symbols.register_variable(register.name, register, allow_rename=True)
931
+ elements = [self._lookup_bit(bit) for bit in register]
932
+ for i, bit in enumerate(register):
933
+ # This might shadow previous definitions, but that's not a problem.
934
+ self.symbols.set_object_ident(
935
+ ast.SubscriptedIdentifier(name.string, ast.IntegerLiteral(i)), bit
936
+ )
937
+ out.append(ast.AliasStatement(name, ast.IndexSet(elements)))
938
+ return out
939
+
940
+ def build_current_scope(self) -> List[ast.Statement]:
941
+ """Build the instructions that occur in the current scope.
942
+
943
+ In addition to everything literally in the circuit's ``data`` field, this also includes
944
+ declarations for any local :class:`.expr.Var` nodes.
945
+ """
946
+
947
+ # We forward-declare all local variables uninitialised at the top of their scope. It would
948
+ # be nice to declare the variable at the point of first store (so we can write things like
949
+ # `uint[8] a = 12;`), but there's lots of edge-case logic to catch with that around
950
+ # use-before-definition errors in the OQ3 output, for example if the user has side-stepped
951
+ # the `QuantumCircuit` API protection to produce a circuit that uses an uninitialised
952
+ # variable, or the initial write to a variable is within a control-flow scope. (It would be
953
+ # easier to see the def/use chain needed to do this cleanly if we were using `DAGCircuit`.)
954
+ statements = [
955
+ ast.ClassicalDeclaration(
956
+ _build_ast_type(var.type),
957
+ self.symbols.register_variable(var.name, var, allow_rename=True),
958
+ )
959
+ for var in self.scope.circuit.iter_declared_vars()
960
+ ]
961
+
962
+ for stretch in self.scope.circuit.iter_declared_stretches():
963
+ statements.append(
964
+ ast.StretchDeclaration(
965
+ self.symbols.register_variable(stretch.name, stretch, allow_rename=True),
966
+ )
967
+ )
968
+
969
+ for instruction in self.scope.circuit.data:
970
+ if isinstance(instruction.operation, ControlFlowOp):
971
+ if isinstance(instruction.operation, ForLoopOp):
972
+ statements.append(self.build_for_loop(instruction))
973
+ elif isinstance(instruction.operation, WhileLoopOp):
974
+ statements.append(self.build_while_loop(instruction))
975
+ elif isinstance(instruction.operation, IfElseOp):
976
+ statements.append(self.build_if_statement(instruction))
977
+ elif isinstance(instruction.operation, SwitchCaseOp):
978
+ statements.extend(self.build_switch_statement(instruction))
979
+ elif isinstance(instruction.operation, BoxOp):
980
+ statements.append(self.build_box(instruction))
981
+ else:
982
+ raise RuntimeError(f"unhandled control-flow construct: {instruction.operation}")
983
+ continue
984
+ # Build the node, ignoring any condition.
985
+ if isinstance(instruction.operation, Gate):
986
+ nodes = [self.build_gate_call(instruction)]
987
+ elif isinstance(instruction.operation, Barrier):
988
+ operands = [self._lookup_bit(operand) for operand in instruction.qubits]
989
+ nodes = [ast.QuantumBarrier(operands)]
990
+ elif isinstance(instruction.operation, Measure):
991
+ measurement = ast.QuantumMeasurement(
992
+ [self._lookup_bit(operand) for operand in instruction.qubits]
993
+ )
994
+ qubit = self._lookup_bit(instruction.clbits[0])
995
+ nodes = [ast.QuantumMeasurementAssignment(qubit, measurement)]
996
+ elif isinstance(instruction.operation, Reset):
997
+ nodes = [
998
+ ast.QuantumReset(self._lookup_bit(operand)) for operand in instruction.qubits
999
+ ]
1000
+ elif isinstance(instruction.operation, Delay):
1001
+ nodes = [self.build_delay(instruction)]
1002
+ elif isinstance(instruction.operation, Store):
1003
+ nodes = [
1004
+ ast.AssignmentStatement(
1005
+ self.build_expression(instruction.operation.lvalue),
1006
+ self.build_expression(instruction.operation.rvalue),
1007
+ )
1008
+ ]
1009
+ elif isinstance(instruction.operation, BreakLoopOp):
1010
+ nodes = [ast.BreakStatement()]
1011
+ elif isinstance(instruction.operation, ContinueLoopOp):
1012
+ nodes = [ast.ContinueStatement()]
1013
+ else:
1014
+ raise QASM3ExporterError(
1015
+ "non-unitary subroutine calls are not yet supported,"
1016
+ f" but received '{instruction.operation}'"
1017
+ )
1018
+
1019
+ statements.extend(nodes)
1020
+ return statements
1021
+
1022
+ def build_if_statement(self, instruction: CircuitInstruction) -> ast.BranchingStatement:
1023
+ """Build an :obj:`.IfElseOp` into a :obj:`.ast.BranchingStatement`."""
1024
+ condition = self.build_expression(_lift_condition(instruction.operation.condition))
1025
+
1026
+ true_circuit = instruction.operation.blocks[0]
1027
+ with self.new_scope(true_circuit, instruction.qubits, instruction.clbits):
1028
+ true_body = ast.ProgramBlock(self.build_current_scope())
1029
+ if len(instruction.operation.blocks) == 1:
1030
+ return ast.BranchingStatement(condition, true_body, None)
1031
+
1032
+ false_circuit = instruction.operation.blocks[1]
1033
+ with self.new_scope(false_circuit, instruction.qubits, instruction.clbits):
1034
+ false_body = ast.ProgramBlock(self.build_current_scope())
1035
+ return ast.BranchingStatement(condition, true_body, false_body)
1036
+
1037
+ def build_switch_statement(self, instruction: CircuitInstruction) -> Iterable[ast.Statement]:
1038
+ """Build a :obj:`.SwitchCaseOp` into a :class:`.ast.SwitchStatement`."""
1039
+ real_target = self.build_expression(expr.lift(instruction.operation.target))
1040
+ target = self.symbols.register_variable(
1041
+ "switch_dummy", None, allow_rename=True, force_global=True
1042
+ )
1043
+ self._global_classical_forward_declarations.append(
1044
+ ast.ClassicalDeclaration(ast.IntType(), target, None)
1045
+ )
1046
+
1047
+ if ExperimentalFeatures.SWITCH_CASE_V1 in self.experimental:
1048
+ # In this case, defaults can be folded in with other cases (useless as that is).
1049
+
1050
+ def case(values, case_block):
1051
+ values = [
1052
+ ast.DefaultCase() if v is CASE_DEFAULT else self.build_integer(v)
1053
+ for v in values
1054
+ ]
1055
+ with self.new_scope(case_block, instruction.qubits, instruction.clbits):
1056
+ case_body = ast.ProgramBlock(self.build_current_scope())
1057
+ return values, case_body
1058
+
1059
+ return [
1060
+ ast.AssignmentStatement(target, real_target),
1061
+ ast.SwitchStatementPreview(
1062
+ target,
1063
+ (
1064
+ case(values, block)
1065
+ for values, block in instruction.operation.cases_specifier()
1066
+ ),
1067
+ ),
1068
+ ]
1069
+
1070
+ # Handle the stabilized syntax.
1071
+ cases = []
1072
+ default = None
1073
+ for values, block in instruction.operation.cases_specifier():
1074
+ with self.new_scope(block, instruction.qubits, instruction.clbits):
1075
+ case_body = ast.ProgramBlock(self.build_current_scope())
1076
+ if CASE_DEFAULT in values:
1077
+ # Even if it's mixed in with other cases, we can skip them and only output the
1078
+ # `default` since that's valid and execution will be the same; the evaluation of
1079
+ # case labels can't have side effects.
1080
+ default = case_body
1081
+ continue
1082
+ cases.append(([self.build_integer(value) for value in values], case_body))
1083
+
1084
+ return [
1085
+ ast.AssignmentStatement(target, real_target),
1086
+ ast.SwitchStatement(target, cases, default=default),
1087
+ ]
1088
+
1089
+ def build_box(self, instruction: CircuitInstruction) -> ast.BoxStatement:
1090
+ """Build a :class:`.BoxOp` into a :class:`.ast.BoxStatement`."""
1091
+ duration = self.build_duration(instruction.operation.duration, instruction.operation.unit)
1092
+ body_circuit = instruction.operation.blocks[0]
1093
+ with self.new_scope(body_circuit, instruction.qubits, instruction.clbits):
1094
+ # TODO: handle no-op qubits (see https://github.com/openqasm/openqasm/issues/584).
1095
+ body = ast.ProgramBlock(self.build_current_scope())
1096
+ return ast.BoxStatement(body, duration)
1097
+
1098
+ def build_while_loop(self, instruction: CircuitInstruction) -> ast.WhileLoopStatement:
1099
+ """Build a :obj:`.WhileLoopOp` into a :obj:`.ast.WhileLoopStatement`."""
1100
+ condition = self.build_expression(_lift_condition(instruction.operation.condition))
1101
+ loop_circuit = instruction.operation.blocks[0]
1102
+ with self.new_scope(loop_circuit, instruction.qubits, instruction.clbits):
1103
+ loop_body = ast.ProgramBlock(self.build_current_scope())
1104
+ return ast.WhileLoopStatement(condition, loop_body)
1105
+
1106
+ def build_for_loop(self, instruction: CircuitInstruction) -> ast.ForLoopStatement:
1107
+ """Build a :obj:`.ForLoopOp` into a :obj:`.ast.ForLoopStatement`."""
1108
+ indexset, loop_parameter, loop_circuit = instruction.operation.params
1109
+ with self.new_scope(loop_circuit, instruction.qubits, instruction.clbits):
1110
+ name = "_" if loop_parameter is None else loop_parameter.name
1111
+ loop_parameter_ast = self.symbols.register_variable(
1112
+ name, loop_parameter, allow_rename=True
1113
+ )
1114
+ if isinstance(indexset, range):
1115
+ # OpenQASM 3 uses inclusive ranges on both ends, unlike Python.
1116
+ indexset_ast = ast.Range(
1117
+ start=self.build_integer(indexset.start),
1118
+ end=self.build_integer(indexset.stop - 1),
1119
+ step=self.build_integer(indexset.step) if indexset.step != 1 else None,
1120
+ )
1121
+ else:
1122
+ try:
1123
+ indexset_ast = ast.IndexSet([self.build_integer(value) for value in indexset])
1124
+ except QASM3ExporterError:
1125
+ raise QASM3ExporterError(
1126
+ "The values in OpenQASM 3 'for' loops must all be integers, but received"
1127
+ f" '{indexset}'."
1128
+ ) from None
1129
+ body_ast = ast.ProgramBlock(self.build_current_scope())
1130
+ return ast.ForLoopStatement(indexset_ast, loop_parameter_ast, body_ast)
1131
+
1132
+ def _lookup_variable_for_expression(self, var):
1133
+ if isinstance(var, Bit):
1134
+ return self._lookup_bit(var)
1135
+ return self.symbols.get_variable(var)
1136
+
1137
+ def build_expression(self, node: expr.Expr) -> ast.Expression:
1138
+ """Build an expression."""
1139
+ return node.accept(_ExprBuilder(self._lookup_variable_for_expression))
1140
+
1141
+ def build_delay(self, instruction: CircuitInstruction) -> ast.QuantumDelay:
1142
+ """Build a built-in delay statement."""
1143
+ if instruction.clbits:
1144
+ raise QASM3ExporterError(
1145
+ f"Found a delay instruction acting on classical bits: {instruction}"
1146
+ )
1147
+ duration = self.build_duration(instruction.operation.duration, instruction.operation.unit)
1148
+ return ast.QuantumDelay(duration, [self._lookup_bit(qubit) for qubit in instruction.qubits])
1149
+
1150
+ def build_duration(self, duration, unit) -> ast.Expression | None:
1151
+ """Build the expression of a given duration (if not ``None``)."""
1152
+ if duration is None:
1153
+ return None
1154
+ if unit == "expr":
1155
+ return self.build_expression(duration)
1156
+ if unit == "ps":
1157
+ return ast.DurationLiteral(1000 * duration, ast.DurationUnit.NANOSECOND)
1158
+ unit_map = {
1159
+ "ns": ast.DurationUnit.NANOSECOND,
1160
+ "us": ast.DurationUnit.MICROSECOND,
1161
+ "ms": ast.DurationUnit.MILLISECOND,
1162
+ "s": ast.DurationUnit.SECOND,
1163
+ "dt": ast.DurationUnit.SAMPLE,
1164
+ }
1165
+ return ast.DurationLiteral(duration, unit_map[unit])
1166
+
1167
+ def build_integer(self, value) -> ast.IntegerLiteral:
1168
+ """Build an integer literal, raising a :obj:`.QASM3ExporterError` if the input is not
1169
+ actually an
1170
+ integer."""
1171
+ if not isinstance(value, numbers.Integral):
1172
+ # This is meant to be purely defensive, in case a non-integer slips into the logic
1173
+ # somewhere, but no valid Terra object should trigger this.
1174
+ raise QASM3ExporterError(f"'{value}' is not an integer") # pragma: no cover
1175
+ return ast.IntegerLiteral(int(value))
1176
+
1177
+ def _rebind_scoped_parameters(self, expression):
1178
+ """If the input is a :class:`.ParameterExpression`, rebind any internal
1179
+ :class:`.Parameter`\\ s so that their names match their names in the scope. Other inputs
1180
+ are returned unchanged."""
1181
+ # This is a little hacky, but the entirety of the Expression handling is essentially
1182
+ # missing, pending a new system in Terra to replace it (2022-03-07).
1183
+ if not isinstance(expression, ParameterExpression):
1184
+ return expression
1185
+ if isinstance(expression, Parameter):
1186
+ return self.symbols.get_variable(expression).string
1187
+ return expression.subs(
1188
+ {
1189
+ param: Parameter(self.symbols.get_variable(param).string, uuid=param.uuid)
1190
+ for param in expression.parameters
1191
+ }
1192
+ )
1193
+
1194
+ def build_gate_call(self, instruction: CircuitInstruction):
1195
+ """Builds a gate-call AST node.
1196
+
1197
+ This will also push the gate into the symbol table (if required), including recursively
1198
+ defining the gate blocks."""
1199
+ operation = instruction.operation
1200
+ if hasattr(operation, "_qasm_decomposition"):
1201
+ operation = operation._qasm_decomposition()
1202
+ ident = self.symbols.get_gate(operation)
1203
+ if ident is None:
1204
+ ident = self.define_gate(operation)
1205
+ qubits = [self._lookup_bit(qubit) for qubit in instruction.qubits]
1206
+ parameters = [
1207
+ ast.StringifyAndPray(self._rebind_scoped_parameters(param))
1208
+ for param in operation.params
1209
+ ]
1210
+ if not self.disable_constants:
1211
+ for parameter in parameters:
1212
+ parameter.obj = pi_check(parameter.obj, output="qasm")
1213
+ return ast.QuantumGateCall(ident, qubits, parameters=parameters)
1214
+
1215
+
1216
+ def _infer_variable_declaration(
1217
+ circuit: QuantumCircuit, parameter: Parameter, parameter_name: ast.Identifier
1218
+ ) -> Union[ast.ClassicalDeclaration, None]:
1219
+ """Attempt to infer what type a parameter should be declared as to work with a circuit.
1220
+
1221
+ This is very simplistic; it assumes all parameters are real numbers that need to be input to the
1222
+ program, unless one is used as a loop variable, in which case it shouldn't be declared at all,
1223
+ because the ``for`` loop declares it implicitly (per the Qiskit/qe-compiler reading of the
1224
+ OpenQASM spec at openqasm/openqasm@8ee55ec).
1225
+
1226
+ .. note::
1227
+
1228
+ This is a hack around not having a proper type system implemented in Terra, and really this
1229
+ whole function should be removed in favour of proper symbol-table building and lookups.
1230
+ This function is purely to try and hack the parameters for ``for`` loops into the exporter
1231
+ for now.
1232
+
1233
+ Args:
1234
+ circuit: The global-scope circuit, which is the base of the exported program.
1235
+ parameter: The parameter to infer the type of.
1236
+ parameter_name: The name of the parameter to use in the declaration.
1237
+
1238
+ Returns:
1239
+ A suitable :obj:`.ast.ClassicalDeclaration` node, or, if the parameter should *not* be
1240
+ declared, then ``None``.
1241
+ """
1242
+
1243
+ def is_loop_variable(circuit, parameter):
1244
+ """Recurse into the instructions a parameter is used in, checking at every level if it is
1245
+ used as the loop variable of a ``for`` loop."""
1246
+ # This private access is hacky, and shouldn't need to happen; the type of a parameter
1247
+ # _should_ be an intrinsic part of the parameter, or somewhere publicly accessible, but
1248
+ # Terra doesn't have those concepts yet. We can only try and guess at the type by looking
1249
+ # at all the places it's used in the circuit.
1250
+ for instr_index, index in circuit._data._raw_parameter_table_entry(parameter):
1251
+ if instr_index is None:
1252
+ continue
1253
+ instruction = circuit.data[instr_index].operation
1254
+ if isinstance(instruction, ForLoopOp):
1255
+ # The parameters of ForLoopOp are (indexset, loop_parameter, body).
1256
+ if index == 1:
1257
+ return True
1258
+ if isinstance(instruction, ControlFlowOp):
1259
+ if is_loop_variable(instruction.params[index], parameter):
1260
+ return True
1261
+ return False
1262
+
1263
+ if is_loop_variable(circuit, parameter):
1264
+ return None
1265
+ # Arbitrary choice of double-precision float for all other parameters, but it's what we actually
1266
+ # expect people to be binding to their Parameters right now.
1267
+ return ast.IODeclaration(ast.IOModifier.INPUT, ast.FloatType.DOUBLE, parameter_name)
1268
+
1269
+
1270
+ def _lift_condition(condition):
1271
+ if isinstance(condition, expr.Expr):
1272
+ return condition
1273
+ return expr.lift_legacy_condition(condition)
1274
+
1275
+
1276
+ def _build_ast_type(type_: types.Type) -> ast.ClassicalType:
1277
+ if type_.kind is types.Bool:
1278
+ return ast.BoolType()
1279
+ if type_.kind is types.Uint:
1280
+ return ast.UintType(type_.width)
1281
+ if type_.kind is types.Float:
1282
+ return ast.FloatType.DOUBLE
1283
+ if type_.kind is types.Duration:
1284
+ return ast.DurationType()
1285
+ raise RuntimeError(f"unhandled expr type '{type_}'")
1286
+
1287
+
1288
+ class _ExprBuilder(expr.ExprVisitor[ast.Expression]):
1289
+ __slots__ = ("lookup",)
1290
+
1291
+ # This is a very simple, non-contextual converter. As the type system expands, we may well end
1292
+ # up with some places where Qiskit's abstract type system needs to be lowered to OQ3 rather than
1293
+ # mapping 100% directly, which might need a more contextual visitor.
1294
+
1295
+ def __init__(self, lookup):
1296
+ self.lookup = lookup
1297
+
1298
+ def visit_var(self, node, /):
1299
+ return self.lookup(node) if node.standalone else self.lookup(node.var)
1300
+
1301
+ def visit_stretch(self, node, /):
1302
+ return self.lookup(node)
1303
+
1304
+ # pylint: disable=too-many-return-statements
1305
+ def visit_value(self, node, /):
1306
+ if node.type.kind is types.Bool:
1307
+ return ast.BooleanLiteral(node.value)
1308
+ if node.type.kind is types.Uint:
1309
+ return ast.IntegerLiteral(node.value)
1310
+ if node.type.kind is types.Float:
1311
+ return ast.FloatLiteral(node.value)
1312
+ if node.type.kind is types.Duration:
1313
+ unit = node.value.unit()
1314
+ if unit == "dt":
1315
+ return ast.DurationLiteral(node.value.value(), ast.DurationUnit.SAMPLE)
1316
+ if unit == "ns":
1317
+ return ast.DurationLiteral(node.value.value(), ast.DurationUnit.NANOSECOND)
1318
+ if unit == "us":
1319
+ return ast.DurationLiteral(node.value.value(), ast.DurationUnit.MICROSECOND)
1320
+ if unit == "ms":
1321
+ return ast.DurationLiteral(node.value.value(), ast.DurationUnit.MILLISECOND)
1322
+ if unit == "s":
1323
+ return ast.DurationLiteral(node.value.value(), ast.DurationUnit.SECOND)
1324
+ raise RuntimeError(f"unhandled Value type '{node}'")
1325
+
1326
+ def visit_cast(self, node, /):
1327
+ if node.implicit:
1328
+ return node.operand.accept(self)
1329
+ return ast.Cast(_build_ast_type(node.type), node.operand.accept(self))
1330
+
1331
+ def visit_unary(self, node, /):
1332
+ return ast.Unary(ast.Unary.Op[node.op.name], node.operand.accept(self))
1333
+
1334
+ def visit_binary(self, node, /):
1335
+ return ast.Binary(
1336
+ ast.Binary.Op[node.op.name], node.left.accept(self), node.right.accept(self)
1337
+ )
1338
+
1339
+ def visit_index(self, node, /):
1340
+ return ast.Index(node.target.accept(self), node.index.accept(self))