qiskit 1.3.0__cp39-abi3-win32.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 (836) hide show
  1. qiskit/VERSION.txt +1 -0
  2. qiskit/__init__.py +146 -0
  3. qiskit/_accelerate.pyd +0 -0
  4. qiskit/_numpy_compat.py +73 -0
  5. qiskit/assembler/__init__.py +42 -0
  6. qiskit/assembler/assemble_circuits.py +451 -0
  7. qiskit/assembler/assemble_schedules.py +367 -0
  8. qiskit/assembler/disassemble.py +310 -0
  9. qiskit/assembler/run_config.py +77 -0
  10. qiskit/circuit/__init__.py +1313 -0
  11. qiskit/circuit/_classical_resource_map.py +148 -0
  12. qiskit/circuit/_standard_gates_commutations.py +3849 -0
  13. qiskit/circuit/_utils.py +167 -0
  14. qiskit/circuit/add_control.py +274 -0
  15. qiskit/circuit/annotated_operation.py +279 -0
  16. qiskit/circuit/barrier.py +50 -0
  17. qiskit/circuit/bit.py +94 -0
  18. qiskit/circuit/classical/__init__.py +41 -0
  19. qiskit/circuit/classical/expr/__init__.py +238 -0
  20. qiskit/circuit/classical/expr/constructors.py +556 -0
  21. qiskit/circuit/classical/expr/expr.py +397 -0
  22. qiskit/circuit/classical/expr/visitors.py +300 -0
  23. qiskit/circuit/classical/types/__init__.py +109 -0
  24. qiskit/circuit/classical/types/ordering.py +222 -0
  25. qiskit/circuit/classical/types/types.py +117 -0
  26. qiskit/circuit/classicalfunction/__init__.py +140 -0
  27. qiskit/circuit/classicalfunction/boolean_expression.py +129 -0
  28. qiskit/circuit/classicalfunction/classical_element.py +54 -0
  29. qiskit/circuit/classicalfunction/classical_function_visitor.py +155 -0
  30. qiskit/circuit/classicalfunction/classicalfunction.py +173 -0
  31. qiskit/circuit/classicalfunction/exceptions.py +35 -0
  32. qiskit/circuit/classicalfunction/types.py +18 -0
  33. qiskit/circuit/classicalfunction/utils.py +91 -0
  34. qiskit/circuit/classicalregister.py +57 -0
  35. qiskit/circuit/commutation_checker.py +106 -0
  36. qiskit/circuit/commutation_library.py +20 -0
  37. qiskit/circuit/controlflow/__init__.py +28 -0
  38. qiskit/circuit/controlflow/_builder_utils.py +207 -0
  39. qiskit/circuit/controlflow/break_loop.py +56 -0
  40. qiskit/circuit/controlflow/builder.py +691 -0
  41. qiskit/circuit/controlflow/continue_loop.py +58 -0
  42. qiskit/circuit/controlflow/control_flow.py +84 -0
  43. qiskit/circuit/controlflow/for_loop.py +217 -0
  44. qiskit/circuit/controlflow/if_else.py +511 -0
  45. qiskit/circuit/controlflow/switch_case.py +417 -0
  46. qiskit/circuit/controlflow/while_loop.py +171 -0
  47. qiskit/circuit/controlledgate.py +274 -0
  48. qiskit/circuit/delay.py +123 -0
  49. qiskit/circuit/duration.py +95 -0
  50. qiskit/circuit/equivalence.py +94 -0
  51. qiskit/circuit/equivalence_library.py +18 -0
  52. qiskit/circuit/exceptions.py +19 -0
  53. qiskit/circuit/gate.py +263 -0
  54. qiskit/circuit/instruction.py +697 -0
  55. qiskit/circuit/instructionset.py +179 -0
  56. qiskit/circuit/library/__init__.py +668 -0
  57. qiskit/circuit/library/arithmetic/__init__.py +34 -0
  58. qiskit/circuit/library/arithmetic/adders/__init__.py +18 -0
  59. qiskit/circuit/library/arithmetic/adders/adder.py +210 -0
  60. qiskit/circuit/library/arithmetic/adders/cdkm_ripple_carry_adder.py +123 -0
  61. qiskit/circuit/library/arithmetic/adders/draper_qft_adder.py +129 -0
  62. qiskit/circuit/library/arithmetic/adders/vbe_ripple_carry_adder.py +95 -0
  63. qiskit/circuit/library/arithmetic/exact_reciprocal.py +88 -0
  64. qiskit/circuit/library/arithmetic/functional_pauli_rotations.py +114 -0
  65. qiskit/circuit/library/arithmetic/integer_comparator.py +243 -0
  66. qiskit/circuit/library/arithmetic/linear_amplitude_function.py +196 -0
  67. qiskit/circuit/library/arithmetic/linear_pauli_rotations.py +189 -0
  68. qiskit/circuit/library/arithmetic/multipliers/__init__.py +17 -0
  69. qiskit/circuit/library/arithmetic/multipliers/hrs_cumulative_multiplier.py +145 -0
  70. qiskit/circuit/library/arithmetic/multipliers/multiplier.py +192 -0
  71. qiskit/circuit/library/arithmetic/multipliers/rg_qft_multiplier.py +108 -0
  72. qiskit/circuit/library/arithmetic/piecewise_chebyshev.py +353 -0
  73. qiskit/circuit/library/arithmetic/piecewise_linear_pauli_rotations.py +277 -0
  74. qiskit/circuit/library/arithmetic/piecewise_polynomial_pauli_rotations.py +317 -0
  75. qiskit/circuit/library/arithmetic/polynomial_pauli_rotations.py +335 -0
  76. qiskit/circuit/library/arithmetic/quadratic_form.py +198 -0
  77. qiskit/circuit/library/arithmetic/weighted_adder.py +337 -0
  78. qiskit/circuit/library/basis_change/__init__.py +15 -0
  79. qiskit/circuit/library/basis_change/qft.py +313 -0
  80. qiskit/circuit/library/blueprintcircuit.py +280 -0
  81. qiskit/circuit/library/boolean_logic/__init__.py +18 -0
  82. qiskit/circuit/library/boolean_logic/inner_product.py +155 -0
  83. qiskit/circuit/library/boolean_logic/quantum_and.py +200 -0
  84. qiskit/circuit/library/boolean_logic/quantum_or.py +202 -0
  85. qiskit/circuit/library/boolean_logic/quantum_xor.py +165 -0
  86. qiskit/circuit/library/data_preparation/__init__.py +57 -0
  87. qiskit/circuit/library/data_preparation/_z_feature_map.py +115 -0
  88. qiskit/circuit/library/data_preparation/_zz_feature_map.py +150 -0
  89. qiskit/circuit/library/data_preparation/initializer.py +107 -0
  90. qiskit/circuit/library/data_preparation/pauli_feature_map.py +656 -0
  91. qiskit/circuit/library/data_preparation/state_preparation.py +336 -0
  92. qiskit/circuit/library/fourier_checking.py +158 -0
  93. qiskit/circuit/library/generalized_gates/__init__.py +30 -0
  94. qiskit/circuit/library/generalized_gates/diagonal.py +159 -0
  95. qiskit/circuit/library/generalized_gates/gms.py +174 -0
  96. qiskit/circuit/library/generalized_gates/gr.py +215 -0
  97. qiskit/circuit/library/generalized_gates/isometry.py +370 -0
  98. qiskit/circuit/library/generalized_gates/linear_function.py +318 -0
  99. qiskit/circuit/library/generalized_gates/mcg_up_to_diagonal.py +143 -0
  100. qiskit/circuit/library/generalized_gates/mcmt.py +316 -0
  101. qiskit/circuit/library/generalized_gates/pauli.py +85 -0
  102. qiskit/circuit/library/generalized_gates/permutation.py +194 -0
  103. qiskit/circuit/library/generalized_gates/rv.py +96 -0
  104. qiskit/circuit/library/generalized_gates/uc.py +213 -0
  105. qiskit/circuit/library/generalized_gates/uc_pauli_rot.py +164 -0
  106. qiskit/circuit/library/generalized_gates/ucrx.py +32 -0
  107. qiskit/circuit/library/generalized_gates/ucry.py +32 -0
  108. qiskit/circuit/library/generalized_gates/ucrz.py +32 -0
  109. qiskit/circuit/library/generalized_gates/unitary.py +215 -0
  110. qiskit/circuit/library/graph_state.py +169 -0
  111. qiskit/circuit/library/grover_operator.py +579 -0
  112. qiskit/circuit/library/hamiltonian_gate.py +142 -0
  113. qiskit/circuit/library/hidden_linear_function.py +161 -0
  114. qiskit/circuit/library/iqp.py +175 -0
  115. qiskit/circuit/library/n_local/__init__.py +45 -0
  116. qiskit/circuit/library/n_local/efficient_su2.py +277 -0
  117. qiskit/circuit/library/n_local/evolved_operator_ansatz.py +515 -0
  118. qiskit/circuit/library/n_local/excitation_preserving.py +297 -0
  119. qiskit/circuit/library/n_local/n_local.py +1472 -0
  120. qiskit/circuit/library/n_local/pauli_two_design.py +243 -0
  121. qiskit/circuit/library/n_local/qaoa_ansatz.py +366 -0
  122. qiskit/circuit/library/n_local/real_amplitudes.py +306 -0
  123. qiskit/circuit/library/n_local/two_local.py +289 -0
  124. qiskit/circuit/library/overlap.py +182 -0
  125. qiskit/circuit/library/pauli_evolution.py +186 -0
  126. qiskit/circuit/library/phase_estimation.py +175 -0
  127. qiskit/circuit/library/phase_oracle.py +153 -0
  128. qiskit/circuit/library/quantum_volume.py +167 -0
  129. qiskit/circuit/library/standard_gates/__init__.py +142 -0
  130. qiskit/circuit/library/standard_gates/dcx.py +78 -0
  131. qiskit/circuit/library/standard_gates/ecr.py +130 -0
  132. qiskit/circuit/library/standard_gates/equivalence_library.py +1800 -0
  133. qiskit/circuit/library/standard_gates/global_phase.py +85 -0
  134. qiskit/circuit/library/standard_gates/h.py +258 -0
  135. qiskit/circuit/library/standard_gates/i.py +76 -0
  136. qiskit/circuit/library/standard_gates/iswap.py +134 -0
  137. qiskit/circuit/library/standard_gates/multi_control_rotation_gates.py +405 -0
  138. qiskit/circuit/library/standard_gates/p.py +441 -0
  139. qiskit/circuit/library/standard_gates/r.py +117 -0
  140. qiskit/circuit/library/standard_gates/rx.py +303 -0
  141. qiskit/circuit/library/standard_gates/rxx.py +183 -0
  142. qiskit/circuit/library/standard_gates/ry.py +298 -0
  143. qiskit/circuit/library/standard_gates/ryy.py +183 -0
  144. qiskit/circuit/library/standard_gates/rz.py +319 -0
  145. qiskit/circuit/library/standard_gates/rzx.py +229 -0
  146. qiskit/circuit/library/standard_gates/rzz.py +196 -0
  147. qiskit/circuit/library/standard_gates/s.py +428 -0
  148. qiskit/circuit/library/standard_gates/swap.py +288 -0
  149. qiskit/circuit/library/standard_gates/sx.py +315 -0
  150. qiskit/circuit/library/standard_gates/t.py +179 -0
  151. qiskit/circuit/library/standard_gates/u.py +403 -0
  152. qiskit/circuit/library/standard_gates/u1.py +501 -0
  153. qiskit/circuit/library/standard_gates/u2.py +149 -0
  154. qiskit/circuit/library/standard_gates/u3.py +436 -0
  155. qiskit/circuit/library/standard_gates/x.py +1529 -0
  156. qiskit/circuit/library/standard_gates/xx_minus_yy.py +235 -0
  157. qiskit/circuit/library/standard_gates/xx_plus_yy.py +239 -0
  158. qiskit/circuit/library/standard_gates/y.py +262 -0
  159. qiskit/circuit/library/standard_gates/z.py +348 -0
  160. qiskit/circuit/library/templates/__init__.py +92 -0
  161. qiskit/circuit/library/templates/clifford/__init__.py +33 -0
  162. qiskit/circuit/library/templates/clifford/clifford_2_1.py +34 -0
  163. qiskit/circuit/library/templates/clifford/clifford_2_2.py +35 -0
  164. qiskit/circuit/library/templates/clifford/clifford_2_3.py +34 -0
  165. qiskit/circuit/library/templates/clifford/clifford_2_4.py +34 -0
  166. qiskit/circuit/library/templates/clifford/clifford_3_1.py +35 -0
  167. qiskit/circuit/library/templates/clifford/clifford_4_1.py +38 -0
  168. qiskit/circuit/library/templates/clifford/clifford_4_2.py +37 -0
  169. qiskit/circuit/library/templates/clifford/clifford_4_3.py +38 -0
  170. qiskit/circuit/library/templates/clifford/clifford_4_4.py +37 -0
  171. qiskit/circuit/library/templates/clifford/clifford_5_1.py +40 -0
  172. qiskit/circuit/library/templates/clifford/clifford_6_1.py +40 -0
  173. qiskit/circuit/library/templates/clifford/clifford_6_2.py +40 -0
  174. qiskit/circuit/library/templates/clifford/clifford_6_3.py +40 -0
  175. qiskit/circuit/library/templates/clifford/clifford_6_4.py +38 -0
  176. qiskit/circuit/library/templates/clifford/clifford_6_5.py +40 -0
  177. qiskit/circuit/library/templates/clifford/clifford_8_1.py +42 -0
  178. qiskit/circuit/library/templates/clifford/clifford_8_2.py +42 -0
  179. qiskit/circuit/library/templates/clifford/clifford_8_3.py +41 -0
  180. qiskit/circuit/library/templates/nct/__init__.py +67 -0
  181. qiskit/circuit/library/templates/nct/template_nct_2a_1.py +34 -0
  182. qiskit/circuit/library/templates/nct/template_nct_2a_2.py +35 -0
  183. qiskit/circuit/library/templates/nct/template_nct_2a_3.py +37 -0
  184. qiskit/circuit/library/templates/nct/template_nct_4a_1.py +43 -0
  185. qiskit/circuit/library/templates/nct/template_nct_4a_2.py +41 -0
  186. qiskit/circuit/library/templates/nct/template_nct_4a_3.py +39 -0
  187. qiskit/circuit/library/templates/nct/template_nct_4b_1.py +41 -0
  188. qiskit/circuit/library/templates/nct/template_nct_4b_2.py +39 -0
  189. qiskit/circuit/library/templates/nct/template_nct_5a_1.py +40 -0
  190. qiskit/circuit/library/templates/nct/template_nct_5a_2.py +40 -0
  191. qiskit/circuit/library/templates/nct/template_nct_5a_3.py +40 -0
  192. qiskit/circuit/library/templates/nct/template_nct_5a_4.py +39 -0
  193. qiskit/circuit/library/templates/nct/template_nct_6a_1.py +40 -0
  194. qiskit/circuit/library/templates/nct/template_nct_6a_2.py +41 -0
  195. qiskit/circuit/library/templates/nct/template_nct_6a_3.py +41 -0
  196. qiskit/circuit/library/templates/nct/template_nct_6a_4.py +41 -0
  197. qiskit/circuit/library/templates/nct/template_nct_6b_1.py +41 -0
  198. qiskit/circuit/library/templates/nct/template_nct_6b_2.py +41 -0
  199. qiskit/circuit/library/templates/nct/template_nct_6c_1.py +41 -0
  200. qiskit/circuit/library/templates/nct/template_nct_7a_1.py +43 -0
  201. qiskit/circuit/library/templates/nct/template_nct_7b_1.py +43 -0
  202. qiskit/circuit/library/templates/nct/template_nct_7c_1.py +43 -0
  203. qiskit/circuit/library/templates/nct/template_nct_7d_1.py +43 -0
  204. qiskit/circuit/library/templates/nct/template_nct_7e_1.py +43 -0
  205. qiskit/circuit/library/templates/nct/template_nct_9a_1.py +45 -0
  206. qiskit/circuit/library/templates/nct/template_nct_9c_1.py +43 -0
  207. qiskit/circuit/library/templates/nct/template_nct_9c_10.py +44 -0
  208. qiskit/circuit/library/templates/nct/template_nct_9c_11.py +44 -0
  209. qiskit/circuit/library/templates/nct/template_nct_9c_12.py +44 -0
  210. qiskit/circuit/library/templates/nct/template_nct_9c_2.py +44 -0
  211. qiskit/circuit/library/templates/nct/template_nct_9c_3.py +44 -0
  212. qiskit/circuit/library/templates/nct/template_nct_9c_4.py +44 -0
  213. qiskit/circuit/library/templates/nct/template_nct_9c_5.py +44 -0
  214. qiskit/circuit/library/templates/nct/template_nct_9c_6.py +44 -0
  215. qiskit/circuit/library/templates/nct/template_nct_9c_7.py +44 -0
  216. qiskit/circuit/library/templates/nct/template_nct_9c_8.py +44 -0
  217. qiskit/circuit/library/templates/nct/template_nct_9c_9.py +44 -0
  218. qiskit/circuit/library/templates/nct/template_nct_9d_1.py +43 -0
  219. qiskit/circuit/library/templates/nct/template_nct_9d_10.py +44 -0
  220. qiskit/circuit/library/templates/nct/template_nct_9d_2.py +44 -0
  221. qiskit/circuit/library/templates/nct/template_nct_9d_3.py +44 -0
  222. qiskit/circuit/library/templates/nct/template_nct_9d_4.py +44 -0
  223. qiskit/circuit/library/templates/nct/template_nct_9d_5.py +44 -0
  224. qiskit/circuit/library/templates/nct/template_nct_9d_6.py +44 -0
  225. qiskit/circuit/library/templates/nct/template_nct_9d_7.py +44 -0
  226. qiskit/circuit/library/templates/nct/template_nct_9d_8.py +44 -0
  227. qiskit/circuit/library/templates/nct/template_nct_9d_9.py +44 -0
  228. qiskit/circuit/library/templates/rzx/__init__.py +25 -0
  229. qiskit/circuit/library/templates/rzx/rzx_cy.py +47 -0
  230. qiskit/circuit/library/templates/rzx/rzx_xz.py +54 -0
  231. qiskit/circuit/library/templates/rzx/rzx_yz.py +45 -0
  232. qiskit/circuit/library/templates/rzx/rzx_zz1.py +69 -0
  233. qiskit/circuit/library/templates/rzx/rzx_zz2.py +59 -0
  234. qiskit/circuit/library/templates/rzx/rzx_zz3.py +59 -0
  235. qiskit/circuit/measure.py +44 -0
  236. qiskit/circuit/operation.py +67 -0
  237. qiskit/circuit/parameter.py +178 -0
  238. qiskit/circuit/parameterexpression.py +692 -0
  239. qiskit/circuit/parametertable.py +119 -0
  240. qiskit/circuit/parametervector.py +120 -0
  241. qiskit/circuit/quantumcircuit.py +6829 -0
  242. qiskit/circuit/quantumcircuitdata.py +136 -0
  243. qiskit/circuit/quantumregister.py +75 -0
  244. qiskit/circuit/random/__init__.py +15 -0
  245. qiskit/circuit/random/utils.py +358 -0
  246. qiskit/circuit/register.py +233 -0
  247. qiskit/circuit/reset.py +34 -0
  248. qiskit/circuit/singleton.py +606 -0
  249. qiskit/circuit/store.py +97 -0
  250. qiskit/circuit/tools/__init__.py +16 -0
  251. qiskit/circuit/tools/pi_check.py +190 -0
  252. qiskit/circuit/twirling.py +145 -0
  253. qiskit/compiler/__init__.py +33 -0
  254. qiskit/compiler/assembler.py +681 -0
  255. qiskit/compiler/scheduler.py +109 -0
  256. qiskit/compiler/sequencer.py +71 -0
  257. qiskit/compiler/transpiler.py +533 -0
  258. qiskit/converters/__init__.py +74 -0
  259. qiskit/converters/circuit_to_dag.py +78 -0
  260. qiskit/converters/circuit_to_dagdependency.py +51 -0
  261. qiskit/converters/circuit_to_dagdependency_v2.py +47 -0
  262. qiskit/converters/circuit_to_gate.py +107 -0
  263. qiskit/converters/circuit_to_instruction.py +155 -0
  264. qiskit/converters/dag_to_circuit.py +79 -0
  265. qiskit/converters/dag_to_dagdependency.py +55 -0
  266. qiskit/converters/dag_to_dagdependency_v2.py +44 -0
  267. qiskit/converters/dagdependency_to_circuit.py +46 -0
  268. qiskit/converters/dagdependency_to_dag.py +54 -0
  269. qiskit/dagcircuit/__init__.py +44 -0
  270. qiskit/dagcircuit/collect_blocks.py +391 -0
  271. qiskit/dagcircuit/dagcircuit.py +24 -0
  272. qiskit/dagcircuit/dagdependency.py +646 -0
  273. qiskit/dagcircuit/dagdependency_v2.py +641 -0
  274. qiskit/dagcircuit/dagdepnode.py +160 -0
  275. qiskit/dagcircuit/dagnode.py +176 -0
  276. qiskit/dagcircuit/exceptions.py +42 -0
  277. qiskit/exceptions.py +153 -0
  278. qiskit/passmanager/__init__.py +240 -0
  279. qiskit/passmanager/base_tasks.py +230 -0
  280. qiskit/passmanager/compilation_status.py +74 -0
  281. qiskit/passmanager/exceptions.py +19 -0
  282. qiskit/passmanager/flow_controllers.py +116 -0
  283. qiskit/passmanager/passmanager.py +333 -0
  284. qiskit/primitives/__init__.py +481 -0
  285. qiskit/primitives/backend_estimator.py +486 -0
  286. qiskit/primitives/backend_estimator_v2.py +434 -0
  287. qiskit/primitives/backend_sampler.py +222 -0
  288. qiskit/primitives/backend_sampler_v2.py +339 -0
  289. qiskit/primitives/base/__init__.py +20 -0
  290. qiskit/primitives/base/base_estimator.py +252 -0
  291. qiskit/primitives/base/base_primitive.py +45 -0
  292. qiskit/primitives/base/base_primitive_job.py +78 -0
  293. qiskit/primitives/base/base_result.py +65 -0
  294. qiskit/primitives/base/base_sampler.py +204 -0
  295. qiskit/primitives/base/estimator_result.py +46 -0
  296. qiskit/primitives/base/sampler_result.py +45 -0
  297. qiskit/primitives/base/validation.py +231 -0
  298. qiskit/primitives/containers/__init__.py +26 -0
  299. qiskit/primitives/containers/bindings_array.py +389 -0
  300. qiskit/primitives/containers/bit_array.py +741 -0
  301. qiskit/primitives/containers/data_bin.py +173 -0
  302. qiskit/primitives/containers/estimator_pub.py +222 -0
  303. qiskit/primitives/containers/object_array.py +94 -0
  304. qiskit/primitives/containers/observables_array.py +279 -0
  305. qiskit/primitives/containers/primitive_result.py +53 -0
  306. qiskit/primitives/containers/pub_result.py +51 -0
  307. qiskit/primitives/containers/sampler_pub.py +193 -0
  308. qiskit/primitives/containers/sampler_pub_result.py +74 -0
  309. qiskit/primitives/containers/shape.py +129 -0
  310. qiskit/primitives/estimator.py +172 -0
  311. qiskit/primitives/primitive_job.py +81 -0
  312. qiskit/primitives/sampler.py +162 -0
  313. qiskit/primitives/statevector_estimator.py +174 -0
  314. qiskit/primitives/statevector_sampler.py +292 -0
  315. qiskit/primitives/utils.py +247 -0
  316. qiskit/providers/__init__.py +803 -0
  317. qiskit/providers/backend.py +667 -0
  318. qiskit/providers/backend_compat.py +472 -0
  319. qiskit/providers/basic_provider/__init__.py +45 -0
  320. qiskit/providers/basic_provider/basic_provider.py +101 -0
  321. qiskit/providers/basic_provider/basic_provider_job.py +65 -0
  322. qiskit/providers/basic_provider/basic_provider_tools.py +218 -0
  323. qiskit/providers/basic_provider/basic_simulator.py +821 -0
  324. qiskit/providers/basic_provider/exceptions.py +30 -0
  325. qiskit/providers/exceptions.py +45 -0
  326. qiskit/providers/fake_provider/__init__.py +105 -0
  327. qiskit/providers/fake_provider/backends_v1/__init__.py +22 -0
  328. qiskit/providers/fake_provider/backends_v1/fake_127q_pulse/__init__.py +18 -0
  329. qiskit/providers/fake_provider/backends_v1/fake_127q_pulse/conf_washington.json +1 -0
  330. qiskit/providers/fake_provider/backends_v1/fake_127q_pulse/defs_washington.json +1 -0
  331. qiskit/providers/fake_provider/backends_v1/fake_127q_pulse/fake_127q_pulse_v1.py +37 -0
  332. qiskit/providers/fake_provider/backends_v1/fake_127q_pulse/props_washington.json +1 -0
  333. qiskit/providers/fake_provider/backends_v1/fake_20q/__init__.py +18 -0
  334. qiskit/providers/fake_provider/backends_v1/fake_20q/conf_singapore.json +1 -0
  335. qiskit/providers/fake_provider/backends_v1/fake_20q/fake_20q.py +43 -0
  336. qiskit/providers/fake_provider/backends_v1/fake_20q/props_singapore.json +1 -0
  337. qiskit/providers/fake_provider/backends_v1/fake_27q_pulse/__init__.py +18 -0
  338. qiskit/providers/fake_provider/backends_v1/fake_27q_pulse/conf_hanoi.json +1 -0
  339. qiskit/providers/fake_provider/backends_v1/fake_27q_pulse/defs_hanoi.json +1 -0
  340. qiskit/providers/fake_provider/backends_v1/fake_27q_pulse/fake_27q_pulse_v1.py +50 -0
  341. qiskit/providers/fake_provider/backends_v1/fake_27q_pulse/props_hanoi.json +1 -0
  342. qiskit/providers/fake_provider/backends_v1/fake_5q/__init__.py +18 -0
  343. qiskit/providers/fake_provider/backends_v1/fake_5q/conf_yorktown.json +1 -0
  344. qiskit/providers/fake_provider/backends_v1/fake_5q/fake_5q_v1.py +41 -0
  345. qiskit/providers/fake_provider/backends_v1/fake_5q/props_yorktown.json +1 -0
  346. qiskit/providers/fake_provider/backends_v1/fake_7q_pulse/__init__.py +18 -0
  347. qiskit/providers/fake_provider/backends_v1/fake_7q_pulse/conf_nairobi.json +1 -0
  348. qiskit/providers/fake_provider/backends_v1/fake_7q_pulse/defs_nairobi.json +1 -0
  349. qiskit/providers/fake_provider/backends_v1/fake_7q_pulse/fake_7q_pulse_v1.py +44 -0
  350. qiskit/providers/fake_provider/backends_v1/fake_7q_pulse/props_nairobi.json +1 -0
  351. qiskit/providers/fake_provider/fake_1q.py +91 -0
  352. qiskit/providers/fake_provider/fake_backend.py +165 -0
  353. qiskit/providers/fake_provider/fake_openpulse_2q.py +391 -0
  354. qiskit/providers/fake_provider/fake_openpulse_3q.py +340 -0
  355. qiskit/providers/fake_provider/fake_pulse_backend.py +49 -0
  356. qiskit/providers/fake_provider/fake_qasm_backend.py +77 -0
  357. qiskit/providers/fake_provider/generic_backend_v2.py +1035 -0
  358. qiskit/providers/fake_provider/utils/__init__.py +15 -0
  359. qiskit/providers/fake_provider/utils/backend_converter.py +150 -0
  360. qiskit/providers/fake_provider/utils/json_decoder.py +109 -0
  361. qiskit/providers/job.py +147 -0
  362. qiskit/providers/jobstatus.py +30 -0
  363. qiskit/providers/models/__init__.py +89 -0
  364. qiskit/providers/models/backendconfiguration.py +1040 -0
  365. qiskit/providers/models/backendproperties.py +517 -0
  366. qiskit/providers/models/backendstatus.py +94 -0
  367. qiskit/providers/models/jobstatus.py +66 -0
  368. qiskit/providers/models/pulsedefaults.py +305 -0
  369. qiskit/providers/options.py +273 -0
  370. qiskit/providers/provider.py +95 -0
  371. qiskit/providers/providerutils.py +110 -0
  372. qiskit/pulse/__init__.py +158 -0
  373. qiskit/pulse/builder.py +2254 -0
  374. qiskit/pulse/calibration_entries.py +381 -0
  375. qiskit/pulse/channels.py +227 -0
  376. qiskit/pulse/configuration.py +245 -0
  377. qiskit/pulse/exceptions.py +45 -0
  378. qiskit/pulse/filters.py +309 -0
  379. qiskit/pulse/instruction_schedule_map.py +424 -0
  380. qiskit/pulse/instructions/__init__.py +67 -0
  381. qiskit/pulse/instructions/acquire.py +150 -0
  382. qiskit/pulse/instructions/delay.py +71 -0
  383. qiskit/pulse/instructions/directives.py +154 -0
  384. qiskit/pulse/instructions/frequency.py +135 -0
  385. qiskit/pulse/instructions/instruction.py +270 -0
  386. qiskit/pulse/instructions/phase.py +152 -0
  387. qiskit/pulse/instructions/play.py +99 -0
  388. qiskit/pulse/instructions/reference.py +100 -0
  389. qiskit/pulse/instructions/snapshot.py +82 -0
  390. qiskit/pulse/library/__init__.py +97 -0
  391. qiskit/pulse/library/continuous.py +430 -0
  392. qiskit/pulse/library/pulse.py +148 -0
  393. qiskit/pulse/library/samplers/__init__.py +15 -0
  394. qiskit/pulse/library/samplers/decorators.py +295 -0
  395. qiskit/pulse/library/samplers/strategies.py +71 -0
  396. qiskit/pulse/library/symbolic_pulses.py +1988 -0
  397. qiskit/pulse/library/waveform.py +136 -0
  398. qiskit/pulse/macros.py +262 -0
  399. qiskit/pulse/parameter_manager.py +445 -0
  400. qiskit/pulse/parser.py +314 -0
  401. qiskit/pulse/reference_manager.py +58 -0
  402. qiskit/pulse/schedule.py +1854 -0
  403. qiskit/pulse/transforms/__init__.py +106 -0
  404. qiskit/pulse/transforms/alignments.py +406 -0
  405. qiskit/pulse/transforms/base_transforms.py +71 -0
  406. qiskit/pulse/transforms/canonicalization.py +498 -0
  407. qiskit/pulse/transforms/dag.py +122 -0
  408. qiskit/pulse/utils.py +149 -0
  409. qiskit/qasm/libs/dummy/stdgates.inc +75 -0
  410. qiskit/qasm/libs/qelib1.inc +266 -0
  411. qiskit/qasm/libs/stdgates.inc +82 -0
  412. qiskit/qasm2/__init__.py +654 -0
  413. qiskit/qasm2/exceptions.py +27 -0
  414. qiskit/qasm2/export.py +372 -0
  415. qiskit/qasm2/parse.py +452 -0
  416. qiskit/qasm3/__init__.py +367 -0
  417. qiskit/qasm3/ast.py +738 -0
  418. qiskit/qasm3/exceptions.py +27 -0
  419. qiskit/qasm3/experimental.py +70 -0
  420. qiskit/qasm3/exporter.py +1299 -0
  421. qiskit/qasm3/printer.py +577 -0
  422. qiskit/qobj/__init__.py +75 -0
  423. qiskit/qobj/common.py +81 -0
  424. qiskit/qobj/converters/__init__.py +18 -0
  425. qiskit/qobj/converters/lo_config.py +177 -0
  426. qiskit/qobj/converters/pulse_instruction.py +897 -0
  427. qiskit/qobj/pulse_qobj.py +709 -0
  428. qiskit/qobj/qasm_qobj.py +708 -0
  429. qiskit/qobj/utils.py +46 -0
  430. qiskit/qpy/__init__.py +1822 -0
  431. qiskit/qpy/binary_io/__init__.py +36 -0
  432. qiskit/qpy/binary_io/circuits.py +1475 -0
  433. qiskit/qpy/binary_io/schedules.py +635 -0
  434. qiskit/qpy/binary_io/value.py +1025 -0
  435. qiskit/qpy/common.py +350 -0
  436. qiskit/qpy/exceptions.py +53 -0
  437. qiskit/qpy/formats.py +401 -0
  438. qiskit/qpy/interface.py +377 -0
  439. qiskit/qpy/type_keys.py +572 -0
  440. qiskit/quantum_info/__init__.py +162 -0
  441. qiskit/quantum_info/analysis/__init__.py +17 -0
  442. qiskit/quantum_info/analysis/average.py +47 -0
  443. qiskit/quantum_info/analysis/distance.py +102 -0
  444. qiskit/quantum_info/analysis/make_observable.py +44 -0
  445. qiskit/quantum_info/analysis/z2_symmetries.py +484 -0
  446. qiskit/quantum_info/operators/__init__.py +28 -0
  447. qiskit/quantum_info/operators/base_operator.py +145 -0
  448. qiskit/quantum_info/operators/channel/__init__.py +29 -0
  449. qiskit/quantum_info/operators/channel/chi.py +191 -0
  450. qiskit/quantum_info/operators/channel/choi.py +218 -0
  451. qiskit/quantum_info/operators/channel/kraus.py +337 -0
  452. qiskit/quantum_info/operators/channel/ptm.py +204 -0
  453. qiskit/quantum_info/operators/channel/quantum_channel.py +348 -0
  454. qiskit/quantum_info/operators/channel/stinespring.py +296 -0
  455. qiskit/quantum_info/operators/channel/superop.py +377 -0
  456. qiskit/quantum_info/operators/channel/transformations.py +475 -0
  457. qiskit/quantum_info/operators/custom_iterator.py +48 -0
  458. qiskit/quantum_info/operators/dihedral/__init__.py +18 -0
  459. qiskit/quantum_info/operators/dihedral/dihedral.py +509 -0
  460. qiskit/quantum_info/operators/dihedral/dihedral_circuits.py +216 -0
  461. qiskit/quantum_info/operators/dihedral/polynomial.py +313 -0
  462. qiskit/quantum_info/operators/dihedral/random.py +64 -0
  463. qiskit/quantum_info/operators/linear_op.py +25 -0
  464. qiskit/quantum_info/operators/measures.py +418 -0
  465. qiskit/quantum_info/operators/mixins/__init__.py +52 -0
  466. qiskit/quantum_info/operators/mixins/adjoint.py +52 -0
  467. qiskit/quantum_info/operators/mixins/group.py +171 -0
  468. qiskit/quantum_info/operators/mixins/linear.py +84 -0
  469. qiskit/quantum_info/operators/mixins/multiply.py +62 -0
  470. qiskit/quantum_info/operators/mixins/tolerances.py +72 -0
  471. qiskit/quantum_info/operators/op_shape.py +525 -0
  472. qiskit/quantum_info/operators/operator.py +865 -0
  473. qiskit/quantum_info/operators/operator_utils.py +76 -0
  474. qiskit/quantum_info/operators/predicates.py +183 -0
  475. qiskit/quantum_info/operators/random.py +154 -0
  476. qiskit/quantum_info/operators/scalar_op.py +254 -0
  477. qiskit/quantum_info/operators/symplectic/__init__.py +23 -0
  478. qiskit/quantum_info/operators/symplectic/base_pauli.py +719 -0
  479. qiskit/quantum_info/operators/symplectic/clifford.py +1030 -0
  480. qiskit/quantum_info/operators/symplectic/clifford_circuits.py +558 -0
  481. qiskit/quantum_info/operators/symplectic/pauli.py +753 -0
  482. qiskit/quantum_info/operators/symplectic/pauli_list.py +1230 -0
  483. qiskit/quantum_info/operators/symplectic/pauli_utils.py +40 -0
  484. qiskit/quantum_info/operators/symplectic/random.py +117 -0
  485. qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py +1196 -0
  486. qiskit/quantum_info/operators/utils/__init__.py +20 -0
  487. qiskit/quantum_info/operators/utils/anti_commutator.py +36 -0
  488. qiskit/quantum_info/operators/utils/commutator.py +36 -0
  489. qiskit/quantum_info/operators/utils/double_commutator.py +76 -0
  490. qiskit/quantum_info/quaternion.py +156 -0
  491. qiskit/quantum_info/random.py +26 -0
  492. qiskit/quantum_info/states/__init__.py +28 -0
  493. qiskit/quantum_info/states/densitymatrix.py +845 -0
  494. qiskit/quantum_info/states/measures.py +288 -0
  495. qiskit/quantum_info/states/quantum_state.py +503 -0
  496. qiskit/quantum_info/states/random.py +157 -0
  497. qiskit/quantum_info/states/stabilizerstate.py +773 -0
  498. qiskit/quantum_info/states/statevector.py +958 -0
  499. qiskit/quantum_info/states/utils.py +247 -0
  500. qiskit/result/__init__.py +73 -0
  501. qiskit/result/counts.py +189 -0
  502. qiskit/result/distributions/__init__.py +17 -0
  503. qiskit/result/distributions/probability.py +100 -0
  504. qiskit/result/distributions/quasi.py +154 -0
  505. qiskit/result/exceptions.py +40 -0
  506. qiskit/result/mitigation/__init__.py +13 -0
  507. qiskit/result/mitigation/base_readout_mitigator.py +79 -0
  508. qiskit/result/mitigation/correlated_readout_mitigator.py +277 -0
  509. qiskit/result/mitigation/local_readout_mitigator.py +328 -0
  510. qiskit/result/mitigation/utils.py +217 -0
  511. qiskit/result/models.py +234 -0
  512. qiskit/result/postprocess.py +239 -0
  513. qiskit/result/result.py +392 -0
  514. qiskit/result/sampled_expval.py +75 -0
  515. qiskit/result/utils.py +295 -0
  516. qiskit/scheduler/__init__.py +40 -0
  517. qiskit/scheduler/config.py +37 -0
  518. qiskit/scheduler/lowering.py +187 -0
  519. qiskit/scheduler/methods/__init__.py +15 -0
  520. qiskit/scheduler/methods/basic.py +140 -0
  521. qiskit/scheduler/schedule_circuit.py +69 -0
  522. qiskit/scheduler/sequence.py +104 -0
  523. qiskit/synthesis/__init__.py +220 -0
  524. qiskit/synthesis/arithmetic/__init__.py +16 -0
  525. qiskit/synthesis/arithmetic/adders/__init__.py +17 -0
  526. qiskit/synthesis/arithmetic/adders/cdkm_ripple_carry_adder.py +154 -0
  527. qiskit/synthesis/arithmetic/adders/draper_qft_adder.py +103 -0
  528. qiskit/synthesis/arithmetic/adders/vbe_ripple_carry_adder.py +161 -0
  529. qiskit/synthesis/arithmetic/multipliers/__init__.py +16 -0
  530. qiskit/synthesis/arithmetic/multipliers/hrs_cumulative_multiplier.py +102 -0
  531. qiskit/synthesis/arithmetic/multipliers/rg_qft_multiplier.py +99 -0
  532. qiskit/synthesis/clifford/__init__.py +19 -0
  533. qiskit/synthesis/clifford/clifford_decompose_ag.py +178 -0
  534. qiskit/synthesis/clifford/clifford_decompose_bm.py +46 -0
  535. qiskit/synthesis/clifford/clifford_decompose_full.py +64 -0
  536. qiskit/synthesis/clifford/clifford_decompose_greedy.py +58 -0
  537. qiskit/synthesis/clifford/clifford_decompose_layers.py +447 -0
  538. qiskit/synthesis/cnotdihedral/__init__.py +17 -0
  539. qiskit/synthesis/cnotdihedral/cnotdihedral_decompose_full.py +52 -0
  540. qiskit/synthesis/cnotdihedral/cnotdihedral_decompose_general.py +141 -0
  541. qiskit/synthesis/cnotdihedral/cnotdihedral_decompose_two_qubits.py +266 -0
  542. qiskit/synthesis/discrete_basis/__init__.py +16 -0
  543. qiskit/synthesis/discrete_basis/commutator_decompose.py +241 -0
  544. qiskit/synthesis/discrete_basis/gate_sequence.py +415 -0
  545. qiskit/synthesis/discrete_basis/generate_basis_approximations.py +163 -0
  546. qiskit/synthesis/discrete_basis/solovay_kitaev.py +217 -0
  547. qiskit/synthesis/evolution/__init__.py +21 -0
  548. qiskit/synthesis/evolution/evolution_synthesis.py +48 -0
  549. qiskit/synthesis/evolution/lie_trotter.py +117 -0
  550. qiskit/synthesis/evolution/matrix_synthesis.py +47 -0
  551. qiskit/synthesis/evolution/pauli_network.py +80 -0
  552. qiskit/synthesis/evolution/product_formula.py +311 -0
  553. qiskit/synthesis/evolution/qdrift.py +138 -0
  554. qiskit/synthesis/evolution/suzuki_trotter.py +215 -0
  555. qiskit/synthesis/linear/__init__.py +26 -0
  556. qiskit/synthesis/linear/cnot_synth.py +69 -0
  557. qiskit/synthesis/linear/linear_circuits_utils.py +128 -0
  558. qiskit/synthesis/linear/linear_depth_lnn.py +276 -0
  559. qiskit/synthesis/linear/linear_matrix_utils.py +27 -0
  560. qiskit/synthesis/linear_phase/__init__.py +17 -0
  561. qiskit/synthesis/linear_phase/cnot_phase_synth.py +206 -0
  562. qiskit/synthesis/linear_phase/cx_cz_depth_lnn.py +262 -0
  563. qiskit/synthesis/linear_phase/cz_depth_lnn.py +58 -0
  564. qiskit/synthesis/multi_controlled/__init__.py +24 -0
  565. qiskit/synthesis/multi_controlled/mcmt_vchain.py +52 -0
  566. qiskit/synthesis/multi_controlled/mcx_synthesis.py +356 -0
  567. qiskit/synthesis/one_qubit/__init__.py +15 -0
  568. qiskit/synthesis/one_qubit/one_qubit_decompose.py +288 -0
  569. qiskit/synthesis/permutation/__init__.py +18 -0
  570. qiskit/synthesis/permutation/permutation_full.py +78 -0
  571. qiskit/synthesis/permutation/permutation_lnn.py +54 -0
  572. qiskit/synthesis/permutation/permutation_reverse_lnn.py +93 -0
  573. qiskit/synthesis/permutation/permutation_utils.py +16 -0
  574. qiskit/synthesis/qft/__init__.py +16 -0
  575. qiskit/synthesis/qft/qft_decompose_full.py +97 -0
  576. qiskit/synthesis/qft/qft_decompose_lnn.py +79 -0
  577. qiskit/synthesis/stabilizer/__init__.py +16 -0
  578. qiskit/synthesis/stabilizer/stabilizer_circuit.py +149 -0
  579. qiskit/synthesis/stabilizer/stabilizer_decompose.py +194 -0
  580. qiskit/synthesis/two_qubit/__init__.py +19 -0
  581. qiskit/synthesis/two_qubit/local_invariance.py +63 -0
  582. qiskit/synthesis/two_qubit/two_qubit_decompose.py +700 -0
  583. qiskit/synthesis/two_qubit/xx_decompose/__init__.py +19 -0
  584. qiskit/synthesis/two_qubit/xx_decompose/circuits.py +300 -0
  585. qiskit/synthesis/two_qubit/xx_decompose/decomposer.py +324 -0
  586. qiskit/synthesis/two_qubit/xx_decompose/embodiments.py +163 -0
  587. qiskit/synthesis/two_qubit/xx_decompose/paths.py +412 -0
  588. qiskit/synthesis/two_qubit/xx_decompose/polytopes.py +262 -0
  589. qiskit/synthesis/two_qubit/xx_decompose/utilities.py +40 -0
  590. qiskit/synthesis/two_qubit/xx_decompose/weyl.py +133 -0
  591. qiskit/synthesis/unitary/__init__.py +13 -0
  592. qiskit/synthesis/unitary/aqc/__init__.py +177 -0
  593. qiskit/synthesis/unitary/aqc/approximate.py +116 -0
  594. qiskit/synthesis/unitary/aqc/aqc.py +175 -0
  595. qiskit/synthesis/unitary/aqc/cnot_structures.py +300 -0
  596. qiskit/synthesis/unitary/aqc/cnot_unit_circuit.py +103 -0
  597. qiskit/synthesis/unitary/aqc/cnot_unit_objective.py +299 -0
  598. qiskit/synthesis/unitary/aqc/elementary_operations.py +108 -0
  599. qiskit/synthesis/unitary/aqc/fast_gradient/__init__.py +164 -0
  600. qiskit/synthesis/unitary/aqc/fast_gradient/fast_grad_utils.py +237 -0
  601. qiskit/synthesis/unitary/aqc/fast_gradient/fast_gradient.py +226 -0
  602. qiskit/synthesis/unitary/aqc/fast_gradient/layer.py +370 -0
  603. qiskit/synthesis/unitary/aqc/fast_gradient/pmatrix.py +312 -0
  604. qiskit/synthesis/unitary/qsd.py +288 -0
  605. qiskit/transpiler/__init__.py +1290 -0
  606. qiskit/transpiler/basepasses.py +221 -0
  607. qiskit/transpiler/coupling.py +500 -0
  608. qiskit/transpiler/exceptions.py +59 -0
  609. qiskit/transpiler/instruction_durations.py +281 -0
  610. qiskit/transpiler/layout.py +737 -0
  611. qiskit/transpiler/passes/__init__.py +312 -0
  612. qiskit/transpiler/passes/analysis/__init__.py +23 -0
  613. qiskit/transpiler/passes/analysis/count_ops.py +30 -0
  614. qiskit/transpiler/passes/analysis/count_ops_longest_path.py +26 -0
  615. qiskit/transpiler/passes/analysis/dag_longest_path.py +24 -0
  616. qiskit/transpiler/passes/analysis/depth.py +33 -0
  617. qiskit/transpiler/passes/analysis/num_qubits.py +26 -0
  618. qiskit/transpiler/passes/analysis/num_tensor_factors.py +26 -0
  619. qiskit/transpiler/passes/analysis/resource_estimation.py +41 -0
  620. qiskit/transpiler/passes/analysis/size.py +36 -0
  621. qiskit/transpiler/passes/analysis/width.py +27 -0
  622. qiskit/transpiler/passes/basis/__init__.py +19 -0
  623. qiskit/transpiler/passes/basis/basis_translator.py +137 -0
  624. qiskit/transpiler/passes/basis/decompose.py +131 -0
  625. qiskit/transpiler/passes/basis/translate_parameterized.py +175 -0
  626. qiskit/transpiler/passes/basis/unroll_3q_or_more.py +88 -0
  627. qiskit/transpiler/passes/basis/unroll_custom_definitions.py +109 -0
  628. qiskit/transpiler/passes/calibration/__init__.py +17 -0
  629. qiskit/transpiler/passes/calibration/base_builder.py +79 -0
  630. qiskit/transpiler/passes/calibration/builders.py +20 -0
  631. qiskit/transpiler/passes/calibration/exceptions.py +22 -0
  632. qiskit/transpiler/passes/calibration/pulse_gate.py +100 -0
  633. qiskit/transpiler/passes/calibration/rx_builder.py +164 -0
  634. qiskit/transpiler/passes/calibration/rzx_builder.py +411 -0
  635. qiskit/transpiler/passes/calibration/rzx_templates.py +51 -0
  636. qiskit/transpiler/passes/layout/__init__.py +26 -0
  637. qiskit/transpiler/passes/layout/_csp_custom_solver.py +65 -0
  638. qiskit/transpiler/passes/layout/apply_layout.py +123 -0
  639. qiskit/transpiler/passes/layout/csp_layout.py +132 -0
  640. qiskit/transpiler/passes/layout/dense_layout.py +202 -0
  641. qiskit/transpiler/passes/layout/disjoint_utils.py +219 -0
  642. qiskit/transpiler/passes/layout/enlarge_with_ancilla.py +49 -0
  643. qiskit/transpiler/passes/layout/full_ancilla_allocation.py +117 -0
  644. qiskit/transpiler/passes/layout/layout_2q_distance.py +77 -0
  645. qiskit/transpiler/passes/layout/sabre_layout.py +487 -0
  646. qiskit/transpiler/passes/layout/sabre_pre_layout.py +225 -0
  647. qiskit/transpiler/passes/layout/set_layout.py +69 -0
  648. qiskit/transpiler/passes/layout/trivial_layout.py +66 -0
  649. qiskit/transpiler/passes/layout/vf2_layout.py +263 -0
  650. qiskit/transpiler/passes/layout/vf2_post_layout.py +419 -0
  651. qiskit/transpiler/passes/layout/vf2_utils.py +260 -0
  652. qiskit/transpiler/passes/optimization/__init__.py +43 -0
  653. qiskit/transpiler/passes/optimization/_gate_extension.py +80 -0
  654. qiskit/transpiler/passes/optimization/collect_1q_runs.py +31 -0
  655. qiskit/transpiler/passes/optimization/collect_2q_blocks.py +35 -0
  656. qiskit/transpiler/passes/optimization/collect_and_collapse.py +115 -0
  657. qiskit/transpiler/passes/optimization/collect_cliffords.py +104 -0
  658. qiskit/transpiler/passes/optimization/collect_linear_functions.py +80 -0
  659. qiskit/transpiler/passes/optimization/collect_multiqubit_blocks.py +227 -0
  660. qiskit/transpiler/passes/optimization/commutation_analysis.py +44 -0
  661. qiskit/transpiler/passes/optimization/commutative_cancellation.py +82 -0
  662. qiskit/transpiler/passes/optimization/commutative_inverse_cancellation.py +140 -0
  663. qiskit/transpiler/passes/optimization/consolidate_blocks.py +149 -0
  664. qiskit/transpiler/passes/optimization/cx_cancellation.py +65 -0
  665. qiskit/transpiler/passes/optimization/echo_rzx_weyl_decomposition.py +162 -0
  666. qiskit/transpiler/passes/optimization/elide_permutations.py +91 -0
  667. qiskit/transpiler/passes/optimization/hoare_opt.py +420 -0
  668. qiskit/transpiler/passes/optimization/inverse_cancellation.py +95 -0
  669. qiskit/transpiler/passes/optimization/normalize_rx_angle.py +149 -0
  670. qiskit/transpiler/passes/optimization/optimize_1q_commutation.py +268 -0
  671. qiskit/transpiler/passes/optimization/optimize_1q_decomposition.py +254 -0
  672. qiskit/transpiler/passes/optimization/optimize_1q_gates.py +384 -0
  673. qiskit/transpiler/passes/optimization/optimize_annotated.py +448 -0
  674. qiskit/transpiler/passes/optimization/optimize_cliffords.py +89 -0
  675. qiskit/transpiler/passes/optimization/optimize_swap_before_measure.py +71 -0
  676. qiskit/transpiler/passes/optimization/remove_diagonal_gates_before_measure.py +41 -0
  677. qiskit/transpiler/passes/optimization/remove_final_reset.py +37 -0
  678. qiskit/transpiler/passes/optimization/remove_identity_equiv.py +69 -0
  679. qiskit/transpiler/passes/optimization/remove_reset_in_zero_state.py +37 -0
  680. qiskit/transpiler/passes/optimization/reset_after_measure_simplification.py +47 -0
  681. qiskit/transpiler/passes/optimization/split_2q_unitaries.py +40 -0
  682. qiskit/transpiler/passes/optimization/template_matching/__init__.py +19 -0
  683. qiskit/transpiler/passes/optimization/template_matching/backward_match.py +749 -0
  684. qiskit/transpiler/passes/optimization/template_matching/forward_match.py +452 -0
  685. qiskit/transpiler/passes/optimization/template_matching/maximal_matches.py +77 -0
  686. qiskit/transpiler/passes/optimization/template_matching/template_matching.py +370 -0
  687. qiskit/transpiler/passes/optimization/template_matching/template_substitution.py +638 -0
  688. qiskit/transpiler/passes/optimization/template_optimization.py +158 -0
  689. qiskit/transpiler/passes/routing/__init__.py +22 -0
  690. qiskit/transpiler/passes/routing/algorithms/__init__.py +33 -0
  691. qiskit/transpiler/passes/routing/algorithms/token_swapper.py +105 -0
  692. qiskit/transpiler/passes/routing/algorithms/types.py +46 -0
  693. qiskit/transpiler/passes/routing/algorithms/util.py +103 -0
  694. qiskit/transpiler/passes/routing/basic_swap.py +166 -0
  695. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/__init__.py +25 -0
  696. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_block.py +60 -0
  697. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py +395 -0
  698. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py +145 -0
  699. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py +306 -0
  700. qiskit/transpiler/passes/routing/layout_transformation.py +119 -0
  701. qiskit/transpiler/passes/routing/lookahead_swap.py +390 -0
  702. qiskit/transpiler/passes/routing/sabre_swap.py +447 -0
  703. qiskit/transpiler/passes/routing/star_prerouting.py +392 -0
  704. qiskit/transpiler/passes/routing/stochastic_swap.py +532 -0
  705. qiskit/transpiler/passes/routing/utils.py +35 -0
  706. qiskit/transpiler/passes/scheduling/__init__.py +27 -0
  707. qiskit/transpiler/passes/scheduling/alap.py +153 -0
  708. qiskit/transpiler/passes/scheduling/alignments/__init__.py +81 -0
  709. qiskit/transpiler/passes/scheduling/alignments/align_measures.py +255 -0
  710. qiskit/transpiler/passes/scheduling/alignments/check_durations.py +78 -0
  711. qiskit/transpiler/passes/scheduling/alignments/pulse_gate_validation.py +107 -0
  712. qiskit/transpiler/passes/scheduling/alignments/reschedule.py +250 -0
  713. qiskit/transpiler/passes/scheduling/asap.py +175 -0
  714. qiskit/transpiler/passes/scheduling/base_scheduler.py +310 -0
  715. qiskit/transpiler/passes/scheduling/dynamical_decoupling.py +312 -0
  716. qiskit/transpiler/passes/scheduling/padding/__init__.py +16 -0
  717. qiskit/transpiler/passes/scheduling/padding/base_padding.py +256 -0
  718. qiskit/transpiler/passes/scheduling/padding/dynamical_decoupling.py +452 -0
  719. qiskit/transpiler/passes/scheduling/padding/pad_delay.py +82 -0
  720. qiskit/transpiler/passes/scheduling/scheduling/__init__.py +17 -0
  721. qiskit/transpiler/passes/scheduling/scheduling/alap.py +127 -0
  722. qiskit/transpiler/passes/scheduling/scheduling/asap.py +131 -0
  723. qiskit/transpiler/passes/scheduling/scheduling/base_scheduler.py +94 -0
  724. qiskit/transpiler/passes/scheduling/scheduling/set_io_latency.py +64 -0
  725. qiskit/transpiler/passes/scheduling/time_unit_conversion.py +165 -0
  726. qiskit/transpiler/passes/synthesis/__init__.py +20 -0
  727. qiskit/transpiler/passes/synthesis/aqc_plugin.py +153 -0
  728. qiskit/transpiler/passes/synthesis/high_level_synthesis.py +854 -0
  729. qiskit/transpiler/passes/synthesis/hls_plugins.py +1559 -0
  730. qiskit/transpiler/passes/synthesis/linear_functions_synthesis.py +41 -0
  731. qiskit/transpiler/passes/synthesis/plugin.py +734 -0
  732. qiskit/transpiler/passes/synthesis/solovay_kitaev_synthesis.py +297 -0
  733. qiskit/transpiler/passes/synthesis/unitary_synthesis.py +1076 -0
  734. qiskit/transpiler/passes/utils/__init__.py +33 -0
  735. qiskit/transpiler/passes/utils/barrier_before_final_measurements.py +41 -0
  736. qiskit/transpiler/passes/utils/check_gate_direction.py +52 -0
  737. qiskit/transpiler/passes/utils/check_map.py +78 -0
  738. qiskit/transpiler/passes/utils/contains_instruction.py +45 -0
  739. qiskit/transpiler/passes/utils/control_flow.py +65 -0
  740. qiskit/transpiler/passes/utils/convert_conditions_to_if_ops.py +93 -0
  741. qiskit/transpiler/passes/utils/dag_fixed_point.py +36 -0
  742. qiskit/transpiler/passes/utils/error.py +69 -0
  743. qiskit/transpiler/passes/utils/filter_op_nodes.py +65 -0
  744. qiskit/transpiler/passes/utils/fixed_point.py +48 -0
  745. qiskit/transpiler/passes/utils/gate_direction.py +86 -0
  746. qiskit/transpiler/passes/utils/gates_basis.py +51 -0
  747. qiskit/transpiler/passes/utils/merge_adjacent_barriers.py +163 -0
  748. qiskit/transpiler/passes/utils/minimum_point.py +118 -0
  749. qiskit/transpiler/passes/utils/remove_barriers.py +49 -0
  750. qiskit/transpiler/passes/utils/remove_final_measurements.py +114 -0
  751. qiskit/transpiler/passes/utils/unroll_forloops.py +81 -0
  752. qiskit/transpiler/passmanager.py +490 -0
  753. qiskit/transpiler/passmanager_config.py +216 -0
  754. qiskit/transpiler/preset_passmanagers/__init__.py +73 -0
  755. qiskit/transpiler/preset_passmanagers/builtin_plugins.py +1045 -0
  756. qiskit/transpiler/preset_passmanagers/common.py +649 -0
  757. qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py +626 -0
  758. qiskit/transpiler/preset_passmanagers/level0.py +113 -0
  759. qiskit/transpiler/preset_passmanagers/level1.py +120 -0
  760. qiskit/transpiler/preset_passmanagers/level2.py +119 -0
  761. qiskit/transpiler/preset_passmanagers/level3.py +119 -0
  762. qiskit/transpiler/preset_passmanagers/plugin.py +353 -0
  763. qiskit/transpiler/target.py +1319 -0
  764. qiskit/transpiler/timing_constraints.py +59 -0
  765. qiskit/user_config.py +262 -0
  766. qiskit/utils/__init__.py +89 -0
  767. qiskit/utils/classtools.py +146 -0
  768. qiskit/utils/deprecate_pulse.py +119 -0
  769. qiskit/utils/deprecation.py +490 -0
  770. qiskit/utils/lazy_tester.py +363 -0
  771. qiskit/utils/multiprocessing.py +56 -0
  772. qiskit/utils/optionals.py +347 -0
  773. qiskit/utils/parallel.py +191 -0
  774. qiskit/utils/units.py +143 -0
  775. qiskit/version.py +84 -0
  776. qiskit/visualization/__init__.py +288 -0
  777. qiskit/visualization/array.py +204 -0
  778. qiskit/visualization/bloch.py +778 -0
  779. qiskit/visualization/circuit/__init__.py +15 -0
  780. qiskit/visualization/circuit/_utils.py +675 -0
  781. qiskit/visualization/circuit/circuit_visualization.py +727 -0
  782. qiskit/visualization/circuit/latex.py +661 -0
  783. qiskit/visualization/circuit/matplotlib.py +2029 -0
  784. qiskit/visualization/circuit/qcstyle.py +278 -0
  785. qiskit/visualization/circuit/styles/__init__.py +13 -0
  786. qiskit/visualization/circuit/styles/bw.json +202 -0
  787. qiskit/visualization/circuit/styles/clifford.json +202 -0
  788. qiskit/visualization/circuit/styles/iqp-dark.json +214 -0
  789. qiskit/visualization/circuit/styles/iqp.json +214 -0
  790. qiskit/visualization/circuit/styles/textbook.json +202 -0
  791. qiskit/visualization/circuit/text.py +1844 -0
  792. qiskit/visualization/circuit_visualization.py +19 -0
  793. qiskit/visualization/counts_visualization.py +481 -0
  794. qiskit/visualization/dag_visualization.py +316 -0
  795. qiskit/visualization/exceptions.py +21 -0
  796. qiskit/visualization/gate_map.py +1485 -0
  797. qiskit/visualization/library.py +37 -0
  798. qiskit/visualization/pass_manager_visualization.py +308 -0
  799. qiskit/visualization/pulse_v2/__init__.py +21 -0
  800. qiskit/visualization/pulse_v2/core.py +901 -0
  801. qiskit/visualization/pulse_v2/device_info.py +173 -0
  802. qiskit/visualization/pulse_v2/drawings.py +253 -0
  803. qiskit/visualization/pulse_v2/events.py +254 -0
  804. qiskit/visualization/pulse_v2/generators/__init__.py +40 -0
  805. qiskit/visualization/pulse_v2/generators/barrier.py +76 -0
  806. qiskit/visualization/pulse_v2/generators/chart.py +208 -0
  807. qiskit/visualization/pulse_v2/generators/frame.py +436 -0
  808. qiskit/visualization/pulse_v2/generators/snapshot.py +133 -0
  809. qiskit/visualization/pulse_v2/generators/waveform.py +645 -0
  810. qiskit/visualization/pulse_v2/interface.py +458 -0
  811. qiskit/visualization/pulse_v2/layouts.py +387 -0
  812. qiskit/visualization/pulse_v2/plotters/__init__.py +17 -0
  813. qiskit/visualization/pulse_v2/plotters/base_plotter.py +53 -0
  814. qiskit/visualization/pulse_v2/plotters/matplotlib.py +201 -0
  815. qiskit/visualization/pulse_v2/stylesheet.py +312 -0
  816. qiskit/visualization/pulse_v2/types.py +242 -0
  817. qiskit/visualization/state_visualization.py +1518 -0
  818. qiskit/visualization/timeline/__init__.py +21 -0
  819. qiskit/visualization/timeline/core.py +480 -0
  820. qiskit/visualization/timeline/drawings.py +260 -0
  821. qiskit/visualization/timeline/generators.py +506 -0
  822. qiskit/visualization/timeline/interface.py +436 -0
  823. qiskit/visualization/timeline/layouts.py +115 -0
  824. qiskit/visualization/timeline/plotters/__init__.py +16 -0
  825. qiskit/visualization/timeline/plotters/base_plotter.py +58 -0
  826. qiskit/visualization/timeline/plotters/matplotlib.py +192 -0
  827. qiskit/visualization/timeline/stylesheet.py +301 -0
  828. qiskit/visualization/timeline/types.py +148 -0
  829. qiskit/visualization/transition_visualization.py +369 -0
  830. qiskit/visualization/utils.py +49 -0
  831. qiskit-1.3.0.dist-info/LICENSE.txt +203 -0
  832. qiskit-1.3.0.dist-info/METADATA +222 -0
  833. qiskit-1.3.0.dist-info/RECORD +836 -0
  834. qiskit-1.3.0.dist-info/WHEEL +5 -0
  835. qiskit-1.3.0.dist-info/entry_points.txt +76 -0
  836. qiskit-1.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1472 @@
1
+ # This code is part of Qiskit.
2
+ #
3
+ # (C) Copyright IBM 2017, 2020.
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
+ """The n-local circuit class."""
14
+
15
+ from __future__ import annotations
16
+
17
+ import collections
18
+ import itertools
19
+ import typing
20
+ from collections.abc import Callable, Mapping, Sequence, Iterable
21
+
22
+ import numpy
23
+ from qiskit.circuit.gate import Gate
24
+ from qiskit.circuit.quantumcircuit import QuantumCircuit, ParameterValueType
25
+ from qiskit.circuit.parametervector import ParameterVector, ParameterVectorElement
26
+ from qiskit.circuit.quantumregister import QuantumRegister
27
+ from qiskit.circuit import (
28
+ Instruction,
29
+ Parameter,
30
+ ParameterExpression,
31
+ CircuitInstruction,
32
+ )
33
+ from qiskit.exceptions import QiskitError
34
+ from qiskit.circuit.library.standard_gates import get_standard_gate_name_mapping
35
+ from qiskit.utils.deprecation import deprecate_func
36
+
37
+ from qiskit._accelerate.circuit_library import (
38
+ Block,
39
+ py_n_local,
40
+ get_entangler_map as fast_entangler_map,
41
+ )
42
+
43
+ from ..blueprintcircuit import BlueprintCircuit
44
+
45
+
46
+ if typing.TYPE_CHECKING:
47
+ import qiskit # pylint: disable=cyclic-import
48
+
49
+ # entanglement for an individual block, e.g. if the block is CXGate() and we have
50
+ # 3 qubits, this could be [(0, 1), (1, 2), (2, 0)]
51
+ BlockEntanglement = typing.Union[str, Iterable[Iterable[int]]]
52
+
53
+
54
+ def n_local(
55
+ num_qubits: int,
56
+ rotation_blocks: str | Gate | Iterable[str | Gate],
57
+ entanglement_blocks: str | Gate | Iterable[str | Gate],
58
+ entanglement: (
59
+ BlockEntanglement
60
+ | Iterable[BlockEntanglement]
61
+ | Callable[[int], BlockEntanglement | Iterable[BlockEntanglement]]
62
+ ) = "full",
63
+ reps: int = 3,
64
+ insert_barriers: bool = False,
65
+ parameter_prefix: str = "θ",
66
+ overwrite_block_parameters: bool = True,
67
+ skip_final_rotation_layer: bool = False,
68
+ skip_unentangled_qubits: bool = False,
69
+ name: str | None = "nlocal",
70
+ ) -> QuantumCircuit:
71
+ r"""Construct an n-local variational circuit.
72
+
73
+ The structure of the n-local circuit are alternating rotation and entanglement layers.
74
+ In both layers, parameterized circuit-blocks act on the circuit in a defined way.
75
+ In the rotation layer, the blocks are applied stacked on top of each other, while in the
76
+ entanglement layer according to the ``entanglement`` strategy.
77
+ The circuit blocks can have arbitrary sizes (smaller equal to the number of qubits in the
78
+ circuit). Each layer is repeated ``reps`` times, and by default a final rotation layer is
79
+ appended.
80
+
81
+ For instance, a rotation block on 2 qubits and an entanglement block on 4 qubits using
82
+ ``"linear"`` entanglement yields the following circuit.
83
+
84
+ .. parsed-literal::
85
+
86
+ ┌──────┐ ░ ┌──────┐ ░ ┌──────┐
87
+ ┤0 ├─░─┤0 ├──────────────── ... ─░─┤0 ├
88
+ │ Rot │ ░ │ │┌──────┐ ░ │ Rot │
89
+ ┤1 ├─░─┤1 ├┤0 ├──────── ... ─░─┤1 ├
90
+ ├──────┤ ░ │ Ent ││ │┌──────┐ ░ ├──────┤
91
+ ┤0 ├─░─┤2 ├┤1 ├┤0 ├ ... ─░─┤0 ├
92
+ │ Rot │ ░ │ ││ Ent ││ │ ░ │ Rot │
93
+ ┤1 ├─░─┤3 ├┤2 ├┤1 ├ ... ─░─┤1 ├
94
+ ├──────┤ ░ └──────┘│ ││ Ent │ ░ ├──────┤
95
+ ┤0 ├─░─────────┤3 ├┤2 ├ ... ─░─┤0 ├
96
+ │ Rot │ ░ └──────┘│ │ ░ │ Rot │
97
+ ┤1 ├─░─────────────────┤3 ├ ... ─░─┤1 ├
98
+ └──────┘ ░ └──────┘ ░ └──────┘
99
+
100
+ | |
101
+ +---------------------------------+
102
+ repeated reps times
103
+
104
+ Entanglement:
105
+
106
+ The entanglement describes the connections of the gates in the entanglement layer.
107
+ For a two-qubit gate for example, the entanglement contains pairs of qubits on which the
108
+ gate should acts, e.g. ``[[ctrl0, target0], [ctrl1, target1], ...]``.
109
+ A set of default entanglement strategies is provided and can be selected by name:
110
+
111
+ * ``"full"`` entanglement is each qubit is entangled with all the others.
112
+ * ``"linear"`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`,
113
+ for all :math:`i \in \{0, 1, ... , n - 2\}`, where :math:`n` is the total number of qubits.
114
+ * ``"reverse_linear"`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`,
115
+ for all :math:`i \in \{n-2, n-3, ... , 1, 0\}`, where :math:`n` is the total number of qubits.
116
+ Note that if ``entanglement_blocks=="cx"`` then this option provides the same unitary as
117
+ ``"full"`` with fewer entangling gates.
118
+ * ``"pairwise"`` entanglement is one layer where qubit :math:`i` is entangled with qubit
119
+ :math:`i + 1`, for all even values of :math:`i`, and then a second layer where qubit :math:`i`
120
+ is entangled with qubit :math:`i + 1`, for all odd values of :math:`i`.
121
+ * ``"circular"`` entanglement is linear entanglement but with an additional entanglement of the
122
+ first and last qubit before the linear part.
123
+ * ``"sca"`` (shifted-circular-alternating) entanglement is a generalized and modified version
124
+ of the proposed circuit 14 in `Sim et al. <https://arxiv.org/abs/1905.10876>`__.
125
+ It consists of circular entanglement where the "long" entanglement connecting the first with
126
+ the last qubit is shifted by one each block. Furthermore the role of control and target
127
+ qubits are swapped every block (therefore alternating).
128
+
129
+ If an entanglement layer contains multiple blocks, then the entanglement should be
130
+ given as list of entanglements for each block. For example::
131
+
132
+ entanglement_blocks = ["rxx", "ryy"]
133
+ entanglement = ["full", "linear"] # full for rxx and linear for ryy
134
+
135
+ or::
136
+
137
+ structure_rxx = [[0, 1], [2, 3]]
138
+ structure_ryy = [[0, 2]]
139
+ entanglement = [structure_rxx, structure_ryy]
140
+
141
+ Finally, the entanglement can vary in each repetition of the circuit. For this, we
142
+ support passing a callable that takes as input the layer index and returns the entanglement
143
+ for the layer in the above format. See the examples below for a concrete example.
144
+
145
+ Examples:
146
+
147
+ The rotation and entanglement gates can be specified via single strings, if they
148
+ are made up of a single block per layer:
149
+
150
+ .. plot::
151
+ :include-source:
152
+ :context:
153
+
154
+ from qiskit.circuit.library import n_local
155
+
156
+ circuit = n_local(3, "ry", "cx", "linear", reps=2, insert_barriers=True)
157
+ circuit.draw("mpl")
158
+
159
+ Multiple gates per layer can be set by passing a list. Here, for example, we use
160
+ Pauli-Y and Pauli-Z rotations in the rotation layer:
161
+
162
+ .. plot::
163
+ :include-source:
164
+ :context:
165
+
166
+ circuit = n_local(3, ["ry", "rz"], "cz", "full", reps=1, insert_barriers=True)
167
+ circuit.draw("mpl")
168
+
169
+ To omit rotation or entanglement layers, the block can be set to an empty list:
170
+
171
+ .. plot::
172
+ :include-source:
173
+ :context:
174
+
175
+ circuit = n_local(4, [], "cry", reps=2)
176
+ circuit.draw("mpl")
177
+
178
+ The entanglement can be set explicitly via the ``entanglement`` argument:
179
+
180
+ .. plot::
181
+ :include-source:
182
+ :context:
183
+
184
+ entangler_map = [[0, 1], [2, 0]]
185
+ circuit = n_local(3, "x", "crx", entangler_map, reps=2)
186
+ circuit.draw("mpl")
187
+
188
+ We can set different entanglements per layer, by specifing a callable that takes
189
+ as input the current layer index, and returns the entanglement structure. For example,
190
+ the following uses different entanglements for odd and even layers:
191
+
192
+ .. plot:
193
+ :include-source:
194
+ :context:
195
+
196
+ def entanglement(layer_index):
197
+ if layer_index % 2 == 0:
198
+ return [[0, 1], [0, 2]]
199
+ return [[1, 2]]
200
+
201
+ circuit = n_local(3, "x", "cx", entanglement, reps=3, insert_barriers=True)
202
+ circuit.draw("mpl")
203
+
204
+
205
+ Args:
206
+ num_qubits: The number of qubits of the circuit.
207
+ rotation_blocks: The blocks used in the rotation layers. If multiple are passed,
208
+ these will be applied one after another (like new sub-layers).
209
+ entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed,
210
+ these will be applied one after another.
211
+ entanglement: The indices specifying on which qubits the input blocks act. This is
212
+ specified by string describing an entanglement strategy (see the additional info)
213
+ or a list of qubit connections.
214
+ If a list of entanglement blocks is passed, different entanglement for each block can
215
+ be specified by passing a list of entanglements. To specify varying entanglement for
216
+ each repetition, pass a callable that takes as input the layer and returns the
217
+ entanglement for that layer.
218
+ Defaults to ``"full"``, meaning an all-to-all entanglement structure.
219
+ reps: Specifies how often the rotation blocks and entanglement blocks are repeated.
220
+ insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``,
221
+ no barriers are inserted.
222
+ parameter_prefix: The prefix used if default parameters are generated.
223
+ overwrite_block_parameters: If the parameters in the added blocks should be overwritten.
224
+ If ``False``, the parameters in the blocks are not changed.
225
+ skip_final_rotation_layer: Whether a final rotation layer is added to the circuit.
226
+ skip_unentangled_qubits: If ``True``, the rotation gates act only on qubits that
227
+ are entangled. If ``False``, the rotation gates act on all qubits.
228
+ name: The name of the circuit.
229
+
230
+ Returns:
231
+ An n-local circuit.
232
+ """
233
+ if reps < 0:
234
+ # this is an important check, since we cast this to an unsigned integer Rust-side
235
+ raise ValueError(f"reps must be non-negative, but is {reps}")
236
+
237
+ supported_gates = get_standard_gate_name_mapping()
238
+ rotation_blocks = _normalize_blocks(
239
+ rotation_blocks, supported_gates, overwrite_block_parameters
240
+ )
241
+ entanglement_blocks = _normalize_blocks(
242
+ entanglement_blocks, supported_gates, overwrite_block_parameters
243
+ )
244
+
245
+ entanglement = _normalize_entanglement(entanglement, len(entanglement_blocks))
246
+
247
+ data = py_n_local(
248
+ num_qubits=num_qubits,
249
+ rotation_blocks=rotation_blocks,
250
+ entanglement_blocks=entanglement_blocks,
251
+ entanglement=entanglement,
252
+ reps=reps,
253
+ insert_barriers=insert_barriers,
254
+ parameter_prefix=parameter_prefix,
255
+ skip_final_rotation_layer=skip_final_rotation_layer,
256
+ skip_unentangled_qubits=skip_unentangled_qubits,
257
+ )
258
+ circuit = QuantumCircuit._from_circuit_data(data, add_regs=True, name=name)
259
+
260
+ return circuit
261
+
262
+
263
+ class NLocal(BlueprintCircuit):
264
+ """The n-local circuit class.
265
+
266
+ The structure of the n-local circuit are alternating rotation and entanglement layers.
267
+ In both layers, parameterized circuit-blocks act on the circuit in a defined way.
268
+ In the rotation layer, the blocks are applied stacked on top of each other, while in the
269
+ entanglement layer according to the ``entanglement`` strategy.
270
+ The circuit blocks can have arbitrary sizes (smaller equal to the number of qubits in the
271
+ circuit). Each layer is repeated ``reps`` times, and by default a final rotation layer is
272
+ appended.
273
+
274
+ For instance, a rotation block on 2 qubits and an entanglement block on 4 qubits using
275
+ ``'linear'`` entanglement yields the following circuit.
276
+
277
+ .. code-block:: text
278
+
279
+ ┌──────┐ ░ ┌──────┐ ░ ┌──────┐
280
+ ┤0 ├─░─┤0 ├──────────────── ... ─░─┤0 ├
281
+ │ Rot │ ░ │ │┌──────┐ ░ │ Rot │
282
+ ┤1 ├─░─┤1 ├┤0 ├──────── ... ─░─┤1 ├
283
+ ├──────┤ ░ │ Ent ││ │┌──────┐ ░ ├──────┤
284
+ ┤0 ├─░─┤2 ├┤1 ├┤0 ├ ... ─░─┤0 ├
285
+ │ Rot │ ░ │ ││ Ent ││ │ ░ │ Rot │
286
+ ┤1 ├─░─┤3 ├┤2 ├┤1 ├ ... ─░─┤1 ├
287
+ ├──────┤ ░ └──────┘│ ││ Ent │ ░ ├──────┤
288
+ ┤0 ├─░─────────┤3 ├┤2 ├ ... ─░─┤0 ├
289
+ │ Rot │ ░ └──────┘│ │ ░ │ Rot │
290
+ ┤1 ├─░─────────────────┤3 ├ ... ─░─┤1 ├
291
+ └──────┘ ░ └──────┘ ░ └──────┘
292
+
293
+ | |
294
+ +---------------------------------+
295
+ repeated reps times
296
+
297
+ If specified, barriers can be inserted in between every block.
298
+ If an initial state object is provided, it is added in front of the NLocal.
299
+
300
+ .. seealso::
301
+
302
+ The :func:`.n_local` function constructs a functionally equivalent circuit, but faster.
303
+
304
+ """
305
+
306
+ @deprecate_func(
307
+ since="1.3",
308
+ additional_msg="Use the function qiskit.circuit.library.n_local instead.",
309
+ pending=True,
310
+ )
311
+ def __init__(
312
+ self,
313
+ num_qubits: int | None = None,
314
+ rotation_blocks: (
315
+ QuantumCircuit
316
+ | list[QuantumCircuit]
317
+ | qiskit.circuit.Instruction
318
+ | list[qiskit.circuit.Instruction]
319
+ | None
320
+ ) = None,
321
+ entanglement_blocks: (
322
+ QuantumCircuit
323
+ | list[QuantumCircuit]
324
+ | qiskit.circuit.Instruction
325
+ | list[qiskit.circuit.Instruction]
326
+ | None
327
+ ) = None,
328
+ entanglement: list[int] | list[list[int]] | None = None,
329
+ reps: int = 1,
330
+ insert_barriers: bool = False,
331
+ parameter_prefix: str = "θ",
332
+ overwrite_block_parameters: bool | list[list[Parameter]] = True,
333
+ skip_final_rotation_layer: bool = False,
334
+ skip_unentangled_qubits: bool = False,
335
+ initial_state: QuantumCircuit | None = None,
336
+ name: str | None = "nlocal",
337
+ flatten: bool | None = None,
338
+ ) -> None:
339
+ """
340
+ Args:
341
+ num_qubits: The number of qubits of the circuit.
342
+ rotation_blocks: The blocks used in the rotation layers. If multiple are passed,
343
+ these will be applied one after another (like new sub-layers).
344
+ entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed,
345
+ these will be applied one after another. To use different entanglements for
346
+ the sub-layers, see :meth:`get_entangler_map`.
347
+ entanglement: The indices specifying on which qubits the input blocks act. If ``None``, the
348
+ entanglement blocks are applied at the top of the circuit.
349
+ reps: Specifies how often the rotation blocks and entanglement blocks are repeated.
350
+ insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``,
351
+ no barriers are inserted.
352
+ parameter_prefix: The prefix used if default parameters are generated.
353
+ overwrite_block_parameters: If the parameters in the added blocks should be overwritten.
354
+ If ``False``, the parameters in the blocks are not changed.
355
+ skip_final_rotation_layer: Whether a final rotation layer is added to the circuit.
356
+ skip_unentangled_qubits: If ``True``, the rotation gates act only on qubits that
357
+ are entangled. If ``False``, the rotation gates act on all qubits.
358
+ initial_state: A :class:`.QuantumCircuit` object which can be used to describe an initial
359
+ state prepended to the NLocal circuit.
360
+ name: The name of the circuit.
361
+ flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple
362
+ layers of gate objects. By default currently the contents of
363
+ the output circuit will be wrapped in nested objects for
364
+ cleaner visualization. However, if you're using this circuit
365
+ for anything besides visualization its **strongly** recommended
366
+ to set this flag to ``True`` to avoid a large performance
367
+ overhead for parameter binding.
368
+
369
+ Raises:
370
+ ValueError: If ``reps`` parameter is less than or equal to 0.
371
+ TypeError: If ``reps`` parameter is not an int value.
372
+ """
373
+ super().__init__(name=name)
374
+
375
+ self._num_qubits: int | None = None
376
+ self._insert_barriers = insert_barriers
377
+ self._reps = reps
378
+ self._entanglement_blocks: list[QuantumCircuit] = []
379
+ self._rotation_blocks: list[QuantumCircuit] = []
380
+ self._prepended_blocks: list[QuantumCircuit] = []
381
+ self._prepended_entanglement: list[list[list[int]] | str] = []
382
+ self._appended_blocks: list[QuantumCircuit] = []
383
+ self._appended_entanglement: list[list[list[int]] | str] = []
384
+ self._entanglement = None
385
+ self._entangler_maps = None
386
+ self._ordered_parameters: ParameterVector | list[Parameter] = ParameterVector(
387
+ name=parameter_prefix
388
+ )
389
+ self._overwrite_block_parameters = overwrite_block_parameters
390
+ self._skip_final_rotation_layer = skip_final_rotation_layer
391
+ self._skip_unentangled_qubits = skip_unentangled_qubits
392
+ self._initial_state: QuantumCircuit | None = None
393
+ self._initial_state_circuit: QuantumCircuit | None = None
394
+ self._bounds: list[tuple[float | None, float | None]] | None = None
395
+ self._flatten = flatten
396
+
397
+ # During the build, if a subclass hasn't overridden our parametrization methods, we can use
398
+ # a newer fast-path method to parametrise the rotation and entanglement blocks if internally
399
+ # those are just simple stdlib gates that have been promoted to circuits. We don't
400
+ # precalculate the fast-path layers themselves because there's far too much that can be
401
+ # overridden between object construction and build, and far too many subclasses of `NLocal`
402
+ # that override bits and bobs of the internal private methods, so it'd be too hard to keep
403
+ # everything in sync.
404
+ self._allow_fast_path_parametrization = (
405
+ getattr(self._parameter_generator, "__func__", None) is NLocal._parameter_generator
406
+ )
407
+
408
+ if int(reps) != reps:
409
+ raise TypeError("The value of reps should be int")
410
+
411
+ if reps < 0:
412
+ raise ValueError("The value of reps should be larger than or equal to 0")
413
+
414
+ if num_qubits is not None:
415
+ self.num_qubits = num_qubits
416
+
417
+ if entanglement_blocks is not None:
418
+ self.entanglement_blocks = entanglement_blocks
419
+
420
+ if rotation_blocks is not None:
421
+ self.rotation_blocks = rotation_blocks
422
+
423
+ if entanglement is not None:
424
+ self.entanglement = entanglement
425
+
426
+ if initial_state is not None:
427
+ self.initial_state = initial_state
428
+
429
+ @property
430
+ def num_qubits(self) -> int:
431
+ """Returns the number of qubits in this circuit.
432
+
433
+ Returns:
434
+ The number of qubits.
435
+ """
436
+ return self._num_qubits if self._num_qubits is not None else 0
437
+
438
+ @num_qubits.setter
439
+ def num_qubits(self, num_qubits: int) -> None:
440
+ """Set the number of qubits for the n-local circuit.
441
+
442
+ Args:
443
+ The new number of qubits.
444
+ """
445
+ if self._num_qubits != num_qubits:
446
+ # invalidate the circuit
447
+ self._invalidate()
448
+ self._num_qubits = num_qubits
449
+ self.qregs = [QuantumRegister(num_qubits, name="q")]
450
+
451
+ @property
452
+ def flatten(self) -> bool:
453
+ """Returns whether the circuit is wrapped in nested gates/instructions or flattened."""
454
+ return bool(self._flatten)
455
+
456
+ @flatten.setter
457
+ def flatten(self, flatten: bool) -> None:
458
+ self._invalidate()
459
+ self._flatten = flatten
460
+
461
+ def _convert_to_block(self, layer: typing.Any) -> QuantumCircuit:
462
+ """Try to convert ``layer`` to a QuantumCircuit.
463
+
464
+ Args:
465
+ layer: The object to be converted to an NLocal block / Instruction.
466
+
467
+ Returns:
468
+ The layer converted to a circuit.
469
+
470
+ Raises:
471
+ TypeError: If the input cannot be converted to a circuit.
472
+ """
473
+ if isinstance(layer, QuantumCircuit):
474
+ return layer
475
+
476
+ if isinstance(layer, Instruction):
477
+ circuit = QuantumCircuit(layer.num_qubits)
478
+ circuit.append(layer, list(range(layer.num_qubits)))
479
+ return circuit
480
+
481
+ try:
482
+ circuit = QuantumCircuit(layer.num_qubits)
483
+ circuit.append(layer.to_instruction(), list(range(layer.num_qubits)))
484
+ return circuit
485
+ except AttributeError:
486
+ pass
487
+
488
+ raise TypeError(f"Adding a {type(layer)} to an NLocal is not supported.")
489
+
490
+ @property
491
+ def rotation_blocks(self) -> list[QuantumCircuit]:
492
+ """The blocks in the rotation layers.
493
+
494
+ Returns:
495
+ The blocks in the rotation layers.
496
+ """
497
+ return self._rotation_blocks
498
+
499
+ @rotation_blocks.setter
500
+ def rotation_blocks(
501
+ self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction]
502
+ ) -> None:
503
+ """Set the blocks in the rotation layers.
504
+
505
+ Args:
506
+ blocks: The new blocks for the rotation layers.
507
+ """
508
+ # cannot check for the attribute ``'__len__'`` because a circuit also has this attribute
509
+ if not isinstance(blocks, (list, numpy.ndarray)):
510
+ blocks = [blocks]
511
+
512
+ self._invalidate()
513
+ self._rotation_blocks = [self._convert_to_block(block) for block in blocks]
514
+
515
+ @property
516
+ def entanglement_blocks(self) -> list[QuantumCircuit]:
517
+ """The blocks in the entanglement layers.
518
+
519
+ Returns:
520
+ The blocks in the entanglement layers.
521
+ """
522
+ return self._entanglement_blocks
523
+
524
+ @entanglement_blocks.setter
525
+ def entanglement_blocks(
526
+ self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction]
527
+ ) -> None:
528
+ """Set the blocks in the entanglement layers.
529
+
530
+ Args:
531
+ blocks: The new blocks for the entanglement layers.
532
+ """
533
+ # cannot check for the attribute ``'__len__'`` because a circuit also has this attribute
534
+ if not isinstance(blocks, (list, numpy.ndarray)):
535
+ blocks = [blocks]
536
+
537
+ self._invalidate()
538
+ self._entanglement_blocks = [self._convert_to_block(block) for block in blocks]
539
+
540
+ @property
541
+ def entanglement(
542
+ self,
543
+ ) -> (
544
+ str
545
+ | list[str]
546
+ | list[list[str]]
547
+ | list[int]
548
+ | list[list[int]]
549
+ | list[list[list[int]]]
550
+ | list[list[list[list[int]]]]
551
+ | Callable[[int], str]
552
+ | Callable[[int], list[list[int]]]
553
+ ):
554
+ """Get the entanglement strategy.
555
+
556
+ Returns:
557
+ The entanglement strategy, see :meth:`get_entangler_map` for more detail on how the
558
+ format is interpreted.
559
+ """
560
+ return self._entanglement
561
+
562
+ @entanglement.setter
563
+ def entanglement(
564
+ self,
565
+ entanglement: (
566
+ str
567
+ | list[str]
568
+ | list[list[str]]
569
+ | list[int]
570
+ | list[list[int]]
571
+ | list[list[list[int]]]
572
+ | list[list[list[list[int]]]]
573
+ | Callable[[int], str]
574
+ | Callable[[int], list[list[int]]]
575
+ | None
576
+ ),
577
+ ) -> None:
578
+ """Set the entanglement strategy.
579
+
580
+ Args:
581
+ entanglement: The entanglement strategy. See :meth:`get_entangler_map` for more detail
582
+ on the supported formats.
583
+ """
584
+ self._invalidate()
585
+ self._entanglement = entanglement
586
+
587
+ @property
588
+ def num_layers(self) -> int:
589
+ """Return the number of layers in the n-local circuit.
590
+
591
+ Returns:
592
+ The number of layers in the circuit.
593
+ """
594
+ return 2 * self._reps + int(not self._skip_final_rotation_layer)
595
+
596
+ def _check_configuration(self, raise_on_failure: bool = True) -> bool:
597
+ """Check if the configuration of the NLocal class is valid.
598
+
599
+ Args:
600
+ raise_on_failure: Whether to raise on failure.
601
+
602
+ Returns:
603
+ True, if the configuration is valid and the circuit can be constructed. Otherwise
604
+ an ValueError is raised.
605
+
606
+ Raises:
607
+ ValueError: If the blocks are not set.
608
+ ValueError: If the number of repetitions is not set.
609
+ ValueError: If the qubit indices are not set.
610
+ ValueError: If the number of qubit indices does not match the number of blocks.
611
+ ValueError: If an index in the repetitions list exceeds the number of blocks.
612
+ ValueError: If the number of repetitions does not match the number of block-wise
613
+ parameters.
614
+ ValueError: If a specified qubit index is larger than the (manually set) number of
615
+ qubits.
616
+ """
617
+ valid = True
618
+ if self.num_qubits is None:
619
+ valid = False
620
+ if raise_on_failure:
621
+ raise ValueError("No number of qubits specified.")
622
+
623
+ # check no needed parameters are None
624
+ if self.entanglement_blocks is None and self.rotation_blocks is None:
625
+ valid = False
626
+ if raise_on_failure:
627
+ raise ValueError("The blocks are not set.")
628
+
629
+ return valid
630
+
631
+ @property
632
+ def ordered_parameters(self) -> list[Parameter]:
633
+ """The parameters used in the underlying circuit.
634
+
635
+ This includes float values and duplicates.
636
+
637
+ Examples:
638
+
639
+ >>> # prepare circuit ...
640
+ >>> print(nlocal)
641
+ ┌───────┐┌──────────┐┌──────────┐┌──────────┐
642
+ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├
643
+ └───────┘└──────────┘└──────────┘└──────────┘
644
+ >>> nlocal.parameters
645
+ {Parameter(θ[1]), Parameter(θ[3])}
646
+ >>> nlocal.ordered_parameters
647
+ [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])]
648
+
649
+ Returns:
650
+ The parameters objects used in the circuit.
651
+ """
652
+ if isinstance(self._ordered_parameters, ParameterVector):
653
+ self._ordered_parameters.resize(self.num_parameters_settable)
654
+ return list(self._ordered_parameters)
655
+
656
+ return self._ordered_parameters
657
+
658
+ @ordered_parameters.setter
659
+ def ordered_parameters(self, parameters: ParameterVector | list[Parameter]) -> None:
660
+ """Set the parameters used in the underlying circuit.
661
+
662
+ Args:
663
+ The parameters to be used in the underlying circuit.
664
+
665
+ Raises:
666
+ ValueError: If the length of ordered parameters does not match the number of
667
+ parameters in the circuit and they are not a ``ParameterVector`` (which could
668
+ be resized to fit the number of parameters).
669
+ """
670
+ if (
671
+ not isinstance(parameters, ParameterVector)
672
+ and len(parameters) != self.num_parameters_settable
673
+ ):
674
+ raise ValueError(
675
+ "The length of ordered parameters must be equal to the number of "
676
+ f"settable parameters in the circuit ({self.num_parameters_settable}),"
677
+ f" but is {len(parameters)}"
678
+ )
679
+ self._ordered_parameters = parameters
680
+ self._invalidate()
681
+
682
+ @property
683
+ def insert_barriers(self) -> bool:
684
+ """If barriers are inserted in between the layers or not.
685
+
686
+ Returns:
687
+ ``True``, if barriers are inserted in between the layers, ``False`` if not.
688
+ """
689
+ return self._insert_barriers
690
+
691
+ @insert_barriers.setter
692
+ def insert_barriers(self, insert_barriers: bool) -> None:
693
+ """Specify whether barriers should be inserted in between the layers or not.
694
+
695
+ Args:
696
+ insert_barriers: If True, barriers are inserted, if False not.
697
+ """
698
+ # if insert_barriers changes, we have to invalidate the circuit definition,
699
+ # if it is the same as before we can leave the NLocal instance as it is
700
+ if insert_barriers is not self._insert_barriers:
701
+ self._invalidate()
702
+ self._insert_barriers = insert_barriers
703
+
704
+ def get_unentangled_qubits(self) -> set[int]:
705
+ """Get the indices of unentangled qubits in a set.
706
+
707
+ Returns:
708
+ The unentangled qubits.
709
+ """
710
+ entangled_qubits = set()
711
+ for i in range(self._reps):
712
+ for j, block in enumerate(self.entanglement_blocks):
713
+ entangler_map = self.get_entangler_map(i, j, block.num_qubits)
714
+ entangled_qubits.update([idx for indices in entangler_map for idx in indices])
715
+ unentangled_qubits = set(range(self.num_qubits)) - entangled_qubits
716
+
717
+ return unentangled_qubits
718
+
719
+ @property
720
+ def num_parameters_settable(self) -> int:
721
+ """The number of total parameters that can be set to distinct values.
722
+
723
+ This does not change when the parameters are bound or exchanged for same parameters,
724
+ and therefore is different from ``num_parameters`` which counts the number of unique
725
+ :class:`~qiskit.circuit.Parameter` objects currently in the circuit.
726
+
727
+ Returns:
728
+ The number of parameters originally available in the circuit.
729
+
730
+ Note:
731
+ This quantity does not require the circuit to be built yet.
732
+ """
733
+ num = 0
734
+
735
+ for i in range(self._reps):
736
+ for j, block in enumerate(self.entanglement_blocks):
737
+ entangler_map = self.get_entangler_map(i, j, block.num_qubits)
738
+ num += len(entangler_map) * len(get_parameters(block))
739
+
740
+ if self._skip_unentangled_qubits:
741
+ unentangled_qubits = self.get_unentangled_qubits()
742
+
743
+ num_rot = 0
744
+ for block in self.rotation_blocks:
745
+ block_indices = [
746
+ list(range(j * block.num_qubits, (j + 1) * block.num_qubits))
747
+ for j in range(self.num_qubits // block.num_qubits)
748
+ ]
749
+ if self._skip_unentangled_qubits:
750
+ block_indices = [
751
+ indices
752
+ for indices in block_indices
753
+ if set(indices).isdisjoint(unentangled_qubits)
754
+ ]
755
+ num_rot += len(block_indices) * len(get_parameters(block))
756
+
757
+ num += num_rot * (self._reps + int(not self._skip_final_rotation_layer))
758
+
759
+ return num
760
+
761
+ @property
762
+ def reps(self) -> int:
763
+ """The number of times rotation and entanglement block are repeated.
764
+
765
+ Returns:
766
+ The number of repetitions.
767
+ """
768
+ return self._reps
769
+
770
+ @reps.setter
771
+ def reps(self, repetitions: int) -> None:
772
+ """Set the repetitions.
773
+
774
+ If the repetitions are `0`, only one rotation layer with no entanglement
775
+ layers is applied (unless ``self.skip_final_rotation_layer`` is set to ``True``).
776
+
777
+ Args:
778
+ repetitions: The new repetitions.
779
+
780
+ Raises:
781
+ ValueError: If reps setter has parameter repetitions < 0.
782
+ """
783
+ if repetitions < 0:
784
+ raise ValueError("The repetitions should be larger than or equal to 0")
785
+ if repetitions != self._reps:
786
+ self._invalidate()
787
+ self._reps = repetitions
788
+
789
+ def print_settings(self) -> str:
790
+ """Returns information about the setting.
791
+
792
+ Returns:
793
+ The class name and the attributes/parameters of the instance as ``str``.
794
+ """
795
+ ret = f"NLocal: {self.__class__.__name__}\n"
796
+ params = ""
797
+ for key, value in self.__dict__.items():
798
+ if key[0] == "_":
799
+ params += f"-- {key[1:]}: {value}\n"
800
+ ret += f"{params}"
801
+ return ret
802
+
803
+ @property
804
+ def preferred_init_points(self) -> list[float] | None:
805
+ """The initial points for the parameters. Can be stored as initial guess in optimization.
806
+
807
+ Returns:
808
+ The initial values for the parameters, or None, if none have been set.
809
+ """
810
+ return None
811
+
812
+ # pylint: disable=too-many-return-statements
813
+ def get_entangler_map(
814
+ self, rep_num: int, block_num: int, num_block_qubits: int
815
+ ) -> Sequence[Sequence[int]]:
816
+ """Get the entangler map for in the repetition ``rep_num`` and the block ``block_num``.
817
+
818
+ The entangler map for the current block is derived from the value of ``self.entanglement``.
819
+ Below the different cases are listed, where ``i`` and ``j`` denote the repetition number
820
+ and the block number, respectively, and ``n`` the number of qubits in the block.
821
+
822
+ =================================== ========================================================
823
+ entanglement type entangler map
824
+ =================================== ========================================================
825
+ ``None`` ``[[0, ..., n - 1]]``
826
+ ``str`` (e.g ``'full'``) the specified connectivity on ``n`` qubits
827
+ ``List[int]`` [``entanglement``]
828
+ ``List[List[int]]`` ``entanglement``
829
+ ``List[List[List[int]]]`` ``entanglement[i]``
830
+ ``List[List[List[List[int]]]]`` ``entanglement[i][j]``
831
+ ``List[str]`` the connectivity specified in ``entanglement[i]``
832
+ ``List[List[str]]`` the connectivity specified in ``entanglement[i][j]``
833
+ ``Callable[int, str]`` same as ``List[str]``
834
+ ``Callable[int, List[List[int]]]`` same as ``List[List[List[int]]]``
835
+ =================================== ========================================================
836
+
837
+
838
+ Note that all indices are to be taken modulo the length of the array they act on, i.e.
839
+ no out-of-bounds index error will be raised but we re-iterate from the beginning of the
840
+ list.
841
+
842
+ Args:
843
+ rep_num: The current repetition we are in.
844
+ block_num: The block number within the entanglement layers.
845
+ num_block_qubits: The number of qubits in the block.
846
+
847
+ Returns:
848
+ The entangler map for the current block in the current repetition.
849
+
850
+ Raises:
851
+ ValueError: If the value of ``entanglement`` could not be cast to a corresponding
852
+ entangler map.
853
+ """
854
+ i, j, n = rep_num, block_num, num_block_qubits
855
+ entanglement = self._entanglement
856
+
857
+ # entanglement is None
858
+ if entanglement is None:
859
+ return [list(range(n))]
860
+
861
+ # entanglement is callable
862
+ if callable(entanglement):
863
+ entanglement = entanglement(i)
864
+
865
+ # entanglement is str
866
+ if isinstance(entanglement, str):
867
+ return get_entangler_map(n, self.num_qubits, entanglement, offset=i)
868
+
869
+ # check if entanglement is list of something
870
+ if not isinstance(entanglement, (tuple, list)):
871
+ raise ValueError(f"Invalid value of entanglement: {entanglement}")
872
+ num_i = len(entanglement)
873
+
874
+ # entanglement is List[str]
875
+ if all(isinstance(en, str) for en in entanglement):
876
+ return get_entangler_map(n, self.num_qubits, entanglement[i % num_i], offset=i)
877
+
878
+ # entanglement is List[int]
879
+ if all(isinstance(en, (int, numpy.integer)) for en in entanglement):
880
+ return [[int(en) for en in entanglement]]
881
+
882
+ # check if entanglement is List[List]
883
+ if not all(isinstance(en, (tuple, list)) for en in entanglement):
884
+ raise ValueError(f"Invalid value of entanglement: {entanglement}")
885
+ num_j = len(entanglement[i % num_i])
886
+
887
+ # entanglement is List[List[str]]
888
+ if all(isinstance(e2, str) for en in entanglement for e2 in en):
889
+ return get_entangler_map(
890
+ n, self.num_qubits, entanglement[i % num_i][j % num_j], offset=i
891
+ )
892
+
893
+ # entanglement is List[List[int]]
894
+ if all(isinstance(e2, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en):
895
+ for ind, en in enumerate(entanglement):
896
+ entanglement[ind] = tuple(map(int, en))
897
+ return entanglement
898
+
899
+ # check if entanglement is List[List[List]]
900
+ if not all(isinstance(e2, (tuple, list)) for en in entanglement for e2 in en):
901
+ raise ValueError(f"Invalid value of entanglement: {entanglement}")
902
+
903
+ # entanglement is List[List[List[int]]]
904
+ if all(
905
+ isinstance(e3, (int, numpy.int32, numpy.int64))
906
+ for en in entanglement
907
+ for e2 in en
908
+ for e3 in e2
909
+ ):
910
+ for en in entanglement:
911
+ for ind, e2 in enumerate(en):
912
+ en[ind] = tuple(map(int, e2))
913
+ return entanglement[i % num_i]
914
+
915
+ # check if entanglement is List[List[List[List]]]
916
+ if not all(isinstance(e3, (tuple, list)) for en in entanglement for e2 in en for e3 in e2):
917
+ raise ValueError(f"Invalid value of entanglement: {entanglement}")
918
+
919
+ # entanglement is List[List[List[List[int]]]]
920
+ if all(
921
+ isinstance(e4, (int, numpy.int32, numpy.int64))
922
+ for en in entanglement
923
+ for e2 in en
924
+ for e3 in e2
925
+ for e4 in e3
926
+ ):
927
+ for en in entanglement:
928
+ for e2 in en:
929
+ for ind, e3 in enumerate(e2):
930
+ e2[ind] = tuple(map(int, e3))
931
+ return entanglement[i % num_i][j % num_j]
932
+
933
+ raise ValueError(f"Invalid value of entanglement: {entanglement}")
934
+
935
+ @property
936
+ def initial_state(self) -> QuantumCircuit:
937
+ """Return the initial state that is added in front of the n-local circuit.
938
+
939
+ Returns:
940
+ The initial state.
941
+ """
942
+ return self._initial_state
943
+
944
+ @initial_state.setter
945
+ def initial_state(self, initial_state: QuantumCircuit) -> None:
946
+ """Set the initial state.
947
+
948
+ Args:
949
+ initial_state: The new initial state.
950
+
951
+ Raises:
952
+ ValueError: If the number of qubits has been set before and the initial state
953
+ does not match the number of qubits.
954
+ """
955
+ self._initial_state = initial_state
956
+ self._invalidate()
957
+
958
+ @property
959
+ def parameter_bounds(self) -> list[tuple[float, float]] | None:
960
+ """The parameter bounds for the unbound parameters in the circuit.
961
+
962
+ Returns:
963
+ A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded
964
+ parameter in the corresponding direction. If ``None`` is returned, problem is fully
965
+ unbounded.
966
+ """
967
+ if not self._is_built:
968
+ self._build()
969
+ return self._bounds
970
+
971
+ @parameter_bounds.setter
972
+ def parameter_bounds(self, bounds: list[tuple[float, float]]) -> None:
973
+ """Set the parameter bounds.
974
+
975
+ Args:
976
+ bounds: The new parameter bounds.
977
+ """
978
+ self._bounds = bounds
979
+
980
+ def add_layer(
981
+ self,
982
+ other: QuantumCircuit | qiskit.circuit.Instruction,
983
+ entanglement: list[int] | str | list[list[int]] | None = None,
984
+ front: bool = False,
985
+ ) -> "NLocal":
986
+ """Append another layer to the NLocal.
987
+
988
+ Args:
989
+ other: The layer to compose, can be another NLocal, an Instruction or Gate,
990
+ or a QuantumCircuit.
991
+ entanglement: The entanglement or qubit indices.
992
+ front: If True, ``other`` is appended to the front, else to the back.
993
+
994
+ Returns:
995
+ self, such that chained composes are possible.
996
+
997
+ Raises:
998
+ TypeError: If `other` is not compatible, i.e. is no Instruction and does not have a
999
+ `to_instruction` method.
1000
+ """
1001
+ block = self._convert_to_block(other)
1002
+
1003
+ if entanglement is None:
1004
+ entanglement = [list(range(block.num_qubits))]
1005
+ elif isinstance(entanglement, list) and not isinstance(entanglement[0], list):
1006
+ entanglement = [entanglement]
1007
+ if front:
1008
+ self._prepended_blocks += [block]
1009
+ self._prepended_entanglement += [entanglement]
1010
+ else:
1011
+ self._appended_blocks += [block]
1012
+ self._appended_entanglement += [entanglement]
1013
+
1014
+ if isinstance(entanglement, list):
1015
+ num_qubits = 1 + max(max(indices) for indices in entanglement)
1016
+ if num_qubits > self.num_qubits:
1017
+ self._invalidate() # rebuild circuit
1018
+ self.num_qubits = num_qubits
1019
+
1020
+ # modify the circuit accordingly
1021
+ if front is False and self._is_built:
1022
+ if self._insert_barriers and len(self.data) > 0:
1023
+ self.barrier()
1024
+
1025
+ if isinstance(entanglement, str):
1026
+ entangler_map: Sequence[Sequence[int]] = get_entangler_map(
1027
+ block.num_qubits, self.num_qubits, entanglement
1028
+ )
1029
+ else:
1030
+ entangler_map = entanglement
1031
+
1032
+ for i in entangler_map:
1033
+ params = self.ordered_parameters[-len(get_parameters(block)) :]
1034
+ parameterized_block = self._parameterize_block(block, params=params)
1035
+ self.compose(parameterized_block, i, inplace=True, copy=False)
1036
+ else:
1037
+ # cannot prepend a block currently, just rebuild
1038
+ self._invalidate()
1039
+
1040
+ return self
1041
+
1042
+ def assign_parameters(
1043
+ self,
1044
+ parameters: (
1045
+ Mapping[Parameter, ParameterExpression | float] | Sequence[ParameterExpression | float]
1046
+ ),
1047
+ inplace: bool = False,
1048
+ **kwargs,
1049
+ ) -> QuantumCircuit | None:
1050
+ """Assign parameters to the n-local circuit.
1051
+
1052
+ This method also supports passing a list instead of a dictionary. If a list
1053
+ is passed, the list must have the same length as the number of unbound parameters in
1054
+ the circuit. The parameters are assigned in the order of the parameters in
1055
+ :meth:`ordered_parameters`.
1056
+
1057
+ Returns:
1058
+ A copy of the NLocal circuit with the specified parameters.
1059
+
1060
+ Raises:
1061
+ AttributeError: If the parameters are given as list and do not match the number
1062
+ of parameters.
1063
+ """
1064
+ if parameters is None or len(parameters) == 0:
1065
+ return self
1066
+
1067
+ if not self._is_built:
1068
+ self._build()
1069
+
1070
+ return super().assign_parameters(parameters, inplace=inplace, **kwargs)
1071
+
1072
+ def _parameterize_block(
1073
+ self, block, param_iter=None, rep_num=None, block_num=None, indices=None, params=None
1074
+ ):
1075
+ """Convert ``block`` to a circuit of correct width and parameterized using the iterator."""
1076
+ if self._overwrite_block_parameters:
1077
+ # check if special parameters should be used
1078
+ # pylint: disable=assignment-from-none
1079
+ if params is None:
1080
+ params = self._parameter_generator(rep_num, block_num, indices)
1081
+ if params is None:
1082
+ params = [next(param_iter) for _ in range(len(get_parameters(block)))]
1083
+
1084
+ update = dict(zip(block.parameters, params))
1085
+ return block.assign_parameters(update)
1086
+
1087
+ return block.copy()
1088
+
1089
+ def _build_rotation_layer(self, circuit, param_iter, i):
1090
+ """Build a rotation layer."""
1091
+ # if the unentangled qubits are skipped, compute the set of qubits that are not entangled
1092
+ if self._skip_unentangled_qubits:
1093
+ skipped_qubits = self.get_unentangled_qubits()
1094
+ else:
1095
+ skipped_qubits = set()
1096
+
1097
+ target_qubits = circuit.qubits
1098
+
1099
+ # iterate over all rotation blocks
1100
+ for j, block in enumerate(self.rotation_blocks):
1101
+ skipped_blocks = {qubit // block.num_qubits for qubit in skipped_qubits}
1102
+ if (
1103
+ self._allow_fast_path_parametrization
1104
+ and (simple_block := _stdlib_gate_from_simple_block(block)) is not None
1105
+ ):
1106
+ all_qubits = (
1107
+ tuple(target_qubits[k * block.num_qubits : (k + 1) * block.num_qubits])
1108
+ for k in range(self.num_qubits // block.num_qubits)
1109
+ if k not in skipped_blocks
1110
+ )
1111
+ for qubits in all_qubits:
1112
+ instr = CircuitInstruction(
1113
+ simple_block.gate(*itertools.islice(param_iter, simple_block.num_params)),
1114
+ qubits,
1115
+ )
1116
+ circuit._append(instr)
1117
+ else:
1118
+ block_indices = [
1119
+ list(range(k * block.num_qubits, (k + 1) * block.num_qubits))
1120
+ for k in range(self.num_qubits // block.num_qubits)
1121
+ if k not in skipped_blocks
1122
+ ]
1123
+ # apply the operations in the layer
1124
+ for indices in block_indices:
1125
+ parameterized_block = self._parameterize_block(block, param_iter, i, j, indices)
1126
+ circuit.compose(parameterized_block, indices, inplace=True, copy=False)
1127
+
1128
+ def _build_entanglement_layer(self, circuit, param_iter, i):
1129
+ """Build an entanglement layer."""
1130
+ # iterate over all entanglement blocks
1131
+ target_qubits = circuit.qubits
1132
+ for j, block in enumerate(self.entanglement_blocks):
1133
+ entangler_map = self.get_entangler_map(i, j, block.num_qubits)
1134
+ if (
1135
+ self._allow_fast_path_parametrization
1136
+ and (simple_block := _stdlib_gate_from_simple_block(block)) is not None
1137
+ ):
1138
+ for indices in entangler_map:
1139
+ # It's actually nontrivially faster to use a listcomp and pass that to `tuple`
1140
+ # than to pass a generator expression directly.
1141
+ # pylint: disable=consider-using-generator
1142
+ instr = CircuitInstruction(
1143
+ simple_block.gate(*itertools.islice(param_iter, simple_block.num_params)),
1144
+ tuple([target_qubits[i] for i in indices]),
1145
+ )
1146
+ circuit._append(instr)
1147
+ else:
1148
+ # apply the operations in the layer
1149
+ for indices in entangler_map:
1150
+ parameterized_block = self._parameterize_block(block, param_iter, i, j, indices)
1151
+ circuit.compose(parameterized_block, indices, inplace=True, copy=False)
1152
+
1153
+ def _build_additional_layers(self, circuit, which):
1154
+ if which == "appended":
1155
+ blocks = self._appended_blocks
1156
+ entanglements = self._appended_entanglement
1157
+ elif which == "prepended":
1158
+ blocks = reversed(self._prepended_blocks)
1159
+ entanglements = reversed(self._prepended_entanglement)
1160
+ else:
1161
+ raise ValueError("`which` must be either `appended` or `prepended`.")
1162
+
1163
+ for block, ent in zip(blocks, entanglements):
1164
+ if isinstance(ent, str):
1165
+ ent = get_entangler_map(block.num_qubits, self.num_qubits, ent)
1166
+ for indices in ent:
1167
+ circuit.compose(block, indices, inplace=True, copy=False)
1168
+
1169
+ def _build(self) -> None:
1170
+ """If not already built, build the circuit."""
1171
+ if self._is_built:
1172
+ return
1173
+
1174
+ super()._build()
1175
+
1176
+ if self.num_qubits == 0:
1177
+ return
1178
+
1179
+ if not self._flatten:
1180
+ circuit = QuantumCircuit(*self.qregs, name=self.name)
1181
+ else:
1182
+ circuit = self
1183
+
1184
+ # use the initial state as starting circuit, if it is set
1185
+ if self.initial_state:
1186
+ circuit.compose(self.initial_state.copy(), inplace=True, copy=False)
1187
+
1188
+ param_iter = iter(self.ordered_parameters)
1189
+
1190
+ # build the prepended layers
1191
+ self._build_additional_layers(circuit, "prepended")
1192
+
1193
+ # main loop to build the entanglement and rotation layers
1194
+ for i in range(self.reps):
1195
+ # insert barrier if specified and there is a preceding layer
1196
+ if self._insert_barriers and (i > 0 or len(self._prepended_blocks) > 0):
1197
+ circuit.barrier()
1198
+
1199
+ # build the rotation layer
1200
+ self._build_rotation_layer(circuit, param_iter, i)
1201
+
1202
+ # barrier in between rotation and entanglement layer
1203
+ if self._insert_barriers and len(self._rotation_blocks) > 0:
1204
+ circuit.barrier()
1205
+
1206
+ # build the entanglement layer
1207
+ self._build_entanglement_layer(circuit, param_iter, i)
1208
+
1209
+ # add the final rotation layer
1210
+ if not self._skip_final_rotation_layer:
1211
+ if self.insert_barriers and self.reps > 0:
1212
+ circuit.barrier()
1213
+ self._build_rotation_layer(circuit, param_iter, self.reps)
1214
+
1215
+ # add the appended layers
1216
+ self._build_additional_layers(circuit, "appended")
1217
+
1218
+ # cast global phase to float if it has no free parameters
1219
+ if isinstance(circuit.global_phase, ParameterExpression):
1220
+ try:
1221
+ circuit.global_phase = float(circuit.global_phase)
1222
+ except TypeError:
1223
+ # expression contains free parameters
1224
+ pass
1225
+
1226
+ if not self._flatten:
1227
+ try:
1228
+ block = circuit.to_gate()
1229
+ except QiskitError:
1230
+ block = circuit.to_instruction()
1231
+
1232
+ self.append(block, self.qubits, copy=False)
1233
+
1234
+ # pylint: disable=unused-argument
1235
+ def _parameter_generator(self, rep: int, block: int, indices: list[int]) -> Parameter | None:
1236
+ """If certain blocks should use certain parameters this method can be overridden."""
1237
+ return None
1238
+
1239
+
1240
+ def get_parameters(block: QuantumCircuit | Instruction) -> list[Parameter]:
1241
+ """Return the list of Parameters objects inside a circuit or instruction.
1242
+
1243
+ This is required since, in a standard gate the parameters are not necessarily Parameter
1244
+ objects (e.g. U3Gate(0.1, 0.2, 0.3).params == [0.1, 0.2, 0.3]) and instructions and
1245
+ circuits do not have the same interface for parameters.
1246
+ """
1247
+ if isinstance(block, QuantumCircuit):
1248
+ return list(block.parameters)
1249
+ else:
1250
+ return [p for p in block.params if isinstance(p, ParameterExpression)]
1251
+
1252
+
1253
+ def get_entangler_map(
1254
+ num_block_qubits: int, num_circuit_qubits: int, entanglement: str, offset: int = 0
1255
+ ) -> Sequence[tuple[int, ...]]:
1256
+ """Get an entangler map for an arbitrary number of qubits.
1257
+
1258
+ Args:
1259
+ num_block_qubits: The number of qubits of the entangling block.
1260
+ num_circuit_qubits: The number of qubits of the circuit.
1261
+ entanglement: The entanglement strategy.
1262
+ offset: The block offset, can be used if the entanglements differ per block.
1263
+ See mode ``sca`` for instance.
1264
+
1265
+ Returns:
1266
+ The entangler map using mode ``entanglement`` to scatter a block of ``num_block_qubits``
1267
+ qubits on ``num_circuit_qubits`` qubits.
1268
+
1269
+ Raises:
1270
+ ValueError: If the entanglement mode ist not supported.
1271
+ """
1272
+ try:
1273
+ return fast_entangler_map(num_circuit_qubits, num_block_qubits, entanglement, offset)
1274
+ except Exception as exc:
1275
+ # need this as Rust is now raising a QiskitError, where this function was raising ValueError
1276
+ raise ValueError("Something went wrong in Rust space, here's the error:") from exc
1277
+
1278
+
1279
+ _StdlibGateResult = collections.namedtuple("_StdlibGateResult", ("gate", "num_params"))
1280
+ _STANDARD_GATE_MAPPING = get_standard_gate_name_mapping()
1281
+
1282
+
1283
+ def _stdlib_gate_from_simple_block(block: QuantumCircuit) -> _StdlibGateResult | None:
1284
+ if block.global_phase != 0.0 or len(block) != 1:
1285
+ return None
1286
+ instruction = block.data[0]
1287
+ # If the single instruction isn't a standard-library gate that spans the full width of the block
1288
+ # in the correct order, we're not simple. If the gate isn't fully parametrized with pure,
1289
+ # unique `Parameter` instances (expressions are too complex) that are in order, we're not
1290
+ # simple.
1291
+ if (
1292
+ instruction.clbits
1293
+ or tuple(instruction.qubits) != tuple(block.qubits)
1294
+ or (
1295
+ getattr(_STANDARD_GATE_MAPPING.get(instruction.operation.name), "base_class", None)
1296
+ is not instruction.operation.base_class
1297
+ )
1298
+ or tuple(instruction.operation.params) != tuple(block.parameters)
1299
+ ):
1300
+ return None
1301
+ return _StdlibGateResult(instruction.operation.base_class, len(instruction.operation.params))
1302
+
1303
+
1304
+ def _normalize_entanglement(
1305
+ entanglement: (
1306
+ BlockEntanglement
1307
+ | Iterable[BlockEntanglement]
1308
+ | Callable[[int], BlockEntanglement | Iterable[BlockEntanglement]]
1309
+ ),
1310
+ num_entanglement_blocks: int,
1311
+ ) -> list[str | list[tuple[int]]] | Callable[[int], list[str | list[tuple[int]]]]:
1312
+ """If the entanglement is Iterable[Iterable], normalize to list[tuple]."""
1313
+ if isinstance(entanglement, str):
1314
+ return [entanglement] * num_entanglement_blocks
1315
+
1316
+ if callable(entanglement):
1317
+ return lambda offset: _normalize_entanglement(entanglement(offset), num_entanglement_blocks)
1318
+
1319
+ # here, entanglement is an Iterable
1320
+ if len(entanglement) == 0:
1321
+ # handle edge cases when entanglement is set to an empty list
1322
+ return [[]]
1323
+
1324
+ # if the entanglement is Iterable[Iterable[int]], normalize to Iterable[Iterable[Iterable[int]]]
1325
+ try:
1326
+ # if users e.g. gave Iterable[int] this in invalid and will raise a TypeError
1327
+ if isinstance(entanglement[0][0], (int, numpy.integer)):
1328
+ entanglement = [entanglement]
1329
+ except TypeError as exc:
1330
+ raise TypeError(f"Invalid entanglement type: {entanglement}.") from exc
1331
+
1332
+ # ensure the number of block entanglements matches the number of blocks
1333
+ if len(entanglement) != num_entanglement_blocks:
1334
+ raise QiskitError(
1335
+ f"Number of block-entanglements ({len(entanglement)}) must match number of "
1336
+ f"entanglement blocks ({num_entanglement_blocks})!"
1337
+ )
1338
+
1339
+ # normalize the data: str remains, and Iterable[Iterable[int]] becomes list[tuple[int]]
1340
+ normalized = []
1341
+ for block in entanglement:
1342
+ if isinstance(block, str):
1343
+ normalized.append(block)
1344
+ else:
1345
+ normalized.append([tuple(connections) for connections in block])
1346
+
1347
+ return normalized
1348
+
1349
+
1350
+ def _normalize_blocks(
1351
+ blocks: str | Gate | Iterable[str | Gate],
1352
+ supported_gates: dict[str, Gate],
1353
+ overwrite_block_parameters: bool,
1354
+ ) -> list[Block]:
1355
+ # normalize the input into an iterable -- we add an extra check for a circuit as
1356
+ # courtesy to the users, since the NLocal class used to accept circuits
1357
+ if isinstance(blocks, (str, Gate, QuantumCircuit)):
1358
+ blocks = [blocks]
1359
+
1360
+ normalized = []
1361
+ for block in blocks:
1362
+ # since the NLocal circuit accepted circuits as inputs, we raise a warning here
1363
+ # to simplify the transition (even though, strictly speaking, quantum circuits are
1364
+ # not a supported input type)
1365
+ if isinstance(block, QuantumCircuit):
1366
+ raise ValueError(
1367
+ "The blocks should be of type Gate or str, but you passed a QuantumCircuit. "
1368
+ "You can call .to_gate() on the circuit to turn it into a Gate object."
1369
+ )
1370
+
1371
+ is_standard = False
1372
+ if isinstance(block, str):
1373
+ if block not in supported_gates:
1374
+ raise ValueError(f"Unsupported gate: {block}")
1375
+ block = supported_gates[block]
1376
+ is_standard = True
1377
+ elif isinstance(block, Gate) and getattr(block, "_standard_gate", None) is not None:
1378
+ if len(block.params) == 0:
1379
+ is_standard = True
1380
+ # the fast path will always overwrite block parameters
1381
+ elif overwrite_block_parameters:
1382
+ # if all parameters are plain Parameter objects, this is a plain
1383
+ # standard gate we do not need to propagate parameterizations for
1384
+ is_standard = all(isinstance(p, Parameter) for p in block.params)
1385
+
1386
+ if is_standard:
1387
+ block = Block.from_standard_gate(block._standard_gate)
1388
+ else:
1389
+ if overwrite_block_parameters:
1390
+ num_parameters, builder = _get_gate_builder(block)
1391
+ else:
1392
+ num_parameters, builder = _trivial_builder(block)
1393
+
1394
+ block = Block.from_callable(block.num_qubits, num_parameters, builder)
1395
+
1396
+ normalized.append(block)
1397
+
1398
+ return normalized
1399
+
1400
+
1401
+ def _trivial_builder(
1402
+ gate: Gate,
1403
+ ) -> tuple[int, Callable[list[Parameter], tuple[Gate, list[ParameterValueType]]]]:
1404
+
1405
+ def builder(_):
1406
+ copied = gate.copy()
1407
+ return copied, copied.params
1408
+
1409
+ return 0, builder
1410
+
1411
+
1412
+ def _get_gate_builder(
1413
+ gate: Gate,
1414
+ ) -> tuple[int, Callable[list[Parameter], tuple[Gate, list[ParameterValueType]]]]:
1415
+ """Construct a callable that handles parameter-rebinding.
1416
+
1417
+ For a given gate, this return the number of free parameters and a callable that can be
1418
+ used to obtain a re-parameterized version of the gate. For example::
1419
+
1420
+ x, y = Parameter("x"), Parameter("y")
1421
+ gate = CUGate(x, 2 * y, 0.5, 0.)
1422
+
1423
+ num_parameters, builder = _build_gate(gate)
1424
+ print(num_parameters) # prints 2
1425
+
1426
+ a, b = Parameter("a"), Parameter("b")
1427
+ new_gate, new_params = builder([a, b])
1428
+ print(new_gate) # CUGate(a, 2 * b, 0.5, 0)
1429
+ print(new_params) # [a, 2 * b, 0.5, 0]
1430
+
1431
+ """
1432
+ free_parameters = set()
1433
+ for p in gate.params:
1434
+ if isinstance(p, ParameterExpression):
1435
+ free_parameters |= set(p.parameters)
1436
+
1437
+ num_parameters = len(free_parameters)
1438
+
1439
+ sorted_parameters = _sort_parameters(free_parameters)
1440
+
1441
+ def builder(new_parameters):
1442
+ out = gate.copy()
1443
+
1444
+ # re-bind the ``Gate.params`` attribute
1445
+ param_dict = dict(zip(sorted_parameters, new_parameters))
1446
+ bound_params = gate.params.copy()
1447
+ for i, expr in enumerate(gate.params):
1448
+ if isinstance(expr, ParameterExpression):
1449
+ for parameter in expr.parameters:
1450
+ expr = expr.assign(parameter, param_dict[parameter])
1451
+ bound_params[i] = expr
1452
+
1453
+ out.params = bound_params
1454
+
1455
+ # if the definition exists, rebind it
1456
+ if out._definition is not None:
1457
+ out._definition.assign_parameters(param_dict, inplace=True)
1458
+
1459
+ return out, bound_params
1460
+
1461
+ return num_parameters, builder
1462
+
1463
+
1464
+ def _sort_parameters(parameters):
1465
+ """Sort a list of Parameter objects."""
1466
+
1467
+ def key(parameter):
1468
+ if isinstance(parameter, ParameterVectorElement):
1469
+ return (parameter.vector.name, parameter.index)
1470
+ return (parameter.name,)
1471
+
1472
+ return sorted(parameters, key=key)