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