qiskit 2.1.0rc1__cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (699) hide show
  1. qiskit/VERSION.txt +1 -0
  2. qiskit/__init__.py +159 -0
  3. qiskit/_accelerate.abi3.so +0 -0
  4. qiskit/_numpy_compat.py +73 -0
  5. qiskit/circuit/__init__.py +1335 -0
  6. qiskit/circuit/_add_control.py +338 -0
  7. qiskit/circuit/_classical_resource_map.py +154 -0
  8. qiskit/circuit/_standard_gates_commutations.py +3849 -0
  9. qiskit/circuit/_utils.py +167 -0
  10. qiskit/circuit/annotated_operation.py +279 -0
  11. qiskit/circuit/annotation.py +404 -0
  12. qiskit/circuit/barrier.py +46 -0
  13. qiskit/circuit/classical/__init__.py +41 -0
  14. qiskit/circuit/classical/expr/__init__.py +266 -0
  15. qiskit/circuit/classical/expr/constructors.py +764 -0
  16. qiskit/circuit/classical/expr/expr.py +156 -0
  17. qiskit/circuit/classical/expr/visitors.py +381 -0
  18. qiskit/circuit/classical/types/__init__.py +113 -0
  19. qiskit/circuit/classical/types/ordering.py +229 -0
  20. qiskit/circuit/classical/types/types.py +30 -0
  21. qiskit/circuit/commutation_checker.py +133 -0
  22. qiskit/circuit/commutation_library.py +20 -0
  23. qiskit/circuit/controlflow/__init__.py +59 -0
  24. qiskit/circuit/controlflow/_builder_utils.py +211 -0
  25. qiskit/circuit/controlflow/box.py +188 -0
  26. qiskit/circuit/controlflow/break_loop.py +56 -0
  27. qiskit/circuit/controlflow/builder.py +791 -0
  28. qiskit/circuit/controlflow/continue_loop.py +56 -0
  29. qiskit/circuit/controlflow/control_flow.py +94 -0
  30. qiskit/circuit/controlflow/for_loop.py +218 -0
  31. qiskit/circuit/controlflow/if_else.py +498 -0
  32. qiskit/circuit/controlflow/switch_case.py +411 -0
  33. qiskit/circuit/controlflow/while_loop.py +166 -0
  34. qiskit/circuit/controlledgate.py +274 -0
  35. qiskit/circuit/delay.py +159 -0
  36. qiskit/circuit/duration.py +80 -0
  37. qiskit/circuit/equivalence.py +94 -0
  38. qiskit/circuit/equivalence_library.py +18 -0
  39. qiskit/circuit/exceptions.py +19 -0
  40. qiskit/circuit/gate.py +261 -0
  41. qiskit/circuit/instruction.py +564 -0
  42. qiskit/circuit/instructionset.py +132 -0
  43. qiskit/circuit/library/__init__.py +984 -0
  44. qiskit/circuit/library/arithmetic/__init__.py +40 -0
  45. qiskit/circuit/library/arithmetic/adders/__init__.py +18 -0
  46. qiskit/circuit/library/arithmetic/adders/adder.py +235 -0
  47. qiskit/circuit/library/arithmetic/adders/cdkm_ripple_carry_adder.py +123 -0
  48. qiskit/circuit/library/arithmetic/adders/draper_qft_adder.py +129 -0
  49. qiskit/circuit/library/arithmetic/adders/vbe_ripple_carry_adder.py +95 -0
  50. qiskit/circuit/library/arithmetic/exact_reciprocal.py +131 -0
  51. qiskit/circuit/library/arithmetic/functional_pauli_rotations.py +114 -0
  52. qiskit/circuit/library/arithmetic/integer_comparator.py +200 -0
  53. qiskit/circuit/library/arithmetic/linear_amplitude_function.py +363 -0
  54. qiskit/circuit/library/arithmetic/linear_pauli_rotations.py +243 -0
  55. qiskit/circuit/library/arithmetic/multipliers/__init__.py +17 -0
  56. qiskit/circuit/library/arithmetic/multipliers/hrs_cumulative_multiplier.py +145 -0
  57. qiskit/circuit/library/arithmetic/multipliers/multiplier.py +201 -0
  58. qiskit/circuit/library/arithmetic/multipliers/rg_qft_multiplier.py +108 -0
  59. qiskit/circuit/library/arithmetic/piecewise_chebyshev.py +506 -0
  60. qiskit/circuit/library/arithmetic/piecewise_linear_pauli_rotations.py +395 -0
  61. qiskit/circuit/library/arithmetic/piecewise_polynomial_pauli_rotations.py +501 -0
  62. qiskit/circuit/library/arithmetic/polynomial_pauli_rotations.py +389 -0
  63. qiskit/circuit/library/arithmetic/quadratic_form.py +370 -0
  64. qiskit/circuit/library/arithmetic/weighted_adder.py +428 -0
  65. qiskit/circuit/library/basis_change/__init__.py +15 -0
  66. qiskit/circuit/library/basis_change/qft.py +316 -0
  67. qiskit/circuit/library/bit_flip_oracle.py +130 -0
  68. qiskit/circuit/library/blueprintcircuit.py +322 -0
  69. qiskit/circuit/library/boolean_logic/__init__.py +18 -0
  70. qiskit/circuit/library/boolean_logic/inner_product.py +157 -0
  71. qiskit/circuit/library/boolean_logic/quantum_and.py +204 -0
  72. qiskit/circuit/library/boolean_logic/quantum_or.py +206 -0
  73. qiskit/circuit/library/boolean_logic/quantum_xor.py +167 -0
  74. qiskit/circuit/library/data_preparation/__init__.py +57 -0
  75. qiskit/circuit/library/data_preparation/_z_feature_map.py +115 -0
  76. qiskit/circuit/library/data_preparation/_zz_feature_map.py +150 -0
  77. qiskit/circuit/library/data_preparation/initializer.py +107 -0
  78. qiskit/circuit/library/data_preparation/pauli_feature_map.py +656 -0
  79. qiskit/circuit/library/data_preparation/state_preparation.py +336 -0
  80. qiskit/circuit/library/fourier_checking.py +160 -0
  81. qiskit/circuit/library/generalized_gates/__init__.py +30 -0
  82. qiskit/circuit/library/generalized_gates/diagonal.py +163 -0
  83. qiskit/circuit/library/generalized_gates/gms.py +179 -0
  84. qiskit/circuit/library/generalized_gates/gr.py +219 -0
  85. qiskit/circuit/library/generalized_gates/isometry.py +370 -0
  86. qiskit/circuit/library/generalized_gates/linear_function.py +318 -0
  87. qiskit/circuit/library/generalized_gates/mcg_up_to_diagonal.py +143 -0
  88. qiskit/circuit/library/generalized_gates/mcmt.py +316 -0
  89. qiskit/circuit/library/generalized_gates/pauli.py +84 -0
  90. qiskit/circuit/library/generalized_gates/permutation.py +202 -0
  91. qiskit/circuit/library/generalized_gates/rv.py +96 -0
  92. qiskit/circuit/library/generalized_gates/uc.py +303 -0
  93. qiskit/circuit/library/generalized_gates/uc_pauli_rot.py +164 -0
  94. qiskit/circuit/library/generalized_gates/ucrx.py +32 -0
  95. qiskit/circuit/library/generalized_gates/ucry.py +32 -0
  96. qiskit/circuit/library/generalized_gates/ucrz.py +32 -0
  97. qiskit/circuit/library/generalized_gates/unitary.py +236 -0
  98. qiskit/circuit/library/graph_state.py +172 -0
  99. qiskit/circuit/library/grover_operator.py +583 -0
  100. qiskit/circuit/library/hamiltonian_gate.py +142 -0
  101. qiskit/circuit/library/hidden_linear_function.py +163 -0
  102. qiskit/circuit/library/iqp.py +180 -0
  103. qiskit/circuit/library/n_local/__init__.py +45 -0
  104. qiskit/circuit/library/n_local/efficient_su2.py +282 -0
  105. qiskit/circuit/library/n_local/evolved_operator_ansatz.py +520 -0
  106. qiskit/circuit/library/n_local/excitation_preserving.py +301 -0
  107. qiskit/circuit/library/n_local/n_local.py +1478 -0
  108. qiskit/circuit/library/n_local/pauli_two_design.py +246 -0
  109. qiskit/circuit/library/n_local/qaoa_ansatz.py +367 -0
  110. qiskit/circuit/library/n_local/real_amplitudes.py +312 -0
  111. qiskit/circuit/library/n_local/two_local.py +289 -0
  112. qiskit/circuit/library/overlap.py +183 -0
  113. qiskit/circuit/library/pauli_evolution.py +202 -0
  114. qiskit/circuit/library/phase_estimation.py +177 -0
  115. qiskit/circuit/library/phase_oracle.py +239 -0
  116. qiskit/circuit/library/quantum_volume.py +179 -0
  117. qiskit/circuit/library/standard_gates/__init__.py +141 -0
  118. qiskit/circuit/library/standard_gates/dcx.py +76 -0
  119. qiskit/circuit/library/standard_gates/ecr.py +126 -0
  120. qiskit/circuit/library/standard_gates/equivalence_library.py +1936 -0
  121. qiskit/circuit/library/standard_gates/global_phase.py +83 -0
  122. qiskit/circuit/library/standard_gates/h.py +230 -0
  123. qiskit/circuit/library/standard_gates/i.py +76 -0
  124. qiskit/circuit/library/standard_gates/iswap.py +115 -0
  125. qiskit/circuit/library/standard_gates/p.py +415 -0
  126. qiskit/circuit/library/standard_gates/r.py +108 -0
  127. qiskit/circuit/library/standard_gates/rx.py +269 -0
  128. qiskit/circuit/library/standard_gates/rxx.py +165 -0
  129. qiskit/circuit/library/standard_gates/ry.py +268 -0
  130. qiskit/circuit/library/standard_gates/ryy.py +165 -0
  131. qiskit/circuit/library/standard_gates/rz.py +290 -0
  132. qiskit/circuit/library/standard_gates/rzx.py +211 -0
  133. qiskit/circuit/library/standard_gates/rzz.py +181 -0
  134. qiskit/circuit/library/standard_gates/s.py +424 -0
  135. qiskit/circuit/library/standard_gates/swap.py +268 -0
  136. qiskit/circuit/library/standard_gates/sx.py +303 -0
  137. qiskit/circuit/library/standard_gates/t.py +169 -0
  138. qiskit/circuit/library/standard_gates/u.py +379 -0
  139. qiskit/circuit/library/standard_gates/u1.py +466 -0
  140. qiskit/circuit/library/standard_gates/u2.py +145 -0
  141. qiskit/circuit/library/standard_gates/u3.py +412 -0
  142. qiskit/circuit/library/standard_gates/x.py +1335 -0
  143. qiskit/circuit/library/standard_gates/xx_minus_yy.py +164 -0
  144. qiskit/circuit/library/standard_gates/xx_plus_yy.py +197 -0
  145. qiskit/circuit/library/standard_gates/y.py +253 -0
  146. qiskit/circuit/library/standard_gates/z.py +331 -0
  147. qiskit/circuit/library/templates/__init__.py +92 -0
  148. qiskit/circuit/library/templates/clifford/__init__.py +33 -0
  149. qiskit/circuit/library/templates/clifford/clifford_2_1.py +34 -0
  150. qiskit/circuit/library/templates/clifford/clifford_2_2.py +35 -0
  151. qiskit/circuit/library/templates/clifford/clifford_2_3.py +34 -0
  152. qiskit/circuit/library/templates/clifford/clifford_2_4.py +34 -0
  153. qiskit/circuit/library/templates/clifford/clifford_3_1.py +35 -0
  154. qiskit/circuit/library/templates/clifford/clifford_4_1.py +38 -0
  155. qiskit/circuit/library/templates/clifford/clifford_4_2.py +37 -0
  156. qiskit/circuit/library/templates/clifford/clifford_4_3.py +38 -0
  157. qiskit/circuit/library/templates/clifford/clifford_4_4.py +37 -0
  158. qiskit/circuit/library/templates/clifford/clifford_5_1.py +40 -0
  159. qiskit/circuit/library/templates/clifford/clifford_6_1.py +40 -0
  160. qiskit/circuit/library/templates/clifford/clifford_6_2.py +40 -0
  161. qiskit/circuit/library/templates/clifford/clifford_6_3.py +40 -0
  162. qiskit/circuit/library/templates/clifford/clifford_6_4.py +38 -0
  163. qiskit/circuit/library/templates/clifford/clifford_6_5.py +40 -0
  164. qiskit/circuit/library/templates/clifford/clifford_8_1.py +42 -0
  165. qiskit/circuit/library/templates/clifford/clifford_8_2.py +42 -0
  166. qiskit/circuit/library/templates/clifford/clifford_8_3.py +41 -0
  167. qiskit/circuit/library/templates/nct/__init__.py +67 -0
  168. qiskit/circuit/library/templates/nct/template_nct_2a_1.py +34 -0
  169. qiskit/circuit/library/templates/nct/template_nct_2a_2.py +35 -0
  170. qiskit/circuit/library/templates/nct/template_nct_2a_3.py +37 -0
  171. qiskit/circuit/library/templates/nct/template_nct_4a_1.py +43 -0
  172. qiskit/circuit/library/templates/nct/template_nct_4a_2.py +41 -0
  173. qiskit/circuit/library/templates/nct/template_nct_4a_3.py +39 -0
  174. qiskit/circuit/library/templates/nct/template_nct_4b_1.py +41 -0
  175. qiskit/circuit/library/templates/nct/template_nct_4b_2.py +39 -0
  176. qiskit/circuit/library/templates/nct/template_nct_5a_1.py +40 -0
  177. qiskit/circuit/library/templates/nct/template_nct_5a_2.py +40 -0
  178. qiskit/circuit/library/templates/nct/template_nct_5a_3.py +40 -0
  179. qiskit/circuit/library/templates/nct/template_nct_5a_4.py +39 -0
  180. qiskit/circuit/library/templates/nct/template_nct_6a_1.py +40 -0
  181. qiskit/circuit/library/templates/nct/template_nct_6a_2.py +41 -0
  182. qiskit/circuit/library/templates/nct/template_nct_6a_3.py +41 -0
  183. qiskit/circuit/library/templates/nct/template_nct_6a_4.py +41 -0
  184. qiskit/circuit/library/templates/nct/template_nct_6b_1.py +41 -0
  185. qiskit/circuit/library/templates/nct/template_nct_6b_2.py +41 -0
  186. qiskit/circuit/library/templates/nct/template_nct_6c_1.py +41 -0
  187. qiskit/circuit/library/templates/nct/template_nct_7a_1.py +43 -0
  188. qiskit/circuit/library/templates/nct/template_nct_7b_1.py +43 -0
  189. qiskit/circuit/library/templates/nct/template_nct_7c_1.py +43 -0
  190. qiskit/circuit/library/templates/nct/template_nct_7d_1.py +43 -0
  191. qiskit/circuit/library/templates/nct/template_nct_7e_1.py +43 -0
  192. qiskit/circuit/library/templates/nct/template_nct_9a_1.py +45 -0
  193. qiskit/circuit/library/templates/nct/template_nct_9c_1.py +43 -0
  194. qiskit/circuit/library/templates/nct/template_nct_9c_10.py +44 -0
  195. qiskit/circuit/library/templates/nct/template_nct_9c_11.py +44 -0
  196. qiskit/circuit/library/templates/nct/template_nct_9c_12.py +44 -0
  197. qiskit/circuit/library/templates/nct/template_nct_9c_2.py +44 -0
  198. qiskit/circuit/library/templates/nct/template_nct_9c_3.py +44 -0
  199. qiskit/circuit/library/templates/nct/template_nct_9c_4.py +44 -0
  200. qiskit/circuit/library/templates/nct/template_nct_9c_5.py +44 -0
  201. qiskit/circuit/library/templates/nct/template_nct_9c_6.py +44 -0
  202. qiskit/circuit/library/templates/nct/template_nct_9c_7.py +44 -0
  203. qiskit/circuit/library/templates/nct/template_nct_9c_8.py +44 -0
  204. qiskit/circuit/library/templates/nct/template_nct_9c_9.py +44 -0
  205. qiskit/circuit/library/templates/nct/template_nct_9d_1.py +43 -0
  206. qiskit/circuit/library/templates/nct/template_nct_9d_10.py +44 -0
  207. qiskit/circuit/library/templates/nct/template_nct_9d_2.py +44 -0
  208. qiskit/circuit/library/templates/nct/template_nct_9d_3.py +44 -0
  209. qiskit/circuit/library/templates/nct/template_nct_9d_4.py +44 -0
  210. qiskit/circuit/library/templates/nct/template_nct_9d_5.py +44 -0
  211. qiskit/circuit/library/templates/nct/template_nct_9d_6.py +44 -0
  212. qiskit/circuit/library/templates/nct/template_nct_9d_7.py +44 -0
  213. qiskit/circuit/library/templates/nct/template_nct_9d_8.py +44 -0
  214. qiskit/circuit/library/templates/nct/template_nct_9d_9.py +44 -0
  215. qiskit/circuit/library/templates/rzx/__init__.py +25 -0
  216. qiskit/circuit/library/templates/rzx/rzx_cy.py +47 -0
  217. qiskit/circuit/library/templates/rzx/rzx_xz.py +54 -0
  218. qiskit/circuit/library/templates/rzx/rzx_yz.py +45 -0
  219. qiskit/circuit/library/templates/rzx/rzx_zz1.py +69 -0
  220. qiskit/circuit/library/templates/rzx/rzx_zz2.py +59 -0
  221. qiskit/circuit/library/templates/rzx/rzx_zz3.py +59 -0
  222. qiskit/circuit/measure.py +53 -0
  223. qiskit/circuit/operation.py +68 -0
  224. qiskit/circuit/parameter.py +188 -0
  225. qiskit/circuit/parameterexpression.py +737 -0
  226. qiskit/circuit/parametertable.py +119 -0
  227. qiskit/circuit/parametervector.py +140 -0
  228. qiskit/circuit/quantumcircuit.py +7610 -0
  229. qiskit/circuit/quantumcircuitdata.py +137 -0
  230. qiskit/circuit/random/__init__.py +50 -0
  231. qiskit/circuit/random/utils.py +755 -0
  232. qiskit/circuit/reset.py +37 -0
  233. qiskit/circuit/singleton.py +600 -0
  234. qiskit/circuit/store.py +89 -0
  235. qiskit/circuit/tools/__init__.py +16 -0
  236. qiskit/circuit/tools/pi_check.py +185 -0
  237. qiskit/circuit/twirling.py +145 -0
  238. qiskit/compiler/__init__.py +27 -0
  239. qiskit/compiler/transpiler.py +375 -0
  240. qiskit/converters/__init__.py +74 -0
  241. qiskit/converters/circuit_to_dag.py +80 -0
  242. qiskit/converters/circuit_to_dagdependency.py +49 -0
  243. qiskit/converters/circuit_to_dagdependency_v2.py +46 -0
  244. qiskit/converters/circuit_to_gate.py +107 -0
  245. qiskit/converters/circuit_to_instruction.py +142 -0
  246. qiskit/converters/dag_to_circuit.py +79 -0
  247. qiskit/converters/dag_to_dagdependency.py +54 -0
  248. qiskit/converters/dag_to_dagdependency_v2.py +43 -0
  249. qiskit/converters/dagdependency_to_circuit.py +40 -0
  250. qiskit/converters/dagdependency_to_dag.py +48 -0
  251. qiskit/dagcircuit/__init__.py +44 -0
  252. qiskit/dagcircuit/collect_blocks.py +403 -0
  253. qiskit/dagcircuit/dagcircuit.py +24 -0
  254. qiskit/dagcircuit/dagdependency.py +612 -0
  255. qiskit/dagcircuit/dagdependency_v2.py +566 -0
  256. qiskit/dagcircuit/dagdepnode.py +160 -0
  257. qiskit/dagcircuit/dagnode.py +193 -0
  258. qiskit/dagcircuit/exceptions.py +42 -0
  259. qiskit/exceptions.py +153 -0
  260. qiskit/passmanager/__init__.py +258 -0
  261. qiskit/passmanager/base_tasks.py +230 -0
  262. qiskit/passmanager/compilation_status.py +74 -0
  263. qiskit/passmanager/exceptions.py +19 -0
  264. qiskit/passmanager/flow_controllers.py +116 -0
  265. qiskit/passmanager/passmanager.py +353 -0
  266. qiskit/primitives/__init__.py +490 -0
  267. qiskit/primitives/backend_estimator_v2.py +530 -0
  268. qiskit/primitives/backend_sampler_v2.py +339 -0
  269. qiskit/primitives/base/__init__.py +20 -0
  270. qiskit/primitives/base/base_estimator.py +247 -0
  271. qiskit/primitives/base/base_primitive_job.py +78 -0
  272. qiskit/primitives/base/base_primitive_v1.py +45 -0
  273. qiskit/primitives/base/base_result_v1.py +65 -0
  274. qiskit/primitives/base/base_sampler.py +196 -0
  275. qiskit/primitives/base/estimator_result_v1.py +46 -0
  276. qiskit/primitives/base/sampler_result_v1.py +45 -0
  277. qiskit/primitives/base/validation_v1.py +250 -0
  278. qiskit/primitives/containers/__init__.py +26 -0
  279. qiskit/primitives/containers/bindings_array.py +391 -0
  280. qiskit/primitives/containers/bit_array.py +764 -0
  281. qiskit/primitives/containers/data_bin.py +172 -0
  282. qiskit/primitives/containers/estimator_pub.py +222 -0
  283. qiskit/primitives/containers/object_array.py +94 -0
  284. qiskit/primitives/containers/observables_array.py +380 -0
  285. qiskit/primitives/containers/primitive_result.py +53 -0
  286. qiskit/primitives/containers/pub_result.py +51 -0
  287. qiskit/primitives/containers/sampler_pub.py +193 -0
  288. qiskit/primitives/containers/sampler_pub_result.py +74 -0
  289. qiskit/primitives/containers/shape.py +129 -0
  290. qiskit/primitives/primitive_job.py +100 -0
  291. qiskit/primitives/statevector_estimator.py +175 -0
  292. qiskit/primitives/statevector_sampler.py +290 -0
  293. qiskit/primitives/utils.py +72 -0
  294. qiskit/providers/__init__.py +677 -0
  295. qiskit/providers/backend.py +364 -0
  296. qiskit/providers/basic_provider/__init__.py +47 -0
  297. qiskit/providers/basic_provider/basic_provider.py +121 -0
  298. qiskit/providers/basic_provider/basic_provider_job.py +65 -0
  299. qiskit/providers/basic_provider/basic_provider_tools.py +218 -0
  300. qiskit/providers/basic_provider/basic_simulator.py +693 -0
  301. qiskit/providers/basic_provider/exceptions.py +30 -0
  302. qiskit/providers/exceptions.py +33 -0
  303. qiskit/providers/fake_provider/__init__.py +69 -0
  304. qiskit/providers/fake_provider/generic_backend_v2.py +376 -0
  305. qiskit/providers/fake_provider/utils/__init__.py +15 -0
  306. qiskit/providers/job.py +147 -0
  307. qiskit/providers/jobstatus.py +30 -0
  308. qiskit/providers/options.py +273 -0
  309. qiskit/providers/providerutils.py +110 -0
  310. qiskit/qasm/libs/dummy/stdgates.inc +75 -0
  311. qiskit/qasm/libs/qelib1.inc +266 -0
  312. qiskit/qasm/libs/stdgates.inc +82 -0
  313. qiskit/qasm2/__init__.py +669 -0
  314. qiskit/qasm2/exceptions.py +27 -0
  315. qiskit/qasm2/export.py +364 -0
  316. qiskit/qasm2/parse.py +438 -0
  317. qiskit/qasm3/__init__.py +466 -0
  318. qiskit/qasm3/ast.py +796 -0
  319. qiskit/qasm3/exceptions.py +27 -0
  320. qiskit/qasm3/experimental.py +70 -0
  321. qiskit/qasm3/exporter.py +1363 -0
  322. qiskit/qasm3/printer.py +620 -0
  323. qiskit/qpy/__init__.py +2141 -0
  324. qiskit/qpy/binary_io/__init__.py +35 -0
  325. qiskit/qpy/binary_io/circuits.py +1687 -0
  326. qiskit/qpy/binary_io/parse_sympy_repr.py +126 -0
  327. qiskit/qpy/binary_io/schedules.py +288 -0
  328. qiskit/qpy/binary_io/value.py +1183 -0
  329. qiskit/qpy/common.py +361 -0
  330. qiskit/qpy/exceptions.py +53 -0
  331. qiskit/qpy/formats.py +458 -0
  332. qiskit/qpy/interface.py +384 -0
  333. qiskit/qpy/type_keys.py +415 -0
  334. qiskit/quantum_info/__init__.py +172 -0
  335. qiskit/quantum_info/analysis/__init__.py +17 -0
  336. qiskit/quantum_info/analysis/average.py +47 -0
  337. qiskit/quantum_info/analysis/distance.py +104 -0
  338. qiskit/quantum_info/analysis/make_observable.py +44 -0
  339. qiskit/quantum_info/analysis/z2_symmetries.py +484 -0
  340. qiskit/quantum_info/operators/__init__.py +29 -0
  341. qiskit/quantum_info/operators/base_operator.py +145 -0
  342. qiskit/quantum_info/operators/channel/__init__.py +29 -0
  343. qiskit/quantum_info/operators/channel/chi.py +191 -0
  344. qiskit/quantum_info/operators/channel/choi.py +218 -0
  345. qiskit/quantum_info/operators/channel/kraus.py +337 -0
  346. qiskit/quantum_info/operators/channel/ptm.py +204 -0
  347. qiskit/quantum_info/operators/channel/quantum_channel.py +348 -0
  348. qiskit/quantum_info/operators/channel/stinespring.py +296 -0
  349. qiskit/quantum_info/operators/channel/superop.py +373 -0
  350. qiskit/quantum_info/operators/channel/transformations.py +490 -0
  351. qiskit/quantum_info/operators/custom_iterator.py +48 -0
  352. qiskit/quantum_info/operators/dihedral/__init__.py +18 -0
  353. qiskit/quantum_info/operators/dihedral/dihedral.py +511 -0
  354. qiskit/quantum_info/operators/dihedral/dihedral_circuits.py +216 -0
  355. qiskit/quantum_info/operators/dihedral/polynomial.py +313 -0
  356. qiskit/quantum_info/operators/dihedral/random.py +64 -0
  357. qiskit/quantum_info/operators/linear_op.py +25 -0
  358. qiskit/quantum_info/operators/measures.py +418 -0
  359. qiskit/quantum_info/operators/mixins/__init__.py +52 -0
  360. qiskit/quantum_info/operators/mixins/adjoint.py +52 -0
  361. qiskit/quantum_info/operators/mixins/group.py +171 -0
  362. qiskit/quantum_info/operators/mixins/linear.py +84 -0
  363. qiskit/quantum_info/operators/mixins/multiply.py +62 -0
  364. qiskit/quantum_info/operators/mixins/tolerances.py +72 -0
  365. qiskit/quantum_info/operators/op_shape.py +525 -0
  366. qiskit/quantum_info/operators/operator.py +869 -0
  367. qiskit/quantum_info/operators/operator_utils.py +76 -0
  368. qiskit/quantum_info/operators/predicates.py +183 -0
  369. qiskit/quantum_info/operators/random.py +154 -0
  370. qiskit/quantum_info/operators/scalar_op.py +254 -0
  371. qiskit/quantum_info/operators/symplectic/__init__.py +24 -0
  372. qiskit/quantum_info/operators/symplectic/base_pauli.py +719 -0
  373. qiskit/quantum_info/operators/symplectic/clifford.py +1032 -0
  374. qiskit/quantum_info/operators/symplectic/clifford_circuits.py +584 -0
  375. qiskit/quantum_info/operators/symplectic/pauli.py +755 -0
  376. qiskit/quantum_info/operators/symplectic/pauli_list.py +1242 -0
  377. qiskit/quantum_info/operators/symplectic/pauli_utils.py +40 -0
  378. qiskit/quantum_info/operators/symplectic/random.py +117 -0
  379. qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py +1239 -0
  380. qiskit/quantum_info/operators/utils/__init__.py +20 -0
  381. qiskit/quantum_info/operators/utils/anti_commutator.py +36 -0
  382. qiskit/quantum_info/operators/utils/commutator.py +36 -0
  383. qiskit/quantum_info/operators/utils/double_commutator.py +76 -0
  384. qiskit/quantum_info/quaternion.py +156 -0
  385. qiskit/quantum_info/random.py +26 -0
  386. qiskit/quantum_info/states/__init__.py +28 -0
  387. qiskit/quantum_info/states/densitymatrix.py +857 -0
  388. qiskit/quantum_info/states/measures.py +288 -0
  389. qiskit/quantum_info/states/quantum_state.py +503 -0
  390. qiskit/quantum_info/states/random.py +157 -0
  391. qiskit/quantum_info/states/stabilizerstate.py +805 -0
  392. qiskit/quantum_info/states/statevector.py +977 -0
  393. qiskit/quantum_info/states/utils.py +247 -0
  394. qiskit/result/__init__.py +61 -0
  395. qiskit/result/counts.py +189 -0
  396. qiskit/result/distributions/__init__.py +17 -0
  397. qiskit/result/distributions/probability.py +100 -0
  398. qiskit/result/distributions/quasi.py +154 -0
  399. qiskit/result/exceptions.py +40 -0
  400. qiskit/result/models.py +241 -0
  401. qiskit/result/postprocess.py +239 -0
  402. qiskit/result/result.py +385 -0
  403. qiskit/result/sampled_expval.py +76 -0
  404. qiskit/result/utils.py +294 -0
  405. qiskit/synthesis/__init__.py +250 -0
  406. qiskit/synthesis/arithmetic/__init__.py +18 -0
  407. qiskit/synthesis/arithmetic/adders/__init__.py +18 -0
  408. qiskit/synthesis/arithmetic/adders/cdkm_ripple_carry_adder.py +154 -0
  409. qiskit/synthesis/arithmetic/adders/draper_qft_adder.py +107 -0
  410. qiskit/synthesis/arithmetic/adders/rv_ripple_carry_adder.py +156 -0
  411. qiskit/synthesis/arithmetic/adders/vbe_ripple_carry_adder.py +161 -0
  412. qiskit/synthesis/arithmetic/comparators/__init__.py +16 -0
  413. qiskit/synthesis/arithmetic/comparators/compare_2s.py +112 -0
  414. qiskit/synthesis/arithmetic/comparators/compare_greedy.py +66 -0
  415. qiskit/synthesis/arithmetic/multipliers/__init__.py +16 -0
  416. qiskit/synthesis/arithmetic/multipliers/hrs_cumulative_multiplier.py +103 -0
  417. qiskit/synthesis/arithmetic/multipliers/rg_qft_multiplier.py +100 -0
  418. qiskit/synthesis/arithmetic/weighted_sum.py +155 -0
  419. qiskit/synthesis/boolean/__init__.py +13 -0
  420. qiskit/synthesis/boolean/boolean_expression.py +231 -0
  421. qiskit/synthesis/boolean/boolean_expression_synth.py +124 -0
  422. qiskit/synthesis/boolean/boolean_expression_visitor.py +96 -0
  423. qiskit/synthesis/clifford/__init__.py +19 -0
  424. qiskit/synthesis/clifford/clifford_decompose_ag.py +178 -0
  425. qiskit/synthesis/clifford/clifford_decompose_bm.py +46 -0
  426. qiskit/synthesis/clifford/clifford_decompose_full.py +64 -0
  427. qiskit/synthesis/clifford/clifford_decompose_greedy.py +58 -0
  428. qiskit/synthesis/clifford/clifford_decompose_layers.py +447 -0
  429. qiskit/synthesis/cnotdihedral/__init__.py +17 -0
  430. qiskit/synthesis/cnotdihedral/cnotdihedral_decompose_full.py +52 -0
  431. qiskit/synthesis/cnotdihedral/cnotdihedral_decompose_general.py +141 -0
  432. qiskit/synthesis/cnotdihedral/cnotdihedral_decompose_two_qubits.py +266 -0
  433. qiskit/synthesis/discrete_basis/__init__.py +16 -0
  434. qiskit/synthesis/discrete_basis/generate_basis_approximations.py +53 -0
  435. qiskit/synthesis/discrete_basis/solovay_kitaev.py +280 -0
  436. qiskit/synthesis/evolution/__init__.py +21 -0
  437. qiskit/synthesis/evolution/evolution_synthesis.py +48 -0
  438. qiskit/synthesis/evolution/lie_trotter.py +123 -0
  439. qiskit/synthesis/evolution/matrix_synthesis.py +47 -0
  440. qiskit/synthesis/evolution/pauli_network.py +80 -0
  441. qiskit/synthesis/evolution/product_formula.py +316 -0
  442. qiskit/synthesis/evolution/qdrift.py +133 -0
  443. qiskit/synthesis/evolution/suzuki_trotter.py +227 -0
  444. qiskit/synthesis/linear/__init__.py +26 -0
  445. qiskit/synthesis/linear/cnot_synth.py +69 -0
  446. qiskit/synthesis/linear/linear_circuits_utils.py +128 -0
  447. qiskit/synthesis/linear/linear_depth_lnn.py +61 -0
  448. qiskit/synthesis/linear/linear_matrix_utils.py +27 -0
  449. qiskit/synthesis/linear_phase/__init__.py +17 -0
  450. qiskit/synthesis/linear_phase/cnot_phase_synth.py +206 -0
  451. qiskit/synthesis/linear_phase/cx_cz_depth_lnn.py +61 -0
  452. qiskit/synthesis/linear_phase/cz_depth_lnn.py +58 -0
  453. qiskit/synthesis/multi_controlled/__init__.py +29 -0
  454. qiskit/synthesis/multi_controlled/mcmt_vchain.py +52 -0
  455. qiskit/synthesis/multi_controlled/mcx_synthesis.py +583 -0
  456. qiskit/synthesis/multi_controlled/multi_control_rotation_gates.py +205 -0
  457. qiskit/synthesis/one_qubit/__init__.py +15 -0
  458. qiskit/synthesis/one_qubit/one_qubit_decompose.py +288 -0
  459. qiskit/synthesis/permutation/__init__.py +18 -0
  460. qiskit/synthesis/permutation/permutation_full.py +78 -0
  461. qiskit/synthesis/permutation/permutation_lnn.py +54 -0
  462. qiskit/synthesis/permutation/permutation_reverse_lnn.py +93 -0
  463. qiskit/synthesis/permutation/permutation_utils.py +16 -0
  464. qiskit/synthesis/qft/__init__.py +16 -0
  465. qiskit/synthesis/qft/qft_decompose_full.py +97 -0
  466. qiskit/synthesis/qft/qft_decompose_lnn.py +61 -0
  467. qiskit/synthesis/stabilizer/__init__.py +16 -0
  468. qiskit/synthesis/stabilizer/stabilizer_circuit.py +149 -0
  469. qiskit/synthesis/stabilizer/stabilizer_decompose.py +194 -0
  470. qiskit/synthesis/two_qubit/__init__.py +20 -0
  471. qiskit/synthesis/two_qubit/local_invariance.py +63 -0
  472. qiskit/synthesis/two_qubit/two_qubit_decompose.py +583 -0
  473. qiskit/synthesis/two_qubit/xx_decompose/__init__.py +19 -0
  474. qiskit/synthesis/two_qubit/xx_decompose/circuits.py +300 -0
  475. qiskit/synthesis/two_qubit/xx_decompose/decomposer.py +324 -0
  476. qiskit/synthesis/two_qubit/xx_decompose/embodiments.py +163 -0
  477. qiskit/synthesis/two_qubit/xx_decompose/paths.py +412 -0
  478. qiskit/synthesis/two_qubit/xx_decompose/polytopes.py +262 -0
  479. qiskit/synthesis/two_qubit/xx_decompose/utilities.py +40 -0
  480. qiskit/synthesis/two_qubit/xx_decompose/weyl.py +133 -0
  481. qiskit/synthesis/unitary/__init__.py +13 -0
  482. qiskit/synthesis/unitary/aqc/__init__.py +177 -0
  483. qiskit/synthesis/unitary/aqc/approximate.py +116 -0
  484. qiskit/synthesis/unitary/aqc/aqc.py +175 -0
  485. qiskit/synthesis/unitary/aqc/cnot_structures.py +300 -0
  486. qiskit/synthesis/unitary/aqc/cnot_unit_circuit.py +103 -0
  487. qiskit/synthesis/unitary/aqc/cnot_unit_objective.py +299 -0
  488. qiskit/synthesis/unitary/aqc/elementary_operations.py +108 -0
  489. qiskit/synthesis/unitary/aqc/fast_gradient/__init__.py +164 -0
  490. qiskit/synthesis/unitary/aqc/fast_gradient/fast_grad_utils.py +237 -0
  491. qiskit/synthesis/unitary/aqc/fast_gradient/fast_gradient.py +226 -0
  492. qiskit/synthesis/unitary/aqc/fast_gradient/layer.py +370 -0
  493. qiskit/synthesis/unitary/aqc/fast_gradient/pmatrix.py +312 -0
  494. qiskit/synthesis/unitary/qsd.py +359 -0
  495. qiskit/transpiler/__init__.py +1352 -0
  496. qiskit/transpiler/basepasses.py +190 -0
  497. qiskit/transpiler/coupling.py +500 -0
  498. qiskit/transpiler/exceptions.py +59 -0
  499. qiskit/transpiler/instruction_durations.py +263 -0
  500. qiskit/transpiler/layout.py +740 -0
  501. qiskit/transpiler/passes/__init__.py +278 -0
  502. qiskit/transpiler/passes/analysis/__init__.py +23 -0
  503. qiskit/transpiler/passes/analysis/count_ops.py +30 -0
  504. qiskit/transpiler/passes/analysis/count_ops_longest_path.py +26 -0
  505. qiskit/transpiler/passes/analysis/dag_longest_path.py +24 -0
  506. qiskit/transpiler/passes/analysis/depth.py +33 -0
  507. qiskit/transpiler/passes/analysis/num_qubits.py +26 -0
  508. qiskit/transpiler/passes/analysis/num_tensor_factors.py +26 -0
  509. qiskit/transpiler/passes/analysis/resource_estimation.py +41 -0
  510. qiskit/transpiler/passes/analysis/size.py +36 -0
  511. qiskit/transpiler/passes/analysis/width.py +27 -0
  512. qiskit/transpiler/passes/basis/__init__.py +19 -0
  513. qiskit/transpiler/passes/basis/basis_translator.py +138 -0
  514. qiskit/transpiler/passes/basis/decompose.py +137 -0
  515. qiskit/transpiler/passes/basis/translate_parameterized.py +175 -0
  516. qiskit/transpiler/passes/basis/unroll_3q_or_more.py +84 -0
  517. qiskit/transpiler/passes/basis/unroll_custom_definitions.py +110 -0
  518. qiskit/transpiler/passes/layout/__init__.py +26 -0
  519. qiskit/transpiler/passes/layout/_csp_custom_solver.py +65 -0
  520. qiskit/transpiler/passes/layout/apply_layout.py +128 -0
  521. qiskit/transpiler/passes/layout/csp_layout.py +132 -0
  522. qiskit/transpiler/passes/layout/dense_layout.py +197 -0
  523. qiskit/transpiler/passes/layout/disjoint_utils.py +54 -0
  524. qiskit/transpiler/passes/layout/enlarge_with_ancilla.py +49 -0
  525. qiskit/transpiler/passes/layout/full_ancilla_allocation.py +116 -0
  526. qiskit/transpiler/passes/layout/layout_2q_distance.py +77 -0
  527. qiskit/transpiler/passes/layout/sabre_layout.py +525 -0
  528. qiskit/transpiler/passes/layout/sabre_pre_layout.py +225 -0
  529. qiskit/transpiler/passes/layout/set_layout.py +69 -0
  530. qiskit/transpiler/passes/layout/trivial_layout.py +66 -0
  531. qiskit/transpiler/passes/layout/vf2_layout.py +292 -0
  532. qiskit/transpiler/passes/layout/vf2_post_layout.py +376 -0
  533. qiskit/transpiler/passes/layout/vf2_utils.py +245 -0
  534. qiskit/transpiler/passes/optimization/__init__.py +42 -0
  535. qiskit/transpiler/passes/optimization/_gate_extension.py +80 -0
  536. qiskit/transpiler/passes/optimization/collect_1q_runs.py +31 -0
  537. qiskit/transpiler/passes/optimization/collect_2q_blocks.py +35 -0
  538. qiskit/transpiler/passes/optimization/collect_and_collapse.py +117 -0
  539. qiskit/transpiler/passes/optimization/collect_cliffords.py +109 -0
  540. qiskit/transpiler/passes/optimization/collect_linear_functions.py +85 -0
  541. qiskit/transpiler/passes/optimization/collect_multiqubit_blocks.py +242 -0
  542. qiskit/transpiler/passes/optimization/commutation_analysis.py +44 -0
  543. qiskit/transpiler/passes/optimization/commutative_cancellation.py +82 -0
  544. qiskit/transpiler/passes/optimization/commutative_inverse_cancellation.py +140 -0
  545. qiskit/transpiler/passes/optimization/consolidate_blocks.py +176 -0
  546. qiskit/transpiler/passes/optimization/contract_idle_wires_in_control_flow.py +104 -0
  547. qiskit/transpiler/passes/optimization/elide_permutations.py +91 -0
  548. qiskit/transpiler/passes/optimization/hoare_opt.py +420 -0
  549. qiskit/transpiler/passes/optimization/inverse_cancellation.py +95 -0
  550. qiskit/transpiler/passes/optimization/light_cone.py +135 -0
  551. qiskit/transpiler/passes/optimization/optimize_1q_commutation.py +267 -0
  552. qiskit/transpiler/passes/optimization/optimize_1q_decomposition.py +251 -0
  553. qiskit/transpiler/passes/optimization/optimize_1q_gates.py +384 -0
  554. qiskit/transpiler/passes/optimization/optimize_annotated.py +449 -0
  555. qiskit/transpiler/passes/optimization/optimize_clifford_t.py +68 -0
  556. qiskit/transpiler/passes/optimization/optimize_cliffords.py +89 -0
  557. qiskit/transpiler/passes/optimization/optimize_swap_before_measure.py +71 -0
  558. qiskit/transpiler/passes/optimization/remove_diagonal_gates_before_measure.py +41 -0
  559. qiskit/transpiler/passes/optimization/remove_final_reset.py +37 -0
  560. qiskit/transpiler/passes/optimization/remove_identity_equiv.py +70 -0
  561. qiskit/transpiler/passes/optimization/remove_reset_in_zero_state.py +37 -0
  562. qiskit/transpiler/passes/optimization/reset_after_measure_simplification.py +50 -0
  563. qiskit/transpiler/passes/optimization/split_2q_unitaries.py +63 -0
  564. qiskit/transpiler/passes/optimization/template_matching/__init__.py +19 -0
  565. qiskit/transpiler/passes/optimization/template_matching/backward_match.py +749 -0
  566. qiskit/transpiler/passes/optimization/template_matching/forward_match.py +452 -0
  567. qiskit/transpiler/passes/optimization/template_matching/maximal_matches.py +77 -0
  568. qiskit/transpiler/passes/optimization/template_matching/template_matching.py +370 -0
  569. qiskit/transpiler/passes/optimization/template_matching/template_substitution.py +633 -0
  570. qiskit/transpiler/passes/optimization/template_optimization.py +158 -0
  571. qiskit/transpiler/passes/routing/__init__.py +21 -0
  572. qiskit/transpiler/passes/routing/algorithms/__init__.py +33 -0
  573. qiskit/transpiler/passes/routing/algorithms/token_swapper.py +105 -0
  574. qiskit/transpiler/passes/routing/algorithms/types.py +46 -0
  575. qiskit/transpiler/passes/routing/algorithms/util.py +103 -0
  576. qiskit/transpiler/passes/routing/basic_swap.py +166 -0
  577. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/__init__.py +25 -0
  578. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_block.py +60 -0
  579. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py +397 -0
  580. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py +145 -0
  581. qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py +306 -0
  582. qiskit/transpiler/passes/routing/layout_transformation.py +119 -0
  583. qiskit/transpiler/passes/routing/lookahead_swap.py +390 -0
  584. qiskit/transpiler/passes/routing/sabre_swap.py +465 -0
  585. qiskit/transpiler/passes/routing/star_prerouting.py +433 -0
  586. qiskit/transpiler/passes/routing/utils.py +35 -0
  587. qiskit/transpiler/passes/scheduling/__init__.py +21 -0
  588. qiskit/transpiler/passes/scheduling/alignments/__init__.py +79 -0
  589. qiskit/transpiler/passes/scheduling/alignments/check_durations.py +70 -0
  590. qiskit/transpiler/passes/scheduling/alignments/reschedule.py +251 -0
  591. qiskit/transpiler/passes/scheduling/padding/__init__.py +17 -0
  592. qiskit/transpiler/passes/scheduling/padding/base_padding.py +284 -0
  593. qiskit/transpiler/passes/scheduling/padding/context_aware_dynamical_decoupling.py +876 -0
  594. qiskit/transpiler/passes/scheduling/padding/dynamical_decoupling.py +415 -0
  595. qiskit/transpiler/passes/scheduling/padding/pad_delay.py +90 -0
  596. qiskit/transpiler/passes/scheduling/scheduling/__init__.py +17 -0
  597. qiskit/transpiler/passes/scheduling/scheduling/alap.py +93 -0
  598. qiskit/transpiler/passes/scheduling/scheduling/asap.py +100 -0
  599. qiskit/transpiler/passes/scheduling/scheduling/base_scheduler.py +88 -0
  600. qiskit/transpiler/passes/scheduling/scheduling/set_io_latency.py +64 -0
  601. qiskit/transpiler/passes/scheduling/time_unit_conversion.py +237 -0
  602. qiskit/transpiler/passes/synthesis/__init__.py +21 -0
  603. qiskit/transpiler/passes/synthesis/aqc_plugin.py +153 -0
  604. qiskit/transpiler/passes/synthesis/clifford_unitary_synth_plugin.py +123 -0
  605. qiskit/transpiler/passes/synthesis/default_unitary_synth_plugin.py +653 -0
  606. qiskit/transpiler/passes/synthesis/high_level_synthesis.py +429 -0
  607. qiskit/transpiler/passes/synthesis/hls_plugins.py +2338 -0
  608. qiskit/transpiler/passes/synthesis/linear_functions_synthesis.py +41 -0
  609. qiskit/transpiler/passes/synthesis/plugin.py +738 -0
  610. qiskit/transpiler/passes/synthesis/solovay_kitaev_synthesis.py +318 -0
  611. qiskit/transpiler/passes/synthesis/unitary_synthesis.py +425 -0
  612. qiskit/transpiler/passes/utils/__init__.py +32 -0
  613. qiskit/transpiler/passes/utils/barrier_before_final_measurements.py +41 -0
  614. qiskit/transpiler/passes/utils/check_gate_direction.py +60 -0
  615. qiskit/transpiler/passes/utils/check_map.py +78 -0
  616. qiskit/transpiler/passes/utils/contains_instruction.py +45 -0
  617. qiskit/transpiler/passes/utils/control_flow.py +61 -0
  618. qiskit/transpiler/passes/utils/dag_fixed_point.py +36 -0
  619. qiskit/transpiler/passes/utils/error.py +69 -0
  620. qiskit/transpiler/passes/utils/filter_op_nodes.py +66 -0
  621. qiskit/transpiler/passes/utils/fixed_point.py +48 -0
  622. qiskit/transpiler/passes/utils/gate_direction.py +93 -0
  623. qiskit/transpiler/passes/utils/gates_basis.py +51 -0
  624. qiskit/transpiler/passes/utils/merge_adjacent_barriers.py +163 -0
  625. qiskit/transpiler/passes/utils/minimum_point.py +118 -0
  626. qiskit/transpiler/passes/utils/remove_barriers.py +50 -0
  627. qiskit/transpiler/passes/utils/remove_final_measurements.py +121 -0
  628. qiskit/transpiler/passes/utils/unroll_forloops.py +81 -0
  629. qiskit/transpiler/passmanager.py +503 -0
  630. qiskit/transpiler/passmanager_config.py +154 -0
  631. qiskit/transpiler/preset_passmanagers/__init__.py +93 -0
  632. qiskit/transpiler/preset_passmanagers/builtin_plugins.py +1114 -0
  633. qiskit/transpiler/preset_passmanagers/common.py +773 -0
  634. qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py +443 -0
  635. qiskit/transpiler/preset_passmanagers/level0.py +104 -0
  636. qiskit/transpiler/preset_passmanagers/level1.py +108 -0
  637. qiskit/transpiler/preset_passmanagers/level2.py +109 -0
  638. qiskit/transpiler/preset_passmanagers/level3.py +110 -0
  639. qiskit/transpiler/preset_passmanagers/plugin.py +346 -0
  640. qiskit/transpiler/target.py +905 -0
  641. qiskit/transpiler/timing_constraints.py +59 -0
  642. qiskit/user_config.py +266 -0
  643. qiskit/utils/__init__.py +90 -0
  644. qiskit/utils/classtools.py +146 -0
  645. qiskit/utils/deprecation.py +382 -0
  646. qiskit/utils/lazy_tester.py +363 -0
  647. qiskit/utils/optionals.py +355 -0
  648. qiskit/utils/parallel.py +318 -0
  649. qiskit/utils/units.py +146 -0
  650. qiskit/version.py +84 -0
  651. qiskit/visualization/__init__.py +290 -0
  652. qiskit/visualization/array.py +207 -0
  653. qiskit/visualization/bloch.py +778 -0
  654. qiskit/visualization/circuit/__init__.py +15 -0
  655. qiskit/visualization/circuit/_utils.py +677 -0
  656. qiskit/visualization/circuit/circuit_visualization.py +735 -0
  657. qiskit/visualization/circuit/latex.py +668 -0
  658. qiskit/visualization/circuit/matplotlib.py +2041 -0
  659. qiskit/visualization/circuit/qcstyle.py +130 -0
  660. qiskit/visualization/circuit/styles/__init__.py +13 -0
  661. qiskit/visualization/circuit/styles/bw.json +202 -0
  662. qiskit/visualization/circuit/styles/clifford.json +202 -0
  663. qiskit/visualization/circuit/styles/iqp-dark.json +214 -0
  664. qiskit/visualization/circuit/styles/iqp.json +214 -0
  665. qiskit/visualization/circuit/styles/textbook.json +202 -0
  666. qiskit/visualization/circuit/text.py +1849 -0
  667. qiskit/visualization/circuit_visualization.py +19 -0
  668. qiskit/visualization/counts_visualization.py +487 -0
  669. qiskit/visualization/dag/__init__.py +13 -0
  670. qiskit/visualization/dag/dagstyle.py +103 -0
  671. qiskit/visualization/dag/styles/__init__.py +13 -0
  672. qiskit/visualization/dag/styles/color.json +10 -0
  673. qiskit/visualization/dag/styles/plain.json +5 -0
  674. qiskit/visualization/dag_visualization.py +389 -0
  675. qiskit/visualization/exceptions.py +21 -0
  676. qiskit/visualization/gate_map.py +1424 -0
  677. qiskit/visualization/library.py +40 -0
  678. qiskit/visualization/pass_manager_visualization.py +312 -0
  679. qiskit/visualization/state_visualization.py +1546 -0
  680. qiskit/visualization/style.py +223 -0
  681. qiskit/visualization/timeline/__init__.py +21 -0
  682. qiskit/visualization/timeline/core.py +495 -0
  683. qiskit/visualization/timeline/drawings.py +260 -0
  684. qiskit/visualization/timeline/generators.py +506 -0
  685. qiskit/visualization/timeline/interface.py +444 -0
  686. qiskit/visualization/timeline/layouts.py +115 -0
  687. qiskit/visualization/timeline/plotters/__init__.py +16 -0
  688. qiskit/visualization/timeline/plotters/base_plotter.py +58 -0
  689. qiskit/visualization/timeline/plotters/matplotlib.py +195 -0
  690. qiskit/visualization/timeline/stylesheet.py +301 -0
  691. qiskit/visualization/timeline/types.py +148 -0
  692. qiskit/visualization/transition_visualization.py +369 -0
  693. qiskit/visualization/utils.py +49 -0
  694. qiskit-2.1.0rc1.dist-info/METADATA +221 -0
  695. qiskit-2.1.0rc1.dist-info/RECORD +699 -0
  696. qiskit-2.1.0rc1.dist-info/WHEEL +6 -0
  697. qiskit-2.1.0rc1.dist-info/entry_points.txt +88 -0
  698. qiskit-2.1.0rc1.dist-info/licenses/LICENSE.txt +203 -0
  699. qiskit-2.1.0rc1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1242 @@
1
+ # This code is part of Qiskit.
2
+ #
3
+ # (C) Copyright IBM 2017, 2022
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
+ Optimized list of Pauli operators
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections import defaultdict
19
+ from typing import Literal
20
+
21
+ import numpy as np
22
+ import rustworkx as rx
23
+
24
+ from qiskit.circuit.quantumcircuit import QuantumCircuit
25
+ from qiskit.exceptions import QiskitError
26
+ from qiskit.quantum_info.operators.custom_iterator import CustomIterator
27
+ from qiskit.quantum_info.operators.mixins import GroupMixin, LinearMixin
28
+ from qiskit.quantum_info.operators.symplectic.base_pauli import BasePauli
29
+ from qiskit.quantum_info.operators.symplectic.clifford import Clifford
30
+ from qiskit.quantum_info.operators.symplectic.pauli import Pauli
31
+
32
+
33
+ class PauliList(BasePauli, LinearMixin, GroupMixin):
34
+ r"""List of N-qubit Pauli operators.
35
+
36
+ This class is an efficient representation of a list of
37
+ :class:`Pauli` operators. It supports 1D numpy array indexing
38
+ returning a :class:`Pauli` for integer indexes or a
39
+ :class:`PauliList` for slice or list indices.
40
+
41
+ **Initialization**
42
+
43
+ A PauliList object can be initialized in several ways.
44
+
45
+ ``PauliList(list[str])``
46
+ where strings are same representation with :class:`~qiskit.quantum_info.Pauli`.
47
+
48
+ ``PauliList(Pauli) and PauliList(list[Pauli])``
49
+ where Pauli is :class:`~qiskit.quantum_info.Pauli`.
50
+
51
+ ``PauliList.from_symplectic(z, x, phase)``
52
+ where ``z`` and ``x`` are 2 dimensional boolean ``numpy.ndarrays`` and ``phase`` is
53
+ an integer in ``[0, 1, 2, 3]``.
54
+
55
+ For example,
56
+
57
+ .. plot::
58
+ :include-source:
59
+ :nofigs:
60
+ :context: reset
61
+
62
+ import numpy as np
63
+
64
+ from qiskit.quantum_info import Pauli, PauliList
65
+
66
+ # 1. init from list[str]
67
+ pauli_list = PauliList(["II", "+ZI", "-iYY"])
68
+ print("1. ", pauli_list)
69
+
70
+ pauli1 = Pauli("iXI")
71
+ pauli2 = Pauli("iZZ")
72
+
73
+ # 2. init from Pauli
74
+ print("2. ", PauliList(pauli1))
75
+
76
+ # 3. init from list[Pauli]
77
+ print("3. ", PauliList([pauli1, pauli2]))
78
+
79
+ # 4. init from np.ndarray
80
+ z = np.array([[True, True], [False, False]])
81
+ x = np.array([[False, True], [True, False]])
82
+ phase = np.array([0, 1])
83
+ pauli_list = PauliList.from_symplectic(z, x, phase)
84
+ print("4. ", pauli_list)
85
+
86
+ .. code-block:: text
87
+
88
+ 1. ['II', 'ZI', '-iYY']
89
+ 2. ['iXI']
90
+ 3. ['iXI', 'iZZ']
91
+ 4. ['YZ', '-iIX']
92
+
93
+ **Data Access**
94
+
95
+ The individual Paulis can be accessed and updated using the ``[]``
96
+ operator which accepts integer, lists, or slices for selecting subsets
97
+ of PauliList. If integer is given, it returns Pauli not PauliList.
98
+
99
+ .. plot::
100
+ :include-source:
101
+ :nofigs:
102
+ :context:
103
+
104
+ pauli_list = PauliList(["XX", "ZZ", "IZ"])
105
+ print("Integer: ", repr(pauli_list[1]))
106
+ print("List: ", repr(pauli_list[[0, 2]]))
107
+ print("Slice: ", repr(pauli_list[0:2]))
108
+
109
+ .. code-block:: text
110
+
111
+ Integer: Pauli('ZZ')
112
+ List: PauliList(['XX', 'IZ'])
113
+ Slice: PauliList(['XX', 'ZZ'])
114
+
115
+ **Iteration**
116
+
117
+ Rows in the Pauli table can be iterated over like a list. Iteration can
118
+ also be done using the label or matrix representation of each row using the
119
+ :meth:`label_iter` and :meth:`matrix_iter` methods.
120
+ """
121
+
122
+ # Set the max number of qubits * paulis before string truncation
123
+ __truncate__ = 2000
124
+
125
+ def __init__(self, data: Pauli | list):
126
+ """Initialize the PauliList.
127
+
128
+ Args:
129
+ data (Pauli or list): input data for Paulis. If input is a list each item in the list
130
+ must be a Pauli object or Pauli str.
131
+
132
+ Raises:
133
+ QiskitError: if input array is invalid shape.
134
+
135
+ Additional Information:
136
+ The input array is not copied so multiple Pauli tables
137
+ can share the same underlying array.
138
+ """
139
+ if isinstance(data, BasePauli):
140
+ base_z, base_x, base_phase = data._z, data._x, data._phase
141
+ else:
142
+ # Conversion as iterable of Paulis
143
+ base_z, base_x, base_phase = self._from_paulis(data)
144
+
145
+ # Initialize BasePauli
146
+ super().__init__(base_z, base_x, base_phase)
147
+
148
+ # ---------------------------------------------------------------------
149
+ # Representation conversions
150
+ # ---------------------------------------------------------------------
151
+
152
+ @property
153
+ def settings(self):
154
+ """Return settings."""
155
+ return {"data": self.to_labels()}
156
+
157
+ def __array__(self, dtype=None, copy=None):
158
+ """Convert to numpy array"""
159
+ if copy is False:
160
+ raise ValueError("cannot provide a matrix without calculation")
161
+ shape = (len(self),) + 2 * (2**self.num_qubits,)
162
+ ret = np.zeros(shape, dtype=complex)
163
+ for i, mat in enumerate(self.matrix_iter()):
164
+ ret[i] = mat
165
+ return ret if dtype is None else ret.astype(dtype, copy=False)
166
+
167
+ @staticmethod
168
+ def _from_paulis(data):
169
+ """Construct a PauliList from a list of Pauli data.
170
+
171
+ Args:
172
+ data (iterable): list of Pauli data.
173
+
174
+ Returns:
175
+ PauliList: the constructed PauliList.
176
+
177
+ Raises:
178
+ QiskitError: If the input list is empty or contains invalid
179
+ Pauli strings.
180
+ """
181
+ if not isinstance(data, (list, tuple, set, np.ndarray)):
182
+ data = [data]
183
+ num_paulis = len(data)
184
+ if num_paulis == 0:
185
+ raise QiskitError("Input Pauli list is empty.")
186
+ paulis = []
187
+ for i in data:
188
+ if not isinstance(i, Pauli):
189
+ paulis.append(Pauli(i))
190
+ else:
191
+ paulis.append(i)
192
+ num_qubits = paulis[0].num_qubits
193
+ base_z = np.zeros((num_paulis, num_qubits), dtype=bool)
194
+ base_x = np.zeros((num_paulis, num_qubits), dtype=bool)
195
+ base_phase = np.zeros(num_paulis, dtype=int)
196
+ for i, pauli in enumerate(paulis):
197
+ if pauli.num_qubits != num_qubits:
198
+ raise ValueError(
199
+ f"The {i}th Pauli is defined over {pauli.num_qubits} qubits, "
200
+ f"but num_qubits == {num_qubits} was expected."
201
+ )
202
+ base_z[i] = pauli._z
203
+ base_x[i] = pauli._x
204
+ base_phase[i] = pauli._phase.item()
205
+ return base_z, base_x, base_phase
206
+
207
+ def __repr__(self):
208
+ """Display representation."""
209
+ return self._truncated_str(True)
210
+
211
+ def __str__(self):
212
+ """Print representation."""
213
+ return self._truncated_str(False)
214
+
215
+ def _truncated_str(self, show_class):
216
+ stop = self._num_paulis
217
+ if self.__truncate__ and self.num_qubits > 0:
218
+ max_paulis = self.__truncate__ // self.num_qubits
219
+ if self._num_paulis > max_paulis:
220
+ stop = max_paulis
221
+ labels = [str(self[i]) for i in range(stop)]
222
+ prefix = "PauliList(" if show_class else ""
223
+ tail = ")" if show_class else ""
224
+ if stop != self._num_paulis:
225
+ suffix = ", ...]" + tail
226
+ else:
227
+ suffix = "]" + tail
228
+ list_str = np.array2string(
229
+ np.array(labels), threshold=stop + 1, separator=", ", prefix=prefix, suffix=suffix
230
+ )
231
+ return prefix + list_str[:-1] + suffix
232
+
233
+ def __eq__(self, other):
234
+ """Entrywise comparison of Pauli equality."""
235
+ if not isinstance(other, PauliList):
236
+ other = PauliList(other)
237
+ if not isinstance(other, BasePauli):
238
+ return False
239
+ return self._eq(other)
240
+
241
+ def equiv(self, other: PauliList | Pauli) -> np.ndarray:
242
+ """Entrywise comparison of Pauli equivalence up to global phase.
243
+
244
+ Args:
245
+ other (PauliList or Pauli): a comparison object.
246
+
247
+ Returns:
248
+ np.ndarray: An array of ``True`` or ``False`` for entrywise equivalence
249
+ of the current table.
250
+ """
251
+ if not isinstance(other, PauliList):
252
+ other = PauliList(other)
253
+ return np.all(self.z == other.z, axis=1) & np.all(self.x == other.x, axis=1)
254
+
255
+ # ---------------------------------------------------------------------
256
+ # Direct array access
257
+ # ---------------------------------------------------------------------
258
+ @property
259
+ def phase(self):
260
+ """Return the phase exponent of the PauliList."""
261
+ # Convert internal ZX-phase convention to group phase convention
262
+ return np.mod(self._phase - self._count_y(dtype=self._phase.dtype), 4)
263
+
264
+ @phase.setter
265
+ def phase(self, value):
266
+ # Convert group phase convetion to internal ZX-phase convention
267
+ self._phase[:] = np.mod(value + self._count_y(dtype=self._phase.dtype), 4)
268
+
269
+ @property
270
+ def x(self):
271
+ """The x array for the symplectic representation."""
272
+ return self._x
273
+
274
+ @x.setter
275
+ def x(self, val):
276
+ self._x[:] = val
277
+
278
+ @property
279
+ def z(self):
280
+ """The z array for the symplectic representation."""
281
+ return self._z
282
+
283
+ @z.setter
284
+ def z(self, val):
285
+ self._z[:] = val
286
+
287
+ # ---------------------------------------------------------------------
288
+ # Size Properties
289
+ # ---------------------------------------------------------------------
290
+
291
+ @property
292
+ def shape(self):
293
+ """The full shape of the :meth:`array`"""
294
+ return self._num_paulis, self.num_qubits
295
+
296
+ @property
297
+ def size(self):
298
+ """The number of Pauli rows in the table."""
299
+ return self._num_paulis
300
+
301
+ def __len__(self):
302
+ """Return the number of Pauli rows in the table."""
303
+ return self._num_paulis
304
+
305
+ # ---------------------------------------------------------------------
306
+ # Pauli Array methods
307
+ # ---------------------------------------------------------------------
308
+
309
+ def __getitem__(self, index):
310
+ """Return a view of the PauliList."""
311
+ # Returns a view of specified rows of the PauliList
312
+ # This supports all slicing operations the underlying array supports.
313
+ if isinstance(index, tuple):
314
+ if len(index) == 1:
315
+ index = index[0]
316
+ elif len(index) > 2:
317
+ raise IndexError(f"Invalid PauliList index {index}")
318
+
319
+ # Row-only indexing
320
+ if isinstance(index, (int, np.integer)):
321
+ # Single Pauli
322
+ return Pauli(
323
+ BasePauli(
324
+ self._z[np.newaxis, index],
325
+ self._x[np.newaxis, index],
326
+ self._phase[np.newaxis, index],
327
+ )
328
+ )
329
+ elif isinstance(index, (slice, list, np.ndarray)):
330
+ # Sub-Table view
331
+ return PauliList(BasePauli(self._z[index], self._x[index], self._phase[index]))
332
+
333
+ # Row and Qubit indexing
334
+ return PauliList((self._z[index], self._x[index], 0))
335
+
336
+ def __setitem__(self, index, value):
337
+ """Update PauliList."""
338
+ if isinstance(index, tuple):
339
+ if len(index) == 1:
340
+ row, qubit = index[0], None
341
+ elif len(index) > 2:
342
+ raise IndexError(f"Invalid PauliList index {index}")
343
+ else:
344
+ row, qubit = index
345
+ else:
346
+ row, qubit = index, None
347
+
348
+ # Modify specified rows of the PauliList
349
+ if not isinstance(value, PauliList):
350
+ value = PauliList(value)
351
+
352
+ # It's not valid to set a single item with a sequence, even if the sequence is length 1.
353
+ phase = value._phase.item() if isinstance(row, (int, np.integer)) else value._phase
354
+
355
+ if qubit is None:
356
+ self._z[row] = value._z
357
+ self._x[row] = value._x
358
+ self._phase[row] = phase
359
+ else:
360
+ self._z[row, qubit] = value._z
361
+ self._x[row, qubit] = value._x
362
+ self._phase[row] += phase
363
+ self._phase %= 4
364
+
365
+ def delete(self, ind: int | list, qubit: bool = False) -> PauliList:
366
+ """Return a copy with Pauli rows deleted from table.
367
+
368
+ When deleting qubits the qubit index is the same as the
369
+ column index of the underlying :attr:`X` and :attr:`Z` arrays.
370
+
371
+ Args:
372
+ ind (int or list): index(es) to delete.
373
+ qubit (bool): if ``True`` delete qubit columns, otherwise delete
374
+ Pauli rows (Default: ``False``).
375
+
376
+ Returns:
377
+ PauliList: the resulting table with the entries removed.
378
+
379
+ Raises:
380
+ QiskitError: if ``ind`` is out of bounds for the array size or
381
+ number of qubits.
382
+ """
383
+ if isinstance(ind, int):
384
+ ind = [ind]
385
+ if len(ind) == 0:
386
+ return PauliList.from_symplectic(self._z, self._x, self.phase)
387
+ # Row deletion
388
+ if not qubit:
389
+ if max(ind) >= len(self):
390
+ raise QiskitError(
391
+ f"Indices {ind} are not all less than the size"
392
+ f" of the PauliList ({len(self)})"
393
+ )
394
+ z = np.delete(self._z, ind, axis=0)
395
+ x = np.delete(self._x, ind, axis=0)
396
+ phase = np.delete(self._phase, ind)
397
+
398
+ return PauliList(BasePauli(z, x, phase))
399
+
400
+ # Column (qubit) deletion
401
+ if max(ind) >= self.num_qubits:
402
+ raise QiskitError(
403
+ f"Indices {ind} are not all less than the number of"
404
+ f" qubits in the PauliList ({self.num_qubits})"
405
+ )
406
+ z = np.delete(self._z, ind, axis=1)
407
+ x = np.delete(self._x, ind, axis=1)
408
+ # Use self.phase, not self._phase as deleting qubits can change the
409
+ # ZX phase convention
410
+ return PauliList.from_symplectic(z, x, self.phase)
411
+
412
+ def insert(self, ind: int, value: PauliList, qubit: bool = False) -> PauliList:
413
+ """Insert Paulis into the table.
414
+
415
+ When inserting qubits the qubit index is the same as the
416
+ column index of the underlying :attr:`X` and :attr:`Z` arrays.
417
+
418
+ Args:
419
+ ind (int): index to insert at.
420
+ value (PauliList): values to insert.
421
+ qubit (bool): if ``True`` insert qubit columns, otherwise insert
422
+ Pauli rows (Default: ``False``).
423
+
424
+ Returns:
425
+ PauliList: the resulting table with the entries inserted.
426
+
427
+ Raises:
428
+ QiskitError: if the insertion index is invalid.
429
+ """
430
+ if not isinstance(ind, int):
431
+ raise QiskitError("Insert index must be an integer.")
432
+
433
+ if not isinstance(value, PauliList):
434
+ value = PauliList(value)
435
+
436
+ # Row insertion
437
+ size = self._num_paulis
438
+ if not qubit:
439
+ if ind > size:
440
+ raise QiskitError(
441
+ f"Index {ind} is larger than the number of rows in the" f" PauliList ({size})."
442
+ )
443
+ base_z = np.insert(self._z, ind, value._z, axis=0)
444
+ base_x = np.insert(self._x, ind, value._x, axis=0)
445
+ base_phase = np.insert(self._phase, ind, value._phase)
446
+ return PauliList(BasePauli(base_z, base_x, base_phase))
447
+
448
+ # Column insertion
449
+ if ind > self.num_qubits:
450
+ raise QiskitError(
451
+ f"Index {ind} is greater than number of qubits"
452
+ f" in the PauliList ({self.num_qubits})"
453
+ )
454
+ if len(value) == size:
455
+ # Blocks are already correct size
456
+ value_x = value.x
457
+ value_z = value.z
458
+ elif len(value) == 1:
459
+ # Pad blocks to correct size
460
+ value_x = np.vstack(size * [value.x])
461
+ value_z = np.vstack(size * [value.z])
462
+ else:
463
+ # Blocks are incorrect size
464
+ raise QiskitError(
465
+ "Input PauliList must have a single row, or"
466
+ " the same number of rows as the Pauli Table"
467
+ f" ({size})."
468
+ )
469
+ # Build new array by blocks
470
+ z = np.hstack([self.z[:, :ind], value_z, self.z[:, ind:]])
471
+ x = np.hstack([self.x[:, :ind], value_x, self.x[:, ind:]])
472
+ phase = self.phase + value.phase
473
+
474
+ return PauliList.from_symplectic(z, x, phase)
475
+
476
+ def argsort(self, weight: bool = False, phase: bool = False) -> np.ndarray:
477
+ """Return indices for sorting the rows of the table.
478
+
479
+ The default sort method is lexicographic sorting by qubit number.
480
+ By using the `weight` kwarg the output can additionally be sorted
481
+ by the number of non-identity terms in the Pauli, where the set of
482
+ all Paulis of a given weight are still ordered lexicographically.
483
+
484
+ Args:
485
+ weight (bool): Optionally sort by weight if ``True`` (Default: ``False``).
486
+ phase (bool): Optionally sort by phase before weight or order
487
+ (Default: ``False``).
488
+
489
+ Returns:
490
+ array: the indices for sorting the table.
491
+ """
492
+ # Get order of each Pauli using
493
+ # I => 0, X => 1, Y => 2, Z => 3
494
+ x = self.x
495
+ z = self.z
496
+ order = 1 * (x & ~z) + 2 * (x & z) + 3 * (~x & z)
497
+ phases = self.phase
498
+ # Optionally get the weight of Pauli
499
+ # This is the number of non identity terms
500
+ if weight:
501
+ weights = np.sum(x | z, axis=1)
502
+
503
+ # To preserve ordering between successive sorts we
504
+ # are use the 'stable' sort method
505
+ indices = np.arange(self._num_paulis)
506
+
507
+ # Initial sort by phases
508
+ sort_inds = phases.argsort(kind="stable")
509
+ indices = indices[sort_inds]
510
+ order = order[sort_inds]
511
+ if phase:
512
+ phases = phases[sort_inds]
513
+ if weight:
514
+ weights = weights[sort_inds]
515
+
516
+ # Sort by order
517
+ for i in range(self.num_qubits):
518
+ sort_inds = order[:, i].argsort(kind="stable")
519
+ order = order[sort_inds]
520
+ indices = indices[sort_inds]
521
+ if weight:
522
+ weights = weights[sort_inds]
523
+ if phase:
524
+ phases = phases[sort_inds]
525
+
526
+ # If using weights we implement a sort by total number
527
+ # of non-identity Paulis
528
+ if weight:
529
+ sort_inds = weights.argsort(kind="stable")
530
+ indices = indices[sort_inds]
531
+ phases = phases[sort_inds]
532
+
533
+ # If sorting by phase we perform a final sort by the phase value
534
+ # of each pauli
535
+ if phase:
536
+ indices = indices[phases.argsort(kind="stable")]
537
+ return indices
538
+
539
+ def sort(self, weight: bool = False, phase: bool = False) -> PauliList:
540
+ """Sort the rows of the table.
541
+
542
+ The default sort method is lexicographic sorting by qubit number.
543
+ By using the `weight` kwarg the output can additionally be sorted
544
+ by the number of non-identity terms in the Pauli, where the set of
545
+ all Paulis of a given weight are still ordered lexicographically.
546
+
547
+ **Example**
548
+
549
+ Consider sorting all a random ordering of all 2-qubit Paulis
550
+
551
+ .. plot::
552
+ :include-source:
553
+ :nofigs:
554
+
555
+ from numpy.random import shuffle
556
+ from qiskit.quantum_info.operators import PauliList
557
+
558
+ # 2-qubit labels
559
+ labels = ['II', 'IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ',
560
+ 'YI', 'YX', 'YY', 'YZ', 'ZI', 'ZX', 'ZY', 'ZZ']
561
+ # Shuffle Labels
562
+ shuffle(labels)
563
+ pt = PauliList(labels)
564
+ print('Initial Ordering')
565
+ print(pt)
566
+
567
+ # Lexicographic Ordering
568
+ srt = pt.sort()
569
+ print('Lexicographically sorted')
570
+ print(srt)
571
+
572
+ # Weight Ordering
573
+ srt = pt.sort(weight=True)
574
+ print('Weight sorted')
575
+ print(srt)
576
+
577
+ .. code-block:: text
578
+
579
+ Initial Ordering
580
+ ['YX', 'ZZ', 'XZ', 'YI', 'YZ', 'II', 'XX', 'XI', 'XY', 'YY', 'IX', 'IZ',
581
+ 'ZY', 'ZI', 'ZX', 'IY']
582
+ Lexicographically sorted
583
+ ['II', 'IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ', 'YI', 'YX', 'YY', 'YZ',
584
+ 'ZI', 'ZX', 'ZY', 'ZZ']
585
+ Weight sorted
586
+ ['II', 'IX', 'IY', 'IZ', 'XI', 'YI', 'ZI', 'XX', 'XY', 'XZ', 'YX', 'YY',
587
+ 'YZ', 'ZX', 'ZY', 'ZZ']
588
+
589
+ Args:
590
+ weight (bool): optionally sort by weight if ``True`` (Default: ``False``).
591
+ phase (bool): Optionally sort by phase before weight or order
592
+ (Default: ``False``).
593
+
594
+ Returns:
595
+ PauliList: a sorted copy of the original table.
596
+ """
597
+ return self[self.argsort(weight=weight, phase=phase)]
598
+
599
+ def unique(self, return_index: bool = False, return_counts: bool = False) -> PauliList:
600
+ """Return unique Paulis from the table.
601
+
602
+ **Example**
603
+
604
+ .. plot::
605
+ :include-source:
606
+ :nofigs:
607
+
608
+ from qiskit.quantum_info.operators import PauliList
609
+
610
+ pt = PauliList(['X', 'Y', '-X', 'I', 'I', 'Z', 'X', 'iZ'])
611
+ unique = pt.unique()
612
+ print(unique)
613
+
614
+ .. code-block:: text
615
+
616
+ ['X', 'Y', '-X', 'I', 'Z', 'iZ']
617
+
618
+ Args:
619
+ return_index (bool): If ``True``, also return the indices that
620
+ result in the unique array.
621
+ (Default: ``False``)
622
+ return_counts (bool): If ``True``, also return the number of times
623
+ each unique item appears in the table.
624
+
625
+ Returns:
626
+ PauliList: unique
627
+ the table of the unique rows.
628
+
629
+ unique_indices: np.ndarray, optional
630
+ The indices of the first occurrences of the unique values in
631
+ the original array. Only provided if ``return_index`` is ``True``.
632
+
633
+ unique_counts: np.array, optional
634
+ The number of times each of the unique values comes up in the
635
+ original array. Only provided if ``return_counts`` is ``True``.
636
+ """
637
+ # Check if we need to stack the phase array
638
+ if np.any(self._phase != self._phase[0]):
639
+ # Create a single array of Pauli's and phases for calling np.unique on
640
+ # so that we treat different phased Pauli's as unique
641
+ array = np.hstack([self._z, self._x, self.phase.reshape((self.phase.shape[0], 1))])
642
+ else:
643
+ # All Pauli's have the same phase so we only need to sort the array
644
+ array = np.hstack([self._z, self._x])
645
+
646
+ # Get indexes of unique entries
647
+ if return_counts:
648
+ _, index, counts = np.unique(array, return_index=True, return_counts=True, axis=0)
649
+ else:
650
+ _, index = np.unique(array, return_index=True, axis=0)
651
+
652
+ # Sort the index so we return unique rows in the original array order
653
+ sort_inds = index.argsort()
654
+ index = index[sort_inds]
655
+ unique = PauliList(BasePauli(self._z[index], self._x[index], self._phase[index]))
656
+
657
+ # Concatenate return tuples
658
+ ret = (unique,)
659
+ if return_index:
660
+ ret += (index,)
661
+ if return_counts:
662
+ ret += (counts[sort_inds],)
663
+ if len(ret) == 1:
664
+ return ret[0]
665
+ return ret
666
+
667
+ # ---------------------------------------------------------------------
668
+ # BaseOperator methods
669
+ # ---------------------------------------------------------------------
670
+
671
+ def tensor(self, other: PauliList) -> PauliList:
672
+ """Return the tensor product with each Pauli in the list.
673
+
674
+ Args:
675
+ other (PauliList): another PauliList.
676
+
677
+ Returns:
678
+ PauliList: the list of tensor product Paulis.
679
+
680
+ Raises:
681
+ QiskitError: if other cannot be converted to a PauliList, does
682
+ not have either 1 or the same number of Paulis as
683
+ the current list.
684
+ """
685
+ if not isinstance(other, PauliList):
686
+ other = PauliList(other)
687
+ return PauliList(super().tensor(other))
688
+
689
+ def expand(self, other: PauliList) -> PauliList:
690
+ """Return the expand product of each Pauli in the list.
691
+
692
+ Args:
693
+ other (PauliList): another PauliList.
694
+
695
+ Returns:
696
+ PauliList: the list of tensor product Paulis.
697
+
698
+ Raises:
699
+ QiskitError: if other cannot be converted to a PauliList, does
700
+ not have either 1 or the same number of Paulis as
701
+ the current list.
702
+ """
703
+ if not isinstance(other, PauliList):
704
+ other = PauliList(other)
705
+ if len(other) not in [1, len(self)]:
706
+ raise QiskitError(
707
+ "Incompatible PauliLists. Other list must "
708
+ "have either 1 or the same number of Paulis."
709
+ )
710
+ return PauliList(super().expand(other))
711
+
712
+ def compose(
713
+ self,
714
+ other: PauliList,
715
+ qargs: None | list = None,
716
+ front: bool = False,
717
+ inplace: bool = False,
718
+ ) -> PauliList:
719
+ """Return the composition self∘other for each Pauli in the list.
720
+
721
+ Args:
722
+ other (PauliList): another PauliList.
723
+ qargs (None or list): qubits to apply dot product on (Default: ``None``).
724
+ front (bool): If True use `dot` composition method [default: ``False``].
725
+ inplace (bool): If ``True`` update in-place (default: ``False``).
726
+
727
+ Returns:
728
+ PauliList: the list of composed Paulis.
729
+
730
+ Raises:
731
+ QiskitError: if other cannot be converted to a PauliList, does
732
+ not have either 1 or the same number of Paulis as
733
+ the current list, or has the wrong number of qubits
734
+ for the specified ``qargs``.
735
+ """
736
+ if qargs is None:
737
+ qargs = getattr(other, "qargs", None)
738
+ if not isinstance(other, PauliList):
739
+ other = PauliList(other)
740
+ if len(other) not in [1, len(self)]:
741
+ raise QiskitError(
742
+ "Incompatible PauliLists. Other list must "
743
+ "have either 1 or the same number of Paulis."
744
+ )
745
+ return PauliList(super().compose(other, qargs=qargs, front=front, inplace=inplace))
746
+
747
+ def dot(self, other: PauliList, qargs: None | list = None, inplace: bool = False) -> PauliList:
748
+ """Return the composition other∘self for each Pauli in the list.
749
+
750
+ Args:
751
+ other (PauliList): another PauliList.
752
+ qargs (None or list): qubits to apply dot product on (Default: ``None``).
753
+ inplace (bool): If True update in-place (default: ``False``).
754
+
755
+ Returns:
756
+ PauliList: the list of composed Paulis.
757
+
758
+ Raises:
759
+ QiskitError: if other cannot be converted to a PauliList, does
760
+ not have either 1 or the same number of Paulis as
761
+ the current list, or has the wrong number of qubits
762
+ for the specified ``qargs``.
763
+ """
764
+ return self.compose(other, qargs=qargs, front=True, inplace=inplace)
765
+
766
+ def _add(self, other, qargs=None):
767
+ """Append two PauliLists.
768
+
769
+ If ``qargs`` are specified the other operator will be added
770
+ assuming it is identity on all other subsystems.
771
+
772
+ Args:
773
+ other (PauliList): another table.
774
+ qargs (None or list): optional subsystems to add on
775
+ (Default: ``None``)
776
+
777
+ Returns:
778
+ PauliList: the concatenated list ``self`` + ``other``.
779
+ """
780
+ if qargs is None:
781
+ qargs = getattr(other, "qargs", None)
782
+
783
+ if not isinstance(other, PauliList):
784
+ other = PauliList(other)
785
+
786
+ self._op_shape._validate_add(other._op_shape, qargs)
787
+
788
+ base_phase = np.hstack((self._phase, other._phase))
789
+
790
+ if qargs is None or (sorted(qargs) == qargs and len(qargs) == self.num_qubits):
791
+ base_z = np.vstack([self._z, other._z])
792
+ base_x = np.vstack([self._x, other._x])
793
+ else:
794
+ # Pad other with identity and then add
795
+ padded = BasePauli(
796
+ np.zeros((other.size, self.num_qubits), dtype=bool),
797
+ np.zeros((other.size, self.num_qubits), dtype=bool),
798
+ np.zeros(other.size, dtype=int),
799
+ )
800
+ padded = padded.compose(other, qargs=qargs, inplace=True)
801
+ base_z = np.vstack([self._z, padded._z])
802
+ base_x = np.vstack([self._x, padded._x])
803
+
804
+ return PauliList(BasePauli(base_z, base_x, base_phase))
805
+
806
+ def _multiply(self, other):
807
+ """Multiply each Pauli in the list by a phase.
808
+
809
+ Args:
810
+ other (complex or array): a complex number in [1, -1j, -1, 1j]
811
+
812
+ Returns:
813
+ PauliList: the list of Paulis other * self.
814
+
815
+ Raises:
816
+ QiskitError: if the phase is not in the set [1, -1j, -1, 1j].
817
+ """
818
+ return PauliList(super()._multiply(other))
819
+
820
+ def conjugate(self):
821
+ """Return the conjugate of each Pauli in the list."""
822
+ return PauliList(super().conjugate())
823
+
824
+ def transpose(self):
825
+ """Return the transpose of each Pauli in the list."""
826
+ return PauliList(super().transpose())
827
+
828
+ def adjoint(self):
829
+ """Return the adjoint of each Pauli in the list."""
830
+ return PauliList(super().adjoint())
831
+
832
+ def inverse(self):
833
+ """Return the inverse of each Pauli in the list."""
834
+ return PauliList(super().adjoint())
835
+
836
+ # ---------------------------------------------------------------------
837
+ # Utility methods
838
+ # ---------------------------------------------------------------------
839
+
840
+ def commutes(self, other: BasePauli, qargs: list | None = None) -> bool:
841
+ """Return True for each Pauli that commutes with other.
842
+
843
+ Args:
844
+ other (PauliList): another PauliList operator.
845
+ qargs (list): qubits to apply dot product on (default: ``None``).
846
+
847
+ Returns:
848
+ bool: ``True`` if Paulis commute, ``False`` if they anti-commute.
849
+ """
850
+ if qargs is None:
851
+ qargs = getattr(other, "qargs", None)
852
+ if not isinstance(other, BasePauli):
853
+ other = PauliList(other)
854
+ return super().commutes(other, qargs=qargs)
855
+
856
+ def anticommutes(self, other: BasePauli, qargs: list | None = None) -> bool:
857
+ """Return ``True`` if other Pauli that anticommutes with other.
858
+
859
+ Args:
860
+ other (PauliList): another PauliList operator.
861
+ qargs (list): qubits to apply dot product on (default: ``None``).
862
+
863
+ Returns:
864
+ bool: ``True`` if Paulis anticommute, ``False`` if they commute.
865
+ """
866
+ return np.logical_not(self.commutes(other, qargs=qargs))
867
+
868
+ def commutes_with_all(self, other: PauliList) -> np.ndarray:
869
+ """Return indexes of rows that commute ``other``.
870
+
871
+ If ``other`` is a multi-row Pauli list the returned vector indexes rows
872
+ of the current PauliList that commute with *all* Paulis in other.
873
+ If no rows satisfy the condition the returned array will be empty.
874
+
875
+ Args:
876
+ other (PauliList): a single Pauli or multi-row PauliList.
877
+
878
+ Returns:
879
+ array: index array of the commuting rows.
880
+ """
881
+ return self._commutes_with_all(other)
882
+
883
+ def anticommutes_with_all(self, other: PauliList) -> np.ndarray:
884
+ """Return indexes of rows that commute other.
885
+
886
+ If ``other`` is a multi-row Pauli list the returned vector indexes rows
887
+ of the current PauliList that anti-commute with *all* Paulis in other.
888
+ If no rows satisfy the condition the returned array will be empty.
889
+
890
+ Args:
891
+ other (PauliList): a single Pauli or multi-row PauliList.
892
+
893
+ Returns:
894
+ array: index array of the anti-commuting rows.
895
+ """
896
+ return self._commutes_with_all(other, anti=True)
897
+
898
+ def _commutes_with_all(self, other, anti=False):
899
+ """Return row indexes that commute with all rows in another PauliList.
900
+
901
+ Args:
902
+ other (PauliList): a PauliList.
903
+ anti (bool): if ``True`` return rows that anti-commute, otherwise
904
+ return rows that commute (Default: ``False``).
905
+
906
+ Returns:
907
+ array: index array of commuting or anti-commuting row.
908
+ """
909
+ if not isinstance(other, PauliList):
910
+ other = PauliList(other)
911
+ comms = self.commutes(other[0])
912
+ (inds,) = np.where(comms == int(not anti))
913
+ for pauli in other[1:]:
914
+ comms = self[inds].commutes(pauli)
915
+ (new_inds,) = np.where(comms == int(not anti))
916
+ if new_inds.size == 0:
917
+ # No commuting rows
918
+ return new_inds
919
+ inds = inds[new_inds]
920
+ return inds
921
+
922
+ def evolve(
923
+ self,
924
+ other: Pauli | Clifford | QuantumCircuit,
925
+ qargs: list | None = None,
926
+ frame: Literal["h", "s"] = "h",
927
+ ) -> Pauli:
928
+ r"""Performs either Heisenberg (default) or Schrödinger picture
929
+ evolution of the Pauli by a Clifford and returns the evolved Pauli.
930
+
931
+ Schrödinger picture evolution can be chosen by passing parameter ``frame='s'``.
932
+ This option yields a faster calculation.
933
+
934
+ Heisenberg picture evolves the Pauli as :math:`P^\prime = C^\dagger.P.C`.
935
+
936
+ Schrödinger picture evolves the Pauli as :math:`P^\prime = C.P.C^\dagger`.
937
+
938
+ Args:
939
+ other (Pauli or Clifford or QuantumCircuit): The Clifford operator to evolve by.
940
+ qargs (list): a list of qubits to apply the Clifford to.
941
+ frame (string): ``'h'`` for Heisenberg (default) or ``'s'`` for Schrödinger framework.
942
+
943
+ Returns:
944
+ PauliList: the Pauli :math:`C^\dagger.P.C` (Heisenberg picture)
945
+ or the Pauli :math:`C.P.C^\dagger` (Schrödinger picture).
946
+
947
+ Raises:
948
+ QiskitError: if the Clifford number of qubits and qargs don't match.
949
+ """
950
+ from qiskit.circuit import Instruction
951
+
952
+ if qargs is None:
953
+ qargs = getattr(other, "qargs", None)
954
+
955
+ if not isinstance(other, (BasePauli, Instruction, QuantumCircuit, Clifford)):
956
+ # Convert to a PauliList
957
+ other = PauliList(other)
958
+
959
+ return PauliList(super().evolve(other, qargs=qargs, frame=frame))
960
+
961
+ def to_labels(self, array: bool = False):
962
+ r"""Convert a PauliList to a list Pauli string labels.
963
+
964
+ For large PauliLists converting using the ``array=True``
965
+ kwarg will be more efficient since it allocates memory for
966
+ the full Numpy array of labels in advance.
967
+
968
+ .. list-table:: Pauli Representations
969
+ :header-rows: 1
970
+
971
+ * - Label
972
+ - Symplectic
973
+ - Matrix
974
+ * - ``"I"``
975
+ - :math:`[0, 0]`
976
+ - :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}`
977
+ * - ``"X"``
978
+ - :math:`[1, 0]`
979
+ - :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}`
980
+ * - ``"Y"``
981
+ - :math:`[1, 1]`
982
+ - :math:`\begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}`
983
+ * - ``"Z"``
984
+ - :math:`[0, 1]`
985
+ - :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}`
986
+
987
+ Args:
988
+ array (bool): return a Numpy array if ``True``, otherwise
989
+ return a list (Default: ``False``).
990
+
991
+ Returns:
992
+ list or array: The rows of the PauliList in label form.
993
+ """
994
+ if (self.phase == 1).any():
995
+ prefix_len = 2
996
+ elif (self.phase > 0).any():
997
+ prefix_len = 1
998
+ else:
999
+ prefix_len = 0
1000
+ str_len = self.num_qubits + prefix_len
1001
+ ret = np.zeros(self.size, dtype=f"<U{str_len}")
1002
+ iterator = self.label_iter()
1003
+ for i in range(self.size):
1004
+ ret[i] = next(iterator)
1005
+ if array:
1006
+ return ret
1007
+ return ret.tolist()
1008
+
1009
+ def to_matrix(self, sparse: bool = False, array: bool = False) -> list:
1010
+ r"""Convert to a list or array of Pauli matrices.
1011
+
1012
+ For large PauliLists converting using the ``array=True``
1013
+ kwarg will be more efficient since it allocates memory a full
1014
+ rank-3 Numpy array of matrices in advance.
1015
+
1016
+ .. list-table:: Pauli Representations
1017
+ :header-rows: 1
1018
+
1019
+ * - Label
1020
+ - Symplectic
1021
+ - Matrix
1022
+ * - ``"I"``
1023
+ - :math:`[0, 0]`
1024
+ - :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}`
1025
+ * - ``"X"``
1026
+ - :math:`[1, 0]`
1027
+ - :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}`
1028
+ * - ``"Y"``
1029
+ - :math:`[1, 1]`
1030
+ - :math:`\begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}`
1031
+ * - ``"Z"``
1032
+ - :math:`[0, 1]`
1033
+ - :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}`
1034
+
1035
+ Args:
1036
+ sparse (bool): if ``True`` return sparse CSR matrices, otherwise
1037
+ return dense Numpy arrays (Default: ``False``).
1038
+ array (bool): return as rank-3 numpy array if ``True``, otherwise
1039
+ return a list of Numpy arrays (Default: ``False``).
1040
+
1041
+ Returns:
1042
+ list: A list of dense Pauli matrices if ``array=False` and ``sparse=False`.
1043
+ list: A list of sparse Pauli matrices if ``array=False`` and ``sparse=True``.
1044
+ array: A dense rank-3 array of Pauli matrices if ``array=True``.
1045
+ """
1046
+ if not array:
1047
+ # We return a list of Numpy array matrices
1048
+ return list(self.matrix_iter(sparse=sparse))
1049
+ # For efficiency we also allow returning a single rank-3
1050
+ # array where first index is the Pauli row, and second two
1051
+ # indices are the matrix indices
1052
+ dim = 2**self.num_qubits
1053
+ ret = np.zeros((self.size, dim, dim), dtype=complex)
1054
+ iterator = self.matrix_iter(sparse=sparse)
1055
+ for i in range(self.size):
1056
+ ret[i] = next(iterator)
1057
+ return ret
1058
+
1059
+ # ---------------------------------------------------------------------
1060
+ # Custom Iterators
1061
+ # ---------------------------------------------------------------------
1062
+
1063
+ def label_iter(self):
1064
+ """Return a label representation iterator.
1065
+
1066
+ This is a lazy iterator that converts each row into the string
1067
+ label only as it is used. To convert the entire table to labels use
1068
+ the :meth:`to_labels` method.
1069
+
1070
+ Returns:
1071
+ LabelIterator: label iterator object for the PauliList.
1072
+ """
1073
+
1074
+ class LabelIterator(CustomIterator):
1075
+ """Label representation iteration and item access."""
1076
+
1077
+ def __repr__(self):
1078
+ return f"<PauliList_label_iterator at {hex(id(self))}>"
1079
+
1080
+ def __getitem__(self, key):
1081
+ return self.obj._to_label(self.obj._z[key], self.obj._x[key], self.obj._phase[key])
1082
+
1083
+ return LabelIterator(self)
1084
+
1085
+ def matrix_iter(self, sparse: bool = False):
1086
+ """Return a matrix representation iterator.
1087
+
1088
+ This is a lazy iterator that converts each row into the Pauli matrix
1089
+ representation only as it is used. To convert the entire table to
1090
+ matrices use the :meth:`to_matrix` method.
1091
+
1092
+ Args:
1093
+ sparse (bool): optionally return sparse CSR matrices if ``True``,
1094
+ otherwise return Numpy array matrices
1095
+ (Default: ``False``)
1096
+
1097
+ Returns:
1098
+ MatrixIterator: matrix iterator object for the PauliList.
1099
+ """
1100
+
1101
+ class MatrixIterator(CustomIterator):
1102
+ """Matrix representation iteration and item access."""
1103
+
1104
+ def __repr__(self):
1105
+ return f"<PauliList_matrix_iterator at {hex(id(self))}>"
1106
+
1107
+ def __getitem__(self, key):
1108
+ return self.obj._to_matrix(
1109
+ self.obj._z[key], self.obj._x[key], self.obj._phase[key], sparse=sparse
1110
+ )
1111
+
1112
+ return MatrixIterator(self)
1113
+
1114
+ # ---------------------------------------------------------------------
1115
+ # Class methods
1116
+ # ---------------------------------------------------------------------
1117
+
1118
+ @classmethod
1119
+ def from_symplectic(
1120
+ cls, z: np.ndarray, x: np.ndarray, phase: np.ndarray | None = 0
1121
+ ) -> PauliList:
1122
+ """Construct a PauliList from a symplectic data.
1123
+
1124
+ Args:
1125
+ z (np.ndarray): 2D boolean Numpy array.
1126
+ x (np.ndarray): 2D boolean Numpy array.
1127
+ phase (np.ndarray or None): Optional, 1D integer array from Z_4.
1128
+
1129
+ Returns:
1130
+ PauliList: the constructed PauliList.
1131
+ """
1132
+ if isinstance(phase, np.ndarray) and np.ndim(phase) > 1:
1133
+ raise ValueError(f"phase should be at most 1D but has {np.ndim(phase)} dimensions.")
1134
+ base_z, base_x, base_phase = cls._from_array(z, x, phase)
1135
+ return cls(BasePauli(base_z, base_x, base_phase))
1136
+
1137
+ def _noncommutation_graph(self, qubit_wise):
1138
+ """Create an edge list representing the non-commutation graph (Pauli Graph).
1139
+
1140
+ An edge (i, j) is present if i and j are not commutable.
1141
+
1142
+ Args:
1143
+ qubit_wise (bool): whether the commutation rule is applied to the whole operator,
1144
+ or on a per-qubit basis.
1145
+
1146
+ Returns:
1147
+ list[tuple[int,int]]: A list of pairs of indices of the PauliList that are not commutable.
1148
+ """
1149
+ # convert a Pauli operator into int vector where {I: 0, X: 2, Y: 3, Z: 1}
1150
+ mat1 = np.array(
1151
+ [op.z + 2 * op.x for op in self],
1152
+ dtype=np.int8,
1153
+ )
1154
+ mat2 = mat1[:, None]
1155
+ # This is 0 (false-y) iff one of the operators is the identity and/or both operators are the
1156
+ # same. In other cases, it is non-zero (truth-y).
1157
+ qubit_anticommutation_mat = (mat1 * mat2) * (mat1 - mat2)
1158
+ # 'adjacency_mat[i, j]' is True iff Paulis 'i' and 'j' do not commute in the given strategy.
1159
+ if qubit_wise:
1160
+ adjacency_mat = np.logical_or.reduce(qubit_anticommutation_mat, axis=2)
1161
+ else:
1162
+ # Don't commute if there's an odd number of element-wise anti-commutations.
1163
+ adjacency_mat = np.logical_xor.reduce(qubit_anticommutation_mat, axis=2)
1164
+ # Convert into list where tuple elements are non-commuting operators. We only want to
1165
+ # results from one triangle to avoid symmetric duplications.
1166
+ return list(zip(*np.where(np.triu(adjacency_mat, k=1))))
1167
+
1168
+ def noncommutation_graph(self, qubit_wise: bool) -> rx.PyGraph:
1169
+ """Create the non-commutation graph of this PauliList.
1170
+
1171
+ This transforms the measurement operator grouping problem into graph coloring problem. The
1172
+ constructed graph contains one node for each Pauli. The nodes will be connecting for any two
1173
+ Pauli terms that do _not_ commute.
1174
+
1175
+ Args:
1176
+ qubit_wise (bool): whether the commutation rule is applied to the whole operator,
1177
+ or on a per-qubit basis.
1178
+
1179
+ Returns:
1180
+ rustworkx.PyGraph: the non-commutation graph with nodes for each Pauli and edges
1181
+ indicating a non-commutation relation. Each node will hold the index of the Pauli
1182
+ term it corresponds to in its data. The edges of the graph hold no data.
1183
+ """
1184
+ edges = self._noncommutation_graph(qubit_wise)
1185
+ graph = rx.PyGraph()
1186
+ graph.add_nodes_from(range(self.size))
1187
+ graph.add_edges_from_no_data(edges)
1188
+ return graph
1189
+
1190
+ def _commuting_groups(self, qubit_wise: bool) -> dict[int, list[int]]:
1191
+ """Partition a PauliList into sets of commuting Pauli strings.
1192
+
1193
+ This is the internal logic of the public ``PauliList.group_commuting`` method which returns
1194
+ a mapping of colors to Pauli indices. The same logic is re-used by
1195
+ ``SparsePauliOp.group_commuting``.
1196
+
1197
+ Args:
1198
+ qubit_wise (bool): whether the commutation rule is applied to the whole operator,
1199
+ or on a per-qubit basis.
1200
+
1201
+ Returns:
1202
+ dict[int, list[int]]: Dictionary of color indices mapping to a list of Pauli indices.
1203
+ """
1204
+ graph = self.noncommutation_graph(qubit_wise)
1205
+ # Keys in coloring_dict are nodes, values are colors
1206
+ coloring_dict = rx.graph_greedy_color(graph)
1207
+ groups = defaultdict(list)
1208
+ for idx, color in coloring_dict.items():
1209
+ groups[color].append(idx)
1210
+ return groups
1211
+
1212
+ def group_qubit_wise_commuting(self) -> list[PauliList]:
1213
+ """Partition a PauliList into sets of mutually qubit-wise commuting Pauli strings.
1214
+
1215
+ Returns:
1216
+ list[PauliList]: List of PauliLists where each PauliList contains commutable Pauli operators.
1217
+ """
1218
+ return self.group_commuting(qubit_wise=True)
1219
+
1220
+ def group_commuting(self, qubit_wise: bool = False) -> list[PauliList]:
1221
+ """Partition a PauliList into sets of commuting Pauli strings.
1222
+
1223
+ Args:
1224
+ qubit_wise (bool): whether the commutation rule is applied to the whole operator,
1225
+ or on a per-qubit basis. For example:
1226
+
1227
+ .. plot::
1228
+ :include-source:
1229
+ :nofigs:
1230
+
1231
+ >>> from qiskit.quantum_info import PauliList
1232
+ >>> op = PauliList(["XX", "YY", "IZ", "ZZ"])
1233
+ >>> op.group_commuting()
1234
+ [PauliList(['XX', 'YY']), PauliList(['IZ', 'ZZ'])]
1235
+ >>> op.group_commuting(qubit_wise=True)
1236
+ [PauliList(['XX']), PauliList(['YY']), PauliList(['IZ', 'ZZ'])]
1237
+
1238
+ Returns:
1239
+ list[PauliList]: List of PauliLists where each PauliList contains commuting Pauli operators.
1240
+ """
1241
+ groups = self._commuting_groups(qubit_wise)
1242
+ return [self[group] for group in groups.values()]