qiskit 1.0.2__cp38-abi3-macosx_11_0_arm64.whl → 1.1.0rc1__cp38-abi3-macosx_11_0_arm64.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 (247) hide show
  1. qiskit/VERSION.txt +1 -1
  2. qiskit/__init__.py +27 -16
  3. qiskit/_accelerate.abi3.so +0 -0
  4. qiskit/_numpy_compat.py +73 -0
  5. qiskit/assembler/disassemble.py +5 -6
  6. qiskit/circuit/__init__.py +1131 -169
  7. qiskit/circuit/_classical_resource_map.py +7 -6
  8. qiskit/circuit/_utils.py +18 -8
  9. qiskit/circuit/annotated_operation.py +21 -0
  10. qiskit/circuit/barrier.py +10 -13
  11. qiskit/circuit/bit.py +0 -1
  12. qiskit/circuit/classical/__init__.py +2 -2
  13. qiskit/circuit/classical/expr/__init__.py +39 -5
  14. qiskit/circuit/classical/expr/constructors.py +84 -1
  15. qiskit/circuit/classical/expr/expr.py +83 -13
  16. qiskit/circuit/classical/expr/visitors.py +83 -0
  17. qiskit/circuit/commutation_checker.py +86 -51
  18. qiskit/circuit/controlflow/_builder_utils.py +9 -1
  19. qiskit/circuit/controlflow/break_loop.py +8 -22
  20. qiskit/circuit/controlflow/builder.py +116 -1
  21. qiskit/circuit/controlflow/continue_loop.py +8 -22
  22. qiskit/circuit/controlflow/control_flow.py +47 -8
  23. qiskit/circuit/controlflow/for_loop.py +8 -23
  24. qiskit/circuit/controlflow/if_else.py +13 -27
  25. qiskit/circuit/controlflow/switch_case.py +14 -21
  26. qiskit/circuit/controlflow/while_loop.py +9 -23
  27. qiskit/circuit/controlledgate.py +2 -2
  28. qiskit/circuit/delay.py +7 -5
  29. qiskit/circuit/gate.py +20 -7
  30. qiskit/circuit/instruction.py +31 -30
  31. qiskit/circuit/instructionset.py +9 -22
  32. qiskit/circuit/library/__init__.py +8 -2
  33. qiskit/circuit/library/arithmetic/integer_comparator.py +2 -2
  34. qiskit/circuit/library/arithmetic/quadratic_form.py +3 -2
  35. qiskit/circuit/library/blueprintcircuit.py +29 -7
  36. qiskit/circuit/library/data_preparation/state_preparation.py +6 -5
  37. qiskit/circuit/library/generalized_gates/diagonal.py +5 -4
  38. qiskit/circuit/library/generalized_gates/isometry.py +51 -254
  39. qiskit/circuit/library/generalized_gates/pauli.py +2 -2
  40. qiskit/circuit/library/generalized_gates/permutation.py +4 -1
  41. qiskit/circuit/library/generalized_gates/rv.py +15 -11
  42. qiskit/circuit/library/generalized_gates/uc.py +2 -98
  43. qiskit/circuit/library/generalized_gates/unitary.py +9 -4
  44. qiskit/circuit/library/hamiltonian_gate.py +11 -5
  45. qiskit/circuit/library/n_local/efficient_su2.py +5 -5
  46. qiskit/circuit/library/n_local/n_local.py +100 -49
  47. qiskit/circuit/library/n_local/two_local.py +3 -59
  48. qiskit/circuit/library/overlap.py +3 -3
  49. qiskit/circuit/library/phase_oracle.py +1 -1
  50. qiskit/circuit/library/quantum_volume.py +39 -38
  51. qiskit/circuit/library/standard_gates/equivalence_library.py +50 -0
  52. qiskit/circuit/library/standard_gates/global_phase.py +4 -2
  53. qiskit/circuit/library/standard_gates/i.py +1 -2
  54. qiskit/circuit/library/standard_gates/iswap.py +1 -2
  55. qiskit/circuit/library/standard_gates/multi_control_rotation_gates.py +11 -5
  56. qiskit/circuit/library/standard_gates/p.py +31 -15
  57. qiskit/circuit/library/standard_gates/r.py +4 -3
  58. qiskit/circuit/library/standard_gates/rx.py +7 -4
  59. qiskit/circuit/library/standard_gates/rxx.py +4 -3
  60. qiskit/circuit/library/standard_gates/ry.py +7 -4
  61. qiskit/circuit/library/standard_gates/ryy.py +4 -3
  62. qiskit/circuit/library/standard_gates/rz.py +7 -4
  63. qiskit/circuit/library/standard_gates/rzx.py +4 -3
  64. qiskit/circuit/library/standard_gates/rzz.py +4 -3
  65. qiskit/circuit/library/standard_gates/s.py +4 -8
  66. qiskit/circuit/library/standard_gates/t.py +2 -4
  67. qiskit/circuit/library/standard_gates/u.py +16 -11
  68. qiskit/circuit/library/standard_gates/u1.py +6 -2
  69. qiskit/circuit/library/standard_gates/u2.py +4 -2
  70. qiskit/circuit/library/standard_gates/u3.py +9 -5
  71. qiskit/circuit/library/standard_gates/x.py +22 -11
  72. qiskit/circuit/library/standard_gates/xx_minus_yy.py +4 -3
  73. qiskit/circuit/library/standard_gates/xx_plus_yy.py +7 -5
  74. qiskit/circuit/library/standard_gates/z.py +1 -2
  75. qiskit/circuit/measure.py +4 -1
  76. qiskit/circuit/operation.py +13 -8
  77. qiskit/circuit/parameter.py +11 -6
  78. qiskit/circuit/quantumcircuit.py +864 -128
  79. qiskit/circuit/quantumcircuitdata.py +2 -2
  80. qiskit/circuit/reset.py +5 -2
  81. qiskit/circuit/store.py +95 -0
  82. qiskit/compiler/assembler.py +22 -22
  83. qiskit/compiler/transpiler.py +63 -112
  84. qiskit/converters/circuit_to_dag.py +7 -0
  85. qiskit/converters/circuit_to_dagdependency_v2.py +47 -0
  86. qiskit/converters/circuit_to_gate.py +2 -0
  87. qiskit/converters/circuit_to_instruction.py +22 -0
  88. qiskit/converters/dag_to_circuit.py +4 -0
  89. qiskit/converters/dag_to_dagdependency_v2.py +44 -0
  90. qiskit/dagcircuit/collect_blocks.py +15 -10
  91. qiskit/dagcircuit/dagcircuit.py +434 -124
  92. qiskit/dagcircuit/dagdependency.py +19 -12
  93. qiskit/dagcircuit/dagdependency_v2.py +641 -0
  94. qiskit/dagcircuit/dagdepnode.py +19 -16
  95. qiskit/dagcircuit/dagnode.py +14 -4
  96. qiskit/primitives/__init__.py +12 -8
  97. qiskit/primitives/backend_estimator.py +3 -5
  98. qiskit/primitives/backend_estimator_v2.py +410 -0
  99. qiskit/primitives/backend_sampler_v2.py +287 -0
  100. qiskit/primitives/base/base_estimator.py +4 -9
  101. qiskit/primitives/base/base_sampler.py +2 -2
  102. qiskit/primitives/containers/__init__.py +5 -4
  103. qiskit/primitives/containers/bit_array.py +292 -2
  104. qiskit/primitives/containers/data_bin.py +123 -50
  105. qiskit/primitives/containers/estimator_pub.py +10 -3
  106. qiskit/primitives/containers/observables_array.py +2 -2
  107. qiskit/primitives/containers/pub_result.py +1 -1
  108. qiskit/primitives/containers/sampler_pub.py +19 -3
  109. qiskit/primitives/containers/sampler_pub_result.py +74 -0
  110. qiskit/primitives/containers/shape.py +1 -1
  111. qiskit/primitives/statevector_estimator.py +4 -4
  112. qiskit/primitives/statevector_sampler.py +7 -12
  113. qiskit/providers/__init__.py +17 -18
  114. qiskit/providers/backend.py +2 -2
  115. qiskit/providers/backend_compat.py +8 -10
  116. qiskit/providers/basic_provider/basic_provider_tools.py +67 -31
  117. qiskit/providers/basic_provider/basic_simulator.py +81 -21
  118. qiskit/providers/fake_provider/fake_1q.py +1 -1
  119. qiskit/providers/fake_provider/fake_backend.py +3 -408
  120. qiskit/providers/fake_provider/generic_backend_v2.py +26 -14
  121. qiskit/providers/provider.py +16 -0
  122. qiskit/pulse/builder.py +4 -1
  123. qiskit/pulse/parameter_manager.py +60 -4
  124. qiskit/pulse/schedule.py +29 -13
  125. qiskit/pulse/utils.py +61 -20
  126. qiskit/qasm2/__init__.py +1 -5
  127. qiskit/qasm2/parse.py +1 -4
  128. qiskit/qasm3/__init__.py +42 -5
  129. qiskit/qasm3/ast.py +19 -0
  130. qiskit/qasm3/exporter.py +178 -106
  131. qiskit/qasm3/printer.py +27 -5
  132. qiskit/qpy/__init__.py +247 -13
  133. qiskit/qpy/binary_io/circuits.py +216 -47
  134. qiskit/qpy/binary_io/schedules.py +42 -36
  135. qiskit/qpy/binary_io/value.py +201 -22
  136. qiskit/qpy/common.py +1 -1
  137. qiskit/qpy/exceptions.py +20 -0
  138. qiskit/qpy/formats.py +29 -0
  139. qiskit/qpy/type_keys.py +21 -0
  140. qiskit/quantum_info/analysis/distance.py +3 -3
  141. qiskit/quantum_info/analysis/make_observable.py +2 -1
  142. qiskit/quantum_info/analysis/z2_symmetries.py +2 -1
  143. qiskit/quantum_info/operators/channel/chi.py +9 -8
  144. qiskit/quantum_info/operators/channel/choi.py +10 -9
  145. qiskit/quantum_info/operators/channel/kraus.py +2 -1
  146. qiskit/quantum_info/operators/channel/ptm.py +10 -9
  147. qiskit/quantum_info/operators/channel/quantum_channel.py +2 -1
  148. qiskit/quantum_info/operators/channel/stinespring.py +2 -1
  149. qiskit/quantum_info/operators/channel/superop.py +12 -11
  150. qiskit/quantum_info/operators/channel/transformations.py +12 -11
  151. qiskit/quantum_info/operators/dihedral/dihedral.py +5 -4
  152. qiskit/quantum_info/operators/operator.py +43 -30
  153. qiskit/quantum_info/operators/scalar_op.py +10 -9
  154. qiskit/quantum_info/operators/symplectic/base_pauli.py +70 -59
  155. qiskit/quantum_info/operators/symplectic/clifford.py +36 -9
  156. qiskit/quantum_info/operators/symplectic/pauli.py +48 -4
  157. qiskit/quantum_info/operators/symplectic/pauli_list.py +36 -14
  158. qiskit/quantum_info/operators/symplectic/random.py +3 -2
  159. qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py +54 -33
  160. qiskit/quantum_info/states/densitymatrix.py +13 -13
  161. qiskit/quantum_info/states/stabilizerstate.py +3 -3
  162. qiskit/quantum_info/states/statevector.py +14 -13
  163. qiskit/quantum_info/states/utils.py +5 -3
  164. qiskit/result/mitigation/correlated_readout_mitigator.py +3 -2
  165. qiskit/result/mitigation/local_readout_mitigator.py +2 -1
  166. qiskit/result/mitigation/utils.py +3 -2
  167. qiskit/synthesis/__init__.py +2 -0
  168. qiskit/synthesis/discrete_basis/commutator_decompose.py +2 -2
  169. qiskit/synthesis/evolution/lie_trotter.py +7 -14
  170. qiskit/synthesis/evolution/qdrift.py +3 -4
  171. qiskit/synthesis/linear/cnot_synth.py +1 -3
  172. qiskit/synthesis/linear/linear_circuits_utils.py +1 -1
  173. qiskit/synthesis/linear_phase/cz_depth_lnn.py +4 -18
  174. qiskit/synthesis/permutation/__init__.py +1 -0
  175. qiskit/synthesis/permutation/permutation_reverse_lnn.py +90 -0
  176. qiskit/synthesis/qft/qft_decompose_lnn.py +2 -6
  177. qiskit/synthesis/two_qubit/two_qubit_decompose.py +165 -954
  178. qiskit/synthesis/two_qubit/xx_decompose/circuits.py +13 -12
  179. qiskit/synthesis/two_qubit/xx_decompose/decomposer.py +7 -1
  180. qiskit/synthesis/unitary/aqc/__init__.py +1 -1
  181. qiskit/synthesis/unitary/aqc/cnot_structures.py +2 -1
  182. qiskit/synthesis/unitary/aqc/fast_gradient/fast_gradient.py +2 -1
  183. qiskit/synthesis/unitary/qsd.py +3 -2
  184. qiskit/transpiler/__init__.py +7 -3
  185. qiskit/transpiler/layout.py +140 -61
  186. qiskit/transpiler/passes/__init__.py +6 -0
  187. qiskit/transpiler/passes/basis/basis_translator.py +7 -2
  188. qiskit/transpiler/passes/basis/unroll_3q_or_more.py +1 -1
  189. qiskit/transpiler/passes/basis/unroll_custom_definitions.py +1 -1
  190. qiskit/transpiler/passes/calibration/rzx_builder.py +2 -1
  191. qiskit/transpiler/passes/layout/apply_layout.py +8 -3
  192. qiskit/transpiler/passes/layout/sabre_layout.py +15 -3
  193. qiskit/transpiler/passes/layout/set_layout.py +1 -1
  194. qiskit/transpiler/passes/optimization/__init__.py +2 -0
  195. qiskit/transpiler/passes/optimization/commutation_analysis.py +2 -2
  196. qiskit/transpiler/passes/optimization/commutative_cancellation.py +1 -1
  197. qiskit/transpiler/passes/optimization/consolidate_blocks.py +1 -1
  198. qiskit/transpiler/passes/optimization/cx_cancellation.py +10 -0
  199. qiskit/transpiler/passes/optimization/elide_permutations.py +114 -0
  200. qiskit/transpiler/passes/optimization/optimize_1q_decomposition.py +9 -3
  201. qiskit/transpiler/passes/optimization/optimize_annotated.py +248 -12
  202. qiskit/transpiler/passes/optimization/remove_final_reset.py +37 -0
  203. qiskit/transpiler/passes/optimization/template_matching/forward_match.py +1 -3
  204. qiskit/transpiler/passes/routing/__init__.py +1 -0
  205. qiskit/transpiler/passes/routing/basic_swap.py +13 -2
  206. qiskit/transpiler/passes/routing/lookahead_swap.py +7 -1
  207. qiskit/transpiler/passes/routing/sabre_swap.py +10 -6
  208. qiskit/transpiler/passes/routing/star_prerouting.py +417 -0
  209. qiskit/transpiler/passes/routing/stochastic_swap.py +24 -8
  210. qiskit/transpiler/passes/scheduling/__init__.py +1 -1
  211. qiskit/transpiler/passes/scheduling/alap.py +1 -2
  212. qiskit/transpiler/passes/scheduling/alignments/align_measures.py +1 -2
  213. qiskit/transpiler/passes/scheduling/alignments/check_durations.py +9 -6
  214. qiskit/transpiler/passes/scheduling/alignments/pulse_gate_validation.py +8 -0
  215. qiskit/transpiler/passes/scheduling/alignments/reschedule.py +13 -4
  216. qiskit/transpiler/passes/scheduling/asap.py +1 -2
  217. qiskit/transpiler/passes/scheduling/base_scheduler.py +21 -2
  218. qiskit/transpiler/passes/scheduling/dynamical_decoupling.py +26 -4
  219. qiskit/transpiler/passes/scheduling/padding/dynamical_decoupling.py +24 -2
  220. qiskit/transpiler/passes/scheduling/time_unit_conversion.py +28 -4
  221. qiskit/transpiler/passes/synthesis/aqc_plugin.py +2 -2
  222. qiskit/transpiler/passes/synthesis/high_level_synthesis.py +120 -13
  223. qiskit/transpiler/passes/synthesis/unitary_synthesis.py +162 -55
  224. qiskit/transpiler/passes/utils/gates_basis.py +3 -3
  225. qiskit/transpiler/passmanager.py +44 -1
  226. qiskit/transpiler/preset_passmanagers/__init__.py +3 -3
  227. qiskit/transpiler/preset_passmanagers/builtin_plugins.py +34 -16
  228. qiskit/transpiler/preset_passmanagers/common.py +4 -6
  229. qiskit/transpiler/preset_passmanagers/plugin.py +9 -1
  230. qiskit/utils/optionals.py +6 -2
  231. qiskit/visualization/array.py +1 -1
  232. qiskit/visualization/bloch.py +2 -3
  233. qiskit/visualization/circuit/matplotlib.py +44 -14
  234. qiskit/visualization/circuit/text.py +38 -18
  235. qiskit/visualization/counts_visualization.py +3 -6
  236. qiskit/visualization/dag_visualization.py +6 -7
  237. qiskit/visualization/pulse_v2/interface.py +8 -3
  238. qiskit/visualization/state_visualization.py +3 -2
  239. qiskit/visualization/timeline/interface.py +18 -8
  240. {qiskit-1.0.2.dist-info → qiskit-1.1.0rc1.dist-info}/METADATA +12 -8
  241. {qiskit-1.0.2.dist-info → qiskit-1.1.0rc1.dist-info}/RECORD +245 -235
  242. {qiskit-1.0.2.dist-info → qiskit-1.1.0rc1.dist-info}/WHEEL +1 -1
  243. qiskit/_qasm2.abi3.so +0 -0
  244. qiskit/_qasm3.abi3.so +0 -0
  245. {qiskit-1.0.2.dist-info → qiskit-1.1.0rc1.dist-info}/LICENSE.txt +0 -0
  246. {qiskit-1.0.2.dist-info → qiskit-1.1.0rc1.dist-info}/entry_points.txt +0 -0
  247. {qiskit-1.0.2.dist-info → qiskit-1.1.0rc1.dist-info}/top_level.txt +0 -0
@@ -10,38 +10,64 @@
10
10
  # copyright notice, and modified files need to carry a notice indicating
11
11
  # that they have been altered from the originals.
12
12
 
13
- """
14
- ========================================
15
- Quantum Circuits (:mod:`qiskit.circuit`)
16
- ========================================
13
+ r"""
14
+ =============================================
15
+ Quantum circuit model (:mod:`qiskit.circuit`)
16
+ =============================================
17
17
 
18
18
  .. currentmodule:: qiskit.circuit
19
19
 
20
- Overview
21
- ========
20
+ The fundamental element of quantum computing is the *quantum circuit*. This is a computational
21
+ routine that can be run, one shot at a time, on a quantum processing unit (QPU). A circuit will act
22
+ on a predefined amount of quantum data (in Qiskit, we only directly support qubits) with unitary
23
+ operations (gates), measurements and resets. In addition, a quantum circuit can contain operations
24
+ on classical data, including real-time computations and control-flow constructs, which are executed
25
+ by the controllers of the QPU.
26
+
27
+ .. note::
28
+
29
+ You may wish to skip the introductory material and jump directly to:
30
+
31
+ * :ref:`the API overview of the whole circuit module <circuit-module-api>`
32
+ * :ref:`the detailed discussion about how circuits are represented <circuit-repr>`
33
+ * the core :class:`QuantumCircuit` class for how to build and query circuits
34
+ * :ref:`information on construction custom instructions <circuit-custom-gates>`
35
+ * :ref:`ways to work with circuit-level objects <circuit-working-with>`
36
+ * :ref:`discussion of Qiskit conventions for circuits, matrices and state labelling
37
+ <circuit-conventions>`
38
+
39
+ Circuits are at a low level of abstraction when building up quantum programs. They are the
40
+ construct that is used to build up to higher levels of abstraction, such as the :ref:`primitives of
41
+ quantum computation <qiskit-primitives>`, which accumulate data from many shots of quantum-circuit
42
+ execution, along with advanced error-mitigation techniques and measurement optimizations, into
43
+ well-typed classical data and error statistics.
44
+
45
+ In Qiskit, circuits can be defined in one of two regimes:
22
46
 
23
- The fundamental element of quantum computing is the **quantum circuit**.
24
- A quantum circuit is a computational routine consisting of coherent quantum
25
- operations on quantum data, such as qubits. It is an ordered sequence of quantum
26
- gates, measurements and resets, which may be conditioned on real-time classical
27
- computation. A set of quantum gates is said to be universal if any unitary
28
- transformation of the quantum data can be efficiently approximated arbitrarily well
29
- as a sequence of gates in the set. Any quantum program can be represented by a
30
- sequence of quantum circuits and classical near-time computation.
47
+ * an *abstract* circuit, which is defined in terms of *virtual qubits* and arbitrary high-level
48
+ operations, like encapsulated algorithms and user-defined gates.
31
49
 
32
- In Qiskit, this core element is represented by the :class:`QuantumCircuit` class.
33
- Below is an example of a quantum circuit that makes a three-qubit GHZ state
50
+ * a *physical* circuit, which is defined in terms of the *hardware qubits* of one particular
51
+ backend, and contains only operations that this backend natively supports. You might also see
52
+ this concept referred to as an *ISA circuit*.
53
+
54
+ You convert from an abstract circuit to a physical circuit by using :ref:`Qiskit's transpilation
55
+ package <qiskit-transpiler>`, of which the top-level access point is :func:`.transpile`.
56
+
57
+ In Qiskit, a quantum circuit is represented by the :class:`QuantumCircuit` class. Below is an
58
+ example of a quantum circuit that makes a three-qubit Greenberger–Horne–Zeilinger (GHZ) state
34
59
  defined as:
35
60
 
36
61
  .. math::
37
62
 
38
- |\\psi\\rangle = \\left(|000\\rangle+|111\\rangle\\right)/\\sqrt{2}
63
+ |\psi\rangle = \left( |000\rangle + |111\rangle \right) / \sqrt{2}
39
64
 
40
65
 
41
66
  .. plot::
42
67
  :include-source:
43
68
 
44
69
  from qiskit import QuantumCircuit
70
+
45
71
  # Create a circuit with a register of three qubits
46
72
  circ = QuantumCircuit(3)
47
73
  # H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
@@ -54,81 +80,852 @@ defined as:
54
80
  circ.draw('mpl')
55
81
 
56
82
 
57
- Supplementary Information
58
- =========================
83
+ .. _circuit-definitions:
84
+
85
+ Circuit concepts and definitions
86
+ ================================
87
+
88
+ There is a lot of specialized terminology around quantum circuits. Much of this is common in
89
+ quantum-computing literature, while some is more specific to quantum software packages, and a small
90
+ amount specific to Qiskit. This is an alphabetical listing of some of the important concepts as a
91
+ quick reference, but does not go into detail of the foundational concepts. Consider using the `IBM
92
+ Quantum Learning platform <https://learning.quantum.ibm.com/>`_ if you want to start from the
93
+ beginning.
94
+
95
+ abstract circuit
96
+ A *circuit* defined in terms of abstract mathematical operations and *virtual qubits*. This is
97
+ typically how you think about quantum algorithms; an abstract circuit can be made up of
98
+ completely arbitrary unitary operations, measurements, and potentially *real-time classical
99
+ computation*, with no restrictions about which qubits can interact with each other.
100
+
101
+ You turn an abstract circuit into a *physical circuit* by using :ref:`Qiskit's transpilation
102
+ package <qiskit-transpiler>`.
103
+
104
+ ancilla qubit
105
+ An extra qubit that is used to help implement operations on other qubits, but whose final state
106
+ is not important for the program.
107
+
108
+ circuit
109
+ A computational routine the defines a single execution to be taken on a QPU. This can either be
110
+ an *abstract circuit* or a *physical circuit*.
111
+
112
+ clbit
113
+ A Qiskit-specific abbreviation meaning a single classical bit of data.
114
+
115
+ gate
116
+ A *unitary operation* on one or more qubits.
117
+
118
+ hardware qubit
119
+ The representation of a single qubit on a particular *QPU*. A hardware qubit has some physical
120
+ quantum-mechanical system backing it, such as superconducting circuits; unlike a *virtual
121
+ qubit*, it has particular coupling constraints and only certain gates can be applied to certain
122
+ groups of hardware qubits.
123
+
124
+ Qiskit does not distinguish *logical qubits* from any individual *physical qubits* when talking
125
+ about hardware qubits. A QPU may implement its hardware qubits as logical qubits, where each
126
+ hardware qubit comprises many physical qubits that are controlled and error-corrected opaquely
127
+ to Qiskit by the control electronics. More likely, for near-term applications, a QPU will be
128
+ directly exposing its physical qubits as the hardware qubits for Qiskit to reason about.
129
+
130
+ Both physical and logical qubits will have coupling constraints between them, only permit
131
+ certain quantum operations on them, and have scheduling concerns between them. Qiskit abstracts
132
+ these concerns together in the concept of hardware qubits. In the early days of quantum error
133
+ correction, particular backends may let you access their qubit resources either as high-level
134
+ logical qubits or as low-level physical qubits through Qiskit.
135
+
136
+ instruction set architecture (ISA)
137
+ The abstract model of which operations are available on which sets of *hardware qubits* on one
138
+ particular *QPU*. For example, one QPU may allow :math:`\sqrt X` and :math:`R_Z` operations on
139
+ all single hardware qubits, and :math:`CX` operations on certain pairs of hardware qubits.
140
+
141
+ logical qubit
142
+ A collection of several *physical qubits* that are controlled together by a QPU (from the user's
143
+ perspective) to apply real-time quantum error correction. A logical qubit is a type of
144
+ *hardware qubit* for Qiskit.
145
+
146
+ measurement
147
+ The act of extracting one classical bit of a data from a single qubit state. This is an
148
+ irreversible operation, and usually destroys entanglement and phase coherence between the target
149
+ qubit and the rest of the system.
150
+
151
+ physical circuit
152
+ A *circuit* defined in terms of *hardware qubits* and only the quantum operations available in a
153
+ particular *QPU's* *ISA*. Physical circuits are tied to one particular QPU architecture, and
154
+ will not run on other incompatible architectures. You may also hear this referred to as an *ISA
155
+ circuit*.
156
+
157
+ You typically get a physical circuit by using :ref:`Qiskit's transpilation routines
158
+ <qiskit-transpiler>` on an *abstract circuit* that you constructed.
159
+
160
+ physical qubit
161
+ A controllable two-level quantum system. This is literally one "physics" qubit, such as a
162
+ transmon or the electronic state of a trapped ion. A QPU may expose this directly as its
163
+ *hardware qubit*, or combine several physical qubits into a *logical qubit*.
164
+
165
+ quantum processing unit (QPU)
166
+ Analogous to a CPU in classical computing or a GPU in graphics processing, a QPU is the hardware
167
+ that runs quantum operations on quantum data. You can always expect a QPU that uses the
168
+ *circuit* model of computation to be able to perform some set of *gates*, and *measurement*
169
+ operations. Depending on the particular technology, they also may be able to run some real-time
170
+ classical computations as well, such as classical control flow and bitwise calculations on
171
+ classical data.
172
+
173
+ qubit
174
+ The basic unit of quantum information.
175
+
176
+ real-time classical computation
177
+ Any classical computation that can happen within the execution of a single shot of a *circuit*,
178
+ where the results of the classical computation can affect later execution of the circuit. The
179
+ amount of real-time classical computation available with particular *QPU*\ s will vary
180
+ significantly dependent on many factors, such as the controlling electronics and the qubit
181
+ technology in use. You should consult your hardware vendor's documentation for more information
182
+ on this.
183
+
184
+ unitary operation
185
+ A reversible operation on a quantum state. All quantum *gates* are unitary operations (by
186
+ definition).
187
+
188
+ virtual qubit
189
+ An abstract, mathematical *qubit* used to build an *abstract circuit*. Virtual qubits are how
190
+ one typically thinks about quantum algorithms at a high level; we assume that all quantum gates
191
+ are valid on all virtual qubits, and all virtual qubits are always connected to every other
192
+ virtual qubit.
193
+
194
+ When mapping to hardware, virtual qubits must be assigned to *hardware qubits*. This mapping
195
+ need not be one-to-one. Typically, one virtual qubit will need to be swapped from one hardware
196
+ qubit to another over the course of a circuit execution in order to satisfy coupling constraints
197
+ of the underlying QPU. It is not strictly necessary for all virtual qubits used in a circuit to
198
+ be mapped to a physical qubit at any given point in a *physical circuit*; it could be that a
199
+ virtual qubit is measured (collapsing its state) and then never used again, so a new virtual
200
+ qubit could take its place. Evaluating these conditions to map a virtual circuit to a physical
201
+ circuit is the job of :ref:`Qiskit's transpilation package <qiskit-transpiler>`.
202
+
203
+
204
+ .. _circuit-module-api:
205
+
206
+ API overview of :mod:`qiskit.circuit`
207
+ =====================================
208
+
209
+ All objects here are described in more detail, and in their greater context in the following
210
+ sections. This section provides an overview of the API elements documented here.
211
+
212
+ ..
213
+ TODO: actually write the "in-depth section on building circuits and cross-ref to it.
214
+
215
+ The principal class is :class:`.QuantumCircuit`, which has its own documentation page, including
216
+ an in-depth section on building circuits. Quantum data and the simplest classical data are
217
+ represented by "bits" and "registers":
218
+
219
+ * :class:`Bit`, an atom of data
220
+ * :class:`Qubit`
221
+ * :class:`Clbit`
222
+ * :class:`AncillaQubit`
223
+
224
+ * :class:`Register`, a collection of bits
225
+ * :class:`QuantumRegister`
226
+ * :class:`ClassicalRegister`
227
+ * :class:`AncillaRegister`
228
+
229
+ Within a circuit, each complete :class:`CircuitInstruction` is made up of an :class:`Operation`
230
+ (which might be an :class:`Instruction`, a :class:`Gate`, or some other subclass) and the qubit
231
+ and clbit operands. The core base classes here are:
232
+
233
+ * :class:`CircuitInstruction`, an operation and its operands
234
+ * :class:`InstructionSet`, a temporary handle to a slice of circuit data
235
+ * :class:`Operation`, any abstract mathematical object or hardware instruction
236
+ * :class:`AnnotatedOperation`, a subclass with applied abstract modifiers
237
+ * :class:`InverseModifier`
238
+ * :class:`ControlModifier`
239
+ * :class:`PowerModifier`
240
+
241
+ The most common concrete subclass of the minimal, abstract :class:`Operation` interface is the
242
+ :class:`Instruction`. While :class:`Operation` can include abstract mathematical objects,
243
+ an :class:`Instruction` is something that could conceivably run directly on hardware. This is in
244
+ turn subclassed by :class:`Gate` and :class:`ControlledGate` that further add unitarity and
245
+ controlled semantics on top:
246
+
247
+ * :class:`Instruction`, representing a hardware-based instruction
248
+ * :class:`Gate`, representing a hardware instruction that is unitary
249
+ * :class:`ControlledGate`, representing a gate with control structure.
250
+
251
+ Qiskit includes a large library of standard gates and circuits, which is documented in
252
+ :mod:`qiskit.circuit.library`. Many of these are declared as Python-object singletons. The
253
+ machinery for this is described in detail in :mod:`qiskit.circuit.singleton`, of which the main
254
+ classes are each a singleton form of the standard instruction–gate hierarchy:
255
+
256
+ * :class:`~singleton.SingletonInstruction`
257
+ * :class:`~singleton.SingletonGate`
258
+ * :class:`~singleton.SingletonControlledGate`
259
+
260
+ Some instructions are particularly special in that they affect the control flow or data flow of the
261
+ circuit. The top-level ones are:
262
+
263
+ * :class:`Barrier`, to mark parts of the circuit that should be optimized independently
264
+ * :class:`Delay`, to insert a real-time wait period
265
+ * :class:`Measure`, to measure a :class:`Qubit` into a :class:`Clbit`
266
+ * :class:`Reset`, to irreversibly reset a qubit to the :math:`\lvert0\rangle` state
267
+ * :class:`Store`, to write a real-time classical expression to a storage location
268
+ * :class:`ControlFlowOp`, which has specific subclasses:
269
+ * :class:`BreakLoopOp`, to break out of the nearest containing loop
270
+ * :class:`ContinueLoopOp`, to move immediately to the next iteration of the containing loop
271
+ * :class:`ForLoopOp`, to loop over a fixed range of values
272
+ * :class:`IfElseOp`, to conditionally enter one of two subcircuits
273
+ * :class:`SwitchCaseOp`, to conditionally enter one of many subcicuits
274
+ * :class:`WhileLoopOp`, to repeat a subcircuit until a condition is falsified.
275
+
276
+ :ref:`Circuits can include classical expressions that are evaluated in real time
277
+ <circuit-repr-real-time-classical>`, while the QPU is executing a single shot of the circuit. These
278
+ are primarily documented in the module documentation of :mod:`qiskit.circuit.classical`. You might
279
+ be particularly interested in the base classes (which are not exposed from the :mod:`qiskit.circuit`
280
+ root):
281
+
282
+ * :class:`~classical.expr.Var`, a typed classical storage location in a circuit
283
+ * :class:`~classical.expr.Expr`, a real-time-evaluated expression
284
+ * :class:`~classical.types.Type`, the classical type of an expression.
285
+
286
+ In addition to this real-time expression evaluation, which is limited by classical hardware
287
+ representations of data, Qiskit has the concept of "compile-time" parametrization, which is done in
288
+ abstract symbolic algebra. These are typically used to represent gate angles in high-level
289
+ algorithms that might want to perform numerical derivatives, but they are an older part of Qiskit
290
+ than the real-time evaluation, so are still used in some places to do general parametrization. The
291
+ main related classes are:
292
+
293
+ * :class:`Parameter`, the atom of compile-time expressions
294
+ * :class:`ParameterExpression`, a symbolic calculation on parameters
295
+ * :class:`ParameterVector`, a convenience collection of many :class:`Parameter`\ s
296
+
297
+ The :mod:`qiskit.circuit` module also exposes some calculation classes that work with circuits to
298
+ assist compilation workflows. These include:
59
299
 
60
- Quantum Circuit with conditionals
61
- ---------------------------------
300
+ * :class:`EquivalenceLibrary`, a database of decomposition relations between gates and circuits
301
+ * :data:`SessionEquivalenceLibrary`, a mutable instance of :class:`EquivalenceLibrary` which is used
302
+ by default by the compiler's :class:`.BasisTranslator`.
62
303
 
63
- When building a quantum circuit, there can be interest in applying a certain gate only
64
- if a classical register has a specific value. This can be done with the
65
- :meth:`InstructionSet.c_if` method.
304
+ There is also a utility for generating random circuits:
305
+
306
+ * :func:`random.random_circuit`
307
+
308
+ Finally, the circuit module has its own exception class, to indicate when things went wrong in
309
+ circuit-specific manners:
310
+
311
+ * :exc:`CircuitError`
312
+
313
+
314
+ .. _circuit-repr:
315
+
316
+ Representation of circuits in Qiskit
317
+ ====================================
318
+
319
+ The main user-facing class for representing circuits is :class:`QuantumCircuit`. This can be either
320
+ an abstract circuit or a physical circuit. There is much more information about the
321
+ :class:`QuantumCircuit` class itself and the multitude of available methods on it in its class
322
+ documentation.
323
+
324
+ ..
325
+ TODO: the intention is to replace this `autosummary` directive with a proper entry in the API
326
+ toctree once the `QuantumCircuit` class-level documentation has been completely rewritten into
327
+ more of this style. For now, this just ensures it gets *any* page generated.
66
328
 
67
- In the following example, we start with a single-qubit circuit formed by only a Hadamard gate
68
- (:class:`~.HGate`), in which we expect to get :math:`|0\\rangle` and :math:`|1\\rangle`
69
- with equal probability.
329
+ .. autosummary::
330
+ :toctree: ../stubs/
331
+
332
+ QuantumCircuit
333
+
334
+ Internally, a :class:`QuantumCircuit` contains the qubits, classical bits, compile-time parameters,
335
+ real-time variables, and other tracking information about the data it acts on and how it is
336
+ parametrized. It then contains a sequence of :class:`CircuitInstruction`\ s, which contain
337
+ the particular operation (gate, measurement, etc) and its operands (the qubits and classical bits).
338
+
339
+
340
+ Bits and registers
341
+ ------------------
342
+
343
+ Qubits and classical bits are represented by a shared base :class:`Bit` type, which is just intended
344
+ to be a "type tag"; the classes have no behavior other than being immutable objects:
345
+
346
+ .. autoclass:: Bit
347
+ .. autoclass:: Qubit
348
+ :show-inheritance:
349
+ :class-doc-from: class
350
+ .. autoclass:: Clbit
351
+ :show-inheritance:
352
+ :class-doc-from: class
353
+
354
+ Qubits and clbits are instantiated by users with no arguments, such as by ``Qubit()``. Bits compare
355
+ equal if they are the same Python object, or if they were both created by a register of the same
356
+ name and size, and they refer to the same index within that register. There is also a special type
357
+ tag for "ancilla" qubits, but this is little used in the current state
358
+ of Qiskit:
359
+
360
+ .. autoclass:: AncillaQubit
361
+ :show-inheritance:
362
+ :class-doc-from: class
363
+
364
+ A collection bits of the same type can be encapsulated in a register of the matching type. The base
365
+ functionality is in a base class that is not directly instantiated:
366
+
367
+ .. autoclass:: Register
368
+ :members:
369
+
370
+ Each of the defined bit subtypes has an associated register, which have the same constructor
371
+ signatures, methods and properties as the base class:
372
+
373
+ .. autoclass:: QuantumRegister
374
+ :show-inheritance:
375
+ :class-doc-from: class
376
+ .. autoclass:: ClassicalRegister
377
+ :show-inheritance:
378
+ :class-doc-from: class
379
+ .. autoclass:: AncillaRegister
380
+ :show-inheritance:
381
+ :class-doc-from: class
382
+
383
+ A common way to instantiate several bits at once is to create a register, such as by
384
+ ``QuantumRegister("my_qreg", 5)``. This has the advantage that you can give that collection of bits
385
+ a name, which will appear during circuit visualizations (:meth:`QuantumCircuit.draw`) and exports to
386
+ interchange languages (see :mod:`.qasm2` and :mod:`.qasm3`). You can also pass a name and a list of
387
+ pre-constructed bits, but this creates an "aliasing register", which are very poorly supported on
388
+ hardware.
389
+
390
+ Circuits track registers, but registers themselves impart almost no behavioral differences on
391
+ circuits. The only exception is that :class:`ClassicalRegister`\ s can be implicitly cast to
392
+ unsigned integers for use in conditional comparisons of :ref:`control flow operations
393
+ <circuit-control-flow>`.
394
+
395
+ Classical registers and bits were the original way of representing classical data in Qiskit, and
396
+ remain the most supported currently. Longer term, the data model is moving towards a more complete
397
+ and strongly typed representation of a range of classical data (see
398
+ :ref:`circuit-repr-real-time-classical`), but you will still very commonly use classical bits in
399
+ current Qiskit.
400
+
401
+
402
+ Instruction contexts
403
+ --------------------
70
404
 
71
- .. plot::
72
- :include-source:
405
+ The scalar type of the :attr:`QuantumCircuit.data` sequence is the "instruction context" object,
406
+ :class:`CircuitInstruction`. This is essentially just a data class that contains a representation
407
+ of what is to be done (its :attr:`~CircuitInstruction.operation`), and the data it acts on (the
408
+ :attr:`~CircuitInstruction.qubits` and :attr:`~CircuitInstruction.clbits`).
73
409
 
74
- from qiskit import transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
75
- qr = QuantumRegister(1)
76
- cr = ClassicalRegister(1)
77
- qc = QuantumCircuit(qr, cr)
78
- qc.h(0)
79
- qc.measure(0, 0)
80
- qc.draw('mpl')
410
+ .. autosummary::
411
+ :toctree: ../stubs/
81
412
 
82
- .. code-block::
413
+ CircuitInstruction
83
414
 
84
- from qiskit.providers.basic_provider import BasicSimulator
85
- backend = BasicSimulator()
86
- tqc = transpile(qc, backend)
87
- counts = backend.run(tqc).result().get_counts()
415
+ Programmatically, this class is actually implemented in Rust and is a constructed handle to internal
416
+ data within Rust space. Mutations to instances of this class will not be reflected in the circuit.
417
+ In general, you cannot mutate instruction contexts that are already in the circuit directly; the
418
+ :class:`QuantumCircuit` interface is designed for storing and building circuits, while the
419
+ :ref:`transpiler and its passes <qiskit-transpiler>`, and its intermediate :class:`.DAGCircuit`
420
+ representation, are where you should look for an interface to mutate circuits.
88
421
 
89
- print(counts)
422
+ The :class:`QuantumCircuit` methods that add instructions to circuits (such as
423
+ :meth:`~QuantumCircuit.append`, and all the helper standard-gate methods) return an
424
+ :class:`InstructionSet`, which is a handle to several :class:`CircuitInstruction`\ s simultaneously.
90
425
 
91
- .. parsed-literal::
426
+ .. autosummary::
427
+ :toctree: ../stubs/
92
428
 
93
- {'0': 524, '1': 500}
429
+ InstructionSet
94
430
 
95
- Now, we add an :class:`~.XGate` only if the value of the :class:`~.ClassicalRegister` is 0.
96
- That way, if the state is :math:`|0\\rangle`, it will be changed to :math:`|1\\rangle` and
97
- if the state is :math:`|1\\rangle`, it will not be changed at all, so the final state will
98
- always be :math:`|1\\rangle`.
431
+ This :class:`InstructionSet` is now little used in Qiskit. It provides a very minimal set of
432
+ methods to perform post-append mutations on instructions (which *will* be propagated to the
433
+ circuit), but these are now discouraged and you should use the alternatives noted in those methods.
99
434
 
100
- .. plot::
101
- :include-source:
102
435
 
103
- from qiskit import transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
436
+ Operations, instructions and gates
437
+ ----------------------------------
104
438
 
105
- qr = QuantumRegister(1)
106
- cr = ClassicalRegister(1)
107
- qc = QuantumCircuit(qr, cr)
108
- qc.h(0)
109
- qc.measure(0, 0)
439
+ Within a :class:`CircuitInstruction`, the minimal interface that any operation must fulfill is
440
+ :class:`Operation`. This is a *very* high level view, and only usable for abstract circuits. The
441
+ main purpose of treating operations as :class:`Operation` is to allow arbitrary mathematical
442
+ objects (such as :class:`.quantum_info.Operator`) to be added to abstract circuits directly.
110
443
 
111
- qc.x(0).c_if(cr, 0)
112
- qc.measure(0, 0)
444
+ .. autosummary::
445
+ :toctree: ../stubs/
113
446
 
114
- qc.draw('mpl')
447
+ Operation
115
448
 
116
- .. code-block::
449
+ Most operations, including all operations on physical circuits, are instances of the more concretely
450
+ defined :class:`Instruction`. This represents any instruction that some QPU might be able to carry
451
+ out natively, such as :class:`Measure`. :class:`Instruction` need not be unitary (much as
452
+ :class:`Measure` isn't); an instruction is specifically unitary if it is a :class:`Gate`.
453
+
454
+ .. autosummary::
455
+ :toctree: ../stubs/
456
+
457
+ Instruction
458
+
459
+ :class:`Instruction`\ s can be near arbitrary, provided they only act on :class:`Qubit`\ s and
460
+ :class:`Clbit`\ s, and are parametrized by their :attr:`~Instruction.params`; they should not
461
+ attempt to "close over" outer circuit registers, or use hidden parameters inside themselves.
462
+ :class:`Instruction`\ s can be related to other circuits to provide a decompositions by using
463
+ their :attr:`Instruction.definition` attribute, which provides a local, one-off decomposition. This
464
+ can be in whatever basis set of operations is most convenient to you, as long as the definitions of
465
+ all contained gates have some topological order; that is, you cannot use a gate in a definition it
466
+ its own definition depends on the parent. If the :class:`Instruction` should be considered entirely
467
+ opaque to optimizers, its :attr:`~Instruction.definition` can be ``None``. See
468
+ :ref:`circuit-custom-gates` for more detail.
469
+
470
+ The :attr:`~Instruction.params` of an instruction can technically be arbitrary, but in general you
471
+ should attempt to stick to parametrizations in terms of real numbers, wherever possible. Qiskit
472
+ itself breaks this rule in many places, and you will find all sorts of unusual types in
473
+ :attr:`Instruction.params` fields, but these are an annoying source of bugs because they often imply
474
+ the need for type-aware special casing. If your instruction is parametrized in terms of angles, you
475
+ will be able to reliably use :ref:`compile-time parametrization in it
476
+ <circuit-compile-time-parameters>`, and it will integrate well with
477
+ :meth:`QuantumCircuit.assign_parameters`.
478
+
479
+ While :class:`Instruction` is not necessarily unitary, its subclass :class:`Gate` implies unitarity,
480
+ and adds :meth:`~Gate.to_matrix` and :meth:`~Gate.control` methods to all the methods inherited from
481
+ :class:`Instruction`.
117
482
 
118
- from qiskit.providers.basic_provider import BasicSimulator
119
- backend = BasicSimulator()
120
- tqc = transpile(qc, backend)
121
- counts = backend.run(tqc).result().get_counts()
483
+ .. autosummary::
484
+ :toctree: ../stubs/
122
485
 
123
- print(counts)
486
+ Gate
124
487
 
125
- .. parsed-literal::
488
+ :class:`Gate` inherits all the methods for :class:`Instruction` and all the same considerations
489
+ about its :attr:`~Instruction.params` and :attr:`~Instruction.definition` field, except of course
490
+ that :class:`Gate`\ s cannot act on any classical resources.
126
491
 
127
- {'1': 1024}
492
+ :class:`Gate` instances can (and should) have a base :attr:`~Instruction.definition`, but you can
493
+ also specify several different decompositions in different bases by using an
494
+ :class:`EquivalenceLibrary`.
128
495
 
496
+ Subclassing :class:`Gate`, Qiskit has a special :class:`ControlledGate` class as well. This class
497
+ is the base of many standard-library gates that are controlled (such as :class:`CXGate`), which is
498
+ where you are most likely to encounter it:
129
499
 
130
- Quantum Circuit Properties
131
- --------------------------
500
+ .. autosummary::
501
+ :toctree: ../stubs/
502
+
503
+ ControlledGate
504
+
505
+ Each of :class:`Instruction`, :class:`Gate` and :class:`ControlledGate` has a corresponding
506
+ singleton type, built using the machinery described in :mod:`qiskit.circuit.singleton`. The
507
+ module-level documentation contains full details, along with descriptions of
508
+ :class:`.SingletonInstruction`, :class:`.SingletonGate` and :class:`.SingletonControlledGate`. From
509
+ a user's perspective, little changes based on whether the base class is a singleton or not; the
510
+ intention always remains that you should call :meth:`~Instruction.to_mutable` first if you need to
511
+ get a safe-to-mutate owned copy of an instruction (you cannot assume that an arbitrary instruction
512
+ is mutable), and while direct :class:`type` inspection is discouraged, if you do need it, the
513
+ reliable way to find the "base" type of a potentially singleton instruction is to use
514
+ :attr:`~Instruction.base_class`.
515
+
516
+ :class:`ControlledGate` uses the same mechanisms as :ref:`subclassing gates <circuit-custom-gates>`
517
+ to define a fixed, lazy synthesis for itself. This is naturally not hardware-aware, and harder to
518
+ hook into the synthesis routines of the compiler, but works better as a concrete
519
+ :class:`Instruction` that could potentially be run natively on hardware. For cases where synthesis
520
+ and abstract optimization is more important, Qiskit offers a composable class called
521
+ :class:`AnnotatedOperation`, which tracks "gate modifiers" (of which :class:`ControlModifier` is
522
+ one) to apply to the inner :attr:`~AnnotatedOperation.base_op`.
523
+
524
+ .. autosummary::
525
+ :toctree: ../stubs/
526
+
527
+ AnnotatedOperation
528
+
529
+ The available modifiers for :class:`AnnotatedOperation` are:
530
+
531
+ .. autoclass:: InverseModifier
532
+ .. autoclass:: ControlModifier
533
+ .. autoclass:: PowerModifier
534
+
535
+ For information on how to create custom gates and instructions, including how to build one-off
536
+ objects, and re-usable parametric gates via subclassing, see :ref:`circuit-custom-gates` below.
537
+ The Qiskit circuit library in :mod:`qiskit.circuit.library` contains many predefined gates and
538
+ circuits for you to use.
539
+
540
+
541
+ Built-in special instructions
542
+ -----------------------------
543
+
544
+ Qiskit contains a few :class:`Instruction` classes that are in some ways "special". These typically
545
+ have special handling in circuit code, in the transpiler, or the models of hardware. These are all
546
+ generally instructions you might already be familiar with.
547
+
548
+ Measurements in Qiskit are of a single :class:`Qubit` into a single :class:`Clbit`. These are the
549
+ two that the instruction is applied to. Measurements are in the computational basis.
550
+
551
+ .. autoclass:: Measure(label=None)
552
+ :show-inheritance:
553
+
554
+ Related to measurements, there is a :class:`Reset` operation, which produces no classical data but
555
+ instructs hardware to return the qubit to the :math:`\lvert0\rangle` state. This is assumed to
556
+ happen incoherently and to collapse any entanglement.
557
+
558
+ .. autoclass:: Reset(label=None)
559
+ :show-inheritance:
560
+
561
+ Hardware can be instructed to apply a real-time idle period on a given qubit. A scheduled circuit
562
+ (see :mod:`qiskit.transpiler`) will include all the idle times on qubits explicitly in terms of this
563
+ :class:`Delay`.
564
+
565
+ .. autoclass:: Delay
566
+ :show-inheritance:
567
+
568
+ The :class:`Barrier` instruction can span an arbitrary number of qubits and clbits, and is a no-op
569
+ in hardware. During transpilation and optimization, however, it blocks any optimizations from
570
+ "crossing" the barrier; that is, in::
571
+
572
+ from qiskit.circuit import QuantumCircuit
573
+
574
+ qc = QuantumCircuit(1)
575
+ qc.x(0)
576
+ qc.barrier()
577
+ qc.x(0)
578
+
579
+ it is forbidden for the optimizer to cancel out the two :math:`X` instructions.
580
+
581
+ .. autoclass:: Barrier
582
+ :show-inheritance:
583
+
584
+ The :class:`Store` instruction is particularly special, in that it allows writing the result of a
585
+ :ref:`real-time classical computation expression <circuit-repr-real-time-classical>` (an
586
+ :class:`.expr.Expr`) in a local classical variable (a :class:`.expr.Var`). It takes *neither*
587
+ :class:`Qubit` nor :class:`Clbit` operands, but has an explicit :attr:`~Store.lvalue` and
588
+ :attr:`~Store.rvalue`.
589
+
590
+ .. autoclass:: Store
591
+ :show-inheritance:
592
+ :members:
593
+ :no-inherited-members:
594
+
595
+
596
+ .. _circuit-repr-real-time-classical:
597
+
598
+ Real-time classical computation
599
+ -------------------------------
600
+
601
+ .. note::
602
+
603
+ The primary documentation for real-time classical computation is in the module-level
604
+ documentation of :mod:`qiskit.circuit.classical`.
605
+
606
+ You might also want to read about the circuit methods for working with real-time variables on
607
+ the :class:`QuantumCircuit` class page.
608
+
609
+ ..
610
+ TODO: write a section in the QuantumCircuit-level guide about real-time-variable methods and
611
+ cross-ref to it.
612
+
613
+ Qiskit has rudimentary low-level support for representing real-time classical computations, which
614
+ happen during the QPU execution and affect the results. We are still relatively early into hardware
615
+ support for these concepts as well, so beware that you will need to work closely with your hardware
616
+ provider's documentation to get the best use out of any real-time classical computation.
617
+
618
+ These real-time calculations are represented by the expression and type system in
619
+ :mod:`qiskit.circuit.classical`. At a high level, all real-time expressions are represented by an
620
+ :class:`.Expr` node, which is part of an expression "tree" representation, which has a well-defined
621
+ :class:`~.classical.Type` associated with it at every level. See the module-level documentation for
622
+ much more detail on the internal representations of these classes.
623
+
624
+ The result of a real-time :class:`.Expr` can be used directly in certain places. Currently this is
625
+ limited to conditions of :class:`.IfElseOp` and :class:`.WhileLoopOp`, and the target of
626
+ :class:`.SwitchCaseOp`. The result can also be stored in a typed classical storage location, using
627
+ the :class:`.Store` instruction (or its :meth:`QuantumCircuit.store` constructor), backed by a
628
+ :class:`.expr.Var` node.
629
+
630
+ A circuit can contain manual classical storage locations, represented internally by the
631
+ :class:`~.expr.Var` node of the :class:`.Expr` tree. These have an attached classical type (like
632
+ any other expression). These can either be declared and initialized within each execution of the
633
+ circuit (:meth:`~QuantumCircuit.add_var`), or be inputs to the circuit
634
+ (:meth:`~QuantumCircuit.add_input`).
635
+
636
+ .. _circuit-compile-time-parameters:
637
+
638
+ Compile-time parametrization
639
+ ----------------------------
640
+
641
+ Various parametric :class:`Instruction` instances in Qiskit can be parametrized in ways that are
642
+ designed to be resolved at compile time. These are characterized by the use of the
643
+ :class:`Parameter` and :class:`ParameterExpression` classes.
644
+
645
+ .. autosummary::
646
+ :toctree: ../stubs/
647
+
648
+ Parameter
649
+ ParameterExpression
650
+
651
+ The main way that this differs from the :class:`expr.Var` variables used in real-time classical
652
+ computation is that :class:`ParameterExpression` is a symbolic representation of a mathematical
653
+ expression. The semantics of the expression are those of regular mathematics over the continuous
654
+ real numbers (and, in limited cases, over the complex numbers). In contrast, :class:`.Var` is a
655
+ handle to a variable stored on a classical computer, such as a floating-point value or an
656
+ fixed-width integer, which are always discrete.
657
+
658
+ In other words, you can expect :class:`ParameterExpression` to do symbolic simplifications that are
659
+ valid in mathematics, such as simplifying :math:`(x + y - x) / y \to 1`. Such a simplification is
660
+ not valid in floating-point arithmetic, and :class:`.expr.Expr` will not do this.
661
+
662
+ The "compile-time" part of these parameters means that you typically will want to "assign" values to
663
+ the parameters before sending the circuit for execution. These parameters can typically be used
664
+ anywhere that expects a mathematical angle (like a rotation gate's parameters), with the caveat that
665
+ hardware will usually require them to be assigned to a proper classically typed value before
666
+ execution. You can do this assignment using :meth:`QuantumCircuit.assign_parameters`.
667
+
668
+ You may want to use many parameters that are related to each other. To make this easier (and to
669
+ avoid you needing to come up with many names), you can use the convenience constructor
670
+ :class:`ParameterVector`. The elements of the vector are all valid :class:`Parameter` instances.
671
+
672
+ .. autosummary::
673
+ :toctree: ../stubs/
674
+
675
+ ParameterVector
676
+
677
+ .. _circuit-control-flow:
678
+
679
+ Control flow in circuits
680
+ ------------------------
681
+
682
+ Within :class:`QuantumCircuit`, classical control flow is represented by specific
683
+ :class:`Instruction`\ s, which are subclasses of :class:`ControlFlowOp`.
684
+
685
+ .. autosummary::
686
+ :toctree: ../stubs/
687
+
688
+ ControlFlowOp
689
+
690
+ These control-flow operations (:class:`IfElseOp`, :class:`WhileLoopOp`,
691
+ :class:`SwitchCaseOp` and :class:`ForLoopOp`) all have specific state that defines the branching
692
+ conditions and strategies, but contain all the different subcircuit blocks that might be entered in
693
+ their :attr:`~ControlFlowOp.blocks` property.
694
+
695
+ .. autosummary::
696
+ :toctree: ../stubs/
697
+
698
+ IfElseOp
699
+ WhileLoopOp
700
+ SwitchCaseOp
701
+ ForLoopOp
702
+
703
+ The :class:`.SwitchCaseOp` also understands a special value:
704
+
705
+ .. autodata:: CASE_DEFAULT
706
+
707
+ In addition to the block-structure control-flow operations, there are also two special instructions
708
+ that affect the flow of control when within loops. These correspond to typical uses of the
709
+ ``break`` and ``continue`` statements in classical programming languages.
710
+
711
+ .. autosummary::
712
+ :toctree: ../stubs/
713
+
714
+ BreakLoopOp
715
+ ContinueLoopOp
716
+
717
+ .. note::
718
+ The classes representations are documented here, but please note that manually constructing
719
+ these classes is a low-level operation that we do not expect users to need to do frequently.
720
+
721
+ ..
722
+ TODO: make this below statement valid, and reinsert.
723
+
724
+ Users should read :ref:`circuit-creating-control-flow` for the recommended workflows for
725
+ building control-flow-enabled circuits.
726
+
727
+ Since :class:`ControlFlowOp` subclasses are also :class:`Instruction` subclasses, this means that
728
+ the way they are stored in :class:`CircuitInstruction` instances has them "applied" to a sequence of
729
+ qubits and clbits in its :attr:`~CircuitInstruction.qubits` and :attr:`~CircuitInstruction.clbits`
730
+ attributes. This can lead to subtle data-coherence problems: the :class:`Qubit` and :class:`Clbit`
731
+ objects used inside the subcircuit blocks of the control-flow ops will not necessarily be identical
732
+ to the corresponding objects in the :class:`CircuitInstruction`. Any code that consumes
733
+ control-flow operations in Qiskit needs to be aware of this; within a subcircuit, you should treat
734
+ ``subcircuit.qubits[i]`` as if it were really ``outer_instruction.qubits[i]``, and so on. You can
735
+ generate an easy lookup table for this by doing::
736
+
737
+ cf_instruction: CircuitInstruction = ...
738
+ cf_operation: ControlFlowOp = cf_instruction.operation
739
+ for block in blocks:
740
+ # Mappings of "inner" qubits/clbits to the outer ones.
741
+ qubit_map = dict(zip(block.qubits, cf_instruction.qubits))
742
+ clbit_map = dict(zip(block.clbits, cf_instruction.clbits))
743
+
744
+ # ... do something with `block` ...
745
+
746
+ Remember that you will need to propagate this information if you recurse into subblocks of
747
+ control-flow operations.
748
+
749
+ ..
750
+ TODO: insert cross-ref to control-flow builder guide into below paragraph once written.
751
+
752
+ All the subcircuit blocks in a :class:`ControlFlowOp` are required to contain the same numbers of
753
+ :class:`Qubit`\ s and :class:`Clbit`\ s, referring to the same outer bits in the same order, such
754
+ that the :class:`zip` loop given in the code block above works. The inner-circuit :class:`Bit`
755
+ objects do not need to be literally the same objects. When using the control-flow builder interface
756
+ (which, it cannot be stressed enough, is *highly* recommended for users), the builders will arrange
757
+ that the inner bit objects *are* identical to the outer bit objects; the ``qubit_map`` in the code
758
+ block above will always be a mapping ``{x: x}``, but if you are consuming the blocks, you should be
759
+ prepared for the case that the mapping is required.
760
+
761
+ Any :class:`ClassicalRegister`\ s used in a control-flow subcircuit must also be present in all
762
+ containing blocks (*i.e.* any containing control-flow operations, and the outermost circuit), and
763
+ all blocks in the same :class:`ControlFlowOp` need to contain the same registers. Again, the
764
+ builder interface will arrange for this to be the case (or produce an eager error if they cannot).
765
+
766
+ When the low-level construction is being used the inner :class:`QuantumCircuit` blocks must
767
+ manually close over any outer-scope :ref:`real-time classical computation variables
768
+ <circuit-repr-real-time-classical>` that they use. This is marked by these being in the
769
+ :meth:`~QuantumCircuit.iter_captured_vars` iterator for that block. Libraries constructing these
770
+ blocks manually will need to track these captures when building control-flow circuit blocks and add
771
+ them to the block using :meth:`~QuantumCircuit.add_capture` (or the ``captures`` constructor
772
+ argument), but user code will typically use the control-flow builder interface, which handles this
773
+ automatically.
774
+
775
+ ..
776
+ TODO: make the below sentence valid, then re-insert.
777
+
778
+ Consult :ref:`the control-flow construction documentation <circuit-creating-control-flow>` for
779
+ more information on how to build circuits with control flow.
780
+
781
+ .. _circuit-custom-gates:
782
+
783
+ Creating custom instructions
784
+ ============================
785
+
786
+ If you wish to create simple one-off instructions or gates that will be added to a circuit, and the
787
+ blocks are just being used for visualization or grouping purposes, the easiest way to create a
788
+ custom instruction or gate is simply to build its definition as a :class:`QuantumCircuit`, and then
789
+ use its :meth:`~QuantumCircuit.to_instruction` or :meth:`~QuantumCircuit.to_gate` method as
790
+ appropriate. The results can be given directly to :meth:`QuantumCircuit.append` on the larger
791
+ circuit. These methods will create base :class:`Instruction` or :class:`Gate` instances whose
792
+ :attr:`~Instruction.definition` attribute is the circuit as supplied, meaning it will automatically
793
+ be accessible to the transpiler, and to other Qiskit functions that attempt to decompose circuits.
794
+
795
+ Note that standalone instructions and gates should act only on qubits and clbits; instructions that
796
+ need to use complex control-flow will need to be inlined onto the :class:`QuantumCircuit` using
797
+ :meth:`~QuantumCircuit.compose`.
798
+
799
+
800
+ Creating instruction subclasses
801
+ -------------------------------
802
+
803
+ The base classes :class:`Instruction`, :class:`Gate` and :class:`ControlledGate` are all designed to
804
+ be safe to subclass, and have hook points for subclasses to implement. If your custom gate is
805
+ parameterless and stateless, you may also want to derive from the corresponding singleton class in
806
+ :mod:`qiskit.circuit.singleton`, such as :class:`SingletonGate`. You should consult the
807
+ documentation in :mod:`qiskit.circuit.singleton` for additional methods and hook points for the
808
+ singleton machinery.
809
+
810
+ Subclasses should typically define a default constructor that calls the :class`super` constructor
811
+ with the correct arguments for your instruction. It is permissible to have extra state in the
812
+ class, but your subclasses will most reliably integrate with the rest of the Qiskit machinery if you
813
+ depend only on your :attr:`Instruction.params`, and these parameters are purely gate angles.
814
+
815
+ Subclasses of :class:`Instruction` (or one of its subclasses) should implement the private
816
+ :meth:`Instruction._define` method, which lazily populates the hidden ``_definition`` cache that
817
+ backs the public :attr:`~Instruction.definition` method.
818
+
819
+ .. automethod:: Instruction._define
820
+
821
+ In subclasses of :class:`ControlledGate`, the :meth:`~Instruction._define` method should implement
822
+ the decomposition only for the all-ones control state. The :attr:`ControlledGate.definition
823
+ <Instruction.definition>` machinery will modify this to handle the actual control state.
824
+
825
+ If the subclass is using the singleton machinery, beware that :meth:`~Instruction._define` will be
826
+ called eagerly immediately after the class-body statement has been executed, in order to produce the
827
+ definition object for the canonical singleton object. This means that your definition must only use
828
+ gates that are already defined; if you are writing a library with many singleton gates, you will
829
+ have to order your files and imports to ensure that this is possible.
830
+
831
+ Subclasses of :class:`Gate` will also likely wish to override `the Numpy array-protocol instance
832
+ method <https://numpy.org/devdocs/user/basics.interoperability.html#the-array-method>`__,
833
+ ``__array__``. This is used by :meth:`Gate.to_matrix`, and has the signature:
834
+
835
+ .. currentmodule:: None
836
+ .. py:method:: __array__(dtype=None, copy=None)
837
+
838
+ Return a Numpy array representing the gate. This can use the gate's :attr:`~Instruction.params`
839
+ field, and may assume that these are numeric values (assuming the subclass expects that) and not
840
+ :ref:`compile-time parameters <circuit-compile-time-parameters>`.
841
+
842
+ For greatest efficiency, the returned array should default to a dtype of :class:`complex`.
843
+ .. currentmodule:: qiskit.circuit
844
+
845
+ If your custom subclass has natural representations of its controlled or inverse forms, you may also
846
+ wish to override the :meth:`~Instruction.inverse` and :meth:`~Gate.control` methods.
847
+
848
+
849
+ As an example of defining a custom :math:`R_{xz}` gate; that is, a single-angle rotation about the
850
+ :math:`XZ` axis. This is essentially :class:`RZXGate`, if the qubits were the other way around, so
851
+ we will write our definition in terms of that. We are parametric, so cannot be a singleton, but we
852
+ are unitary, so should be a :class:`Gate`::
853
+
854
+ import math
855
+ import numpy as np
856
+ from qiskit.circuit import Gate, QuantumCircuit
857
+
858
+ class RXZGate(Gate):
859
+ def __init__(self, theta):
860
+ # Initialize with our name, number of qubits and parameters.
861
+ super().__init__("rxz", 2, [theta])
862
+
863
+ def _define(self):
864
+ # Our base definition is an RZXGate, applied "backwards".
865
+ defn = QuantumCircuit(2)
866
+ defn.rzx(1, 0)
867
+ self._definition = defn
868
+
869
+ def inverse(self, annotated = False):
870
+ # We have an efficient representation of our inverse,
871
+ # so we'll override this method.
872
+ return RXZGate(-self.params[0])
873
+
874
+ def power(self, exponent: float):
875
+ # Also we have an efficient representation of power.
876
+ return RXZGate(exponent * self.params[0])
877
+
878
+ def __array__(self, dtype=None, copy=None):
879
+ if copy is False:
880
+ raise ValueError("unable to avoid copy while creating an array as requested")
881
+ cos = math.cos(0.5 * self.params[0])
882
+ isin = 1j * math.sin(0.5 * self.params[0])
883
+ return np.array([
884
+ [cos, -isin, 0, 0],
885
+ [-isin, cos, 0, 0],
886
+ [0, 0, cos, isin],
887
+ [0, 0, isin, cos],
888
+ ], dtype=dtype)
889
+
890
+
891
+ In this example, we defined a base definition in terms of :class:`RZXGate`, but to enable faster
892
+ decompositions to a range of bases, we might want to add some more equivalences to
893
+ :data:`SessionEquivalenceLibrary`. Note that the :class:`.BasisTranslator` translation search will
894
+ search through all possible equivalences at all possible depths, so providing an equivalence in
895
+ terms of (say) :class:`.XGate` will automatically make decompositions in terms of :class:`.RXGate`
896
+ available as well.
897
+
898
+ Let us add an equivalence in terms of :math:`H`, :math:`CX` and :math:`R_z` for an arbitrary symbolic
899
+ parameter::
900
+
901
+ from qiskit.circuit import SessionEquivalenceLibrary, Parameter
902
+
903
+ theta = Parameter("theta")
904
+
905
+ equiv = QuantumCircuit(2)
906
+ equiv.h(0)
907
+ equiv.cx(1, 0)
908
+ equiv.rz(theta, 0)
909
+ equiv.cx(1, 0)
910
+ equiv.h(0)
911
+
912
+ SessionEquivalenceLibrary.add_equivalence(RZXGate(theta), equiv)
913
+
914
+ After this, for the duration of the Python interpreter session, translators like
915
+ :class:`.BasisTranslator` will find our new definition in their search.
916
+
917
+
918
+ .. _circuit-working-with:
919
+
920
+ Working with circuit-level objects
921
+ ==================================
922
+
923
+ Circuit properties
924
+ ------------------
925
+
926
+ ..
927
+ TODO: rewrite this section and move it into the `QuantumCircuit` class-level overview of its
928
+ functions.
132
929
 
133
930
  When constructing quantum circuits, there are several properties that help quantify
134
931
  the "size" of the circuits, and their ability to be run on a noisy quantum device.
@@ -229,11 +1026,6 @@ graphically:
229
1026
  .. image:: /source_images/depth.gif
230
1027
 
231
1028
 
232
- .. raw:: html
233
-
234
- <br><br>
235
-
236
-
237
1029
  We can verify our graphical result using :meth:`QuantumCircuit.depth`:
238
1030
 
239
1031
  .. code-block::
@@ -244,145 +1036,313 @@ We can verify our graphical result using :meth:`QuantumCircuit.depth`:
244
1036
 
245
1037
  9
246
1038
 
247
- .. raw:: html
1039
+ .. _circuit-abstract-to-physical:
248
1040
 
249
- <br>
1041
+ Converting abstract circuits to physical circuits
1042
+ -------------------------------------------------
250
1043
 
251
- Quantum Circuit API
252
- ===================
1044
+ ..
1045
+ Note that this is just a "jumping-off" section - this should just provide an overview of links
1046
+ to where the real information is.
253
1047
 
254
- Quantum Circuit Construction
255
- ----------------------------
256
-
257
- .. autosummary::
258
- :toctree: ../stubs/
259
-
260
- QuantumCircuit
261
- QuantumRegister
262
- Qubit
263
- ClassicalRegister
264
- Clbit
265
- AncillaRegister
266
- AncillaQubit
267
- CircuitInstruction
268
- Register
269
- Bit
270
-
271
- Gates and Instructions
272
- ----------------------
273
-
274
- .. autosummary::
275
- :toctree: ../stubs/
1048
+ An abstract :class:`QuantumCircuit` cannot reliably be run on hardware. You might be able to use
1049
+ some of the high-level simulators linked to in :ref:`circuit-simulation` to produce quick results
1050
+ for small scale circuits, but to run utility-scale circuits, you will need to use real hardware,
1051
+ which involves compiling to a physical circuit.
276
1052
 
277
- Gate
278
- ControlledGate
279
- Delay
280
- Instruction
281
- InstructionSet
282
- Operation
283
- EquivalenceLibrary
1053
+ The high-level function to do this is :func:`.transpile`; it takes in an abstract circuit and a
1054
+ hardware ``backend`` or ``target``, and returns a physical circuit. To get more access and control
1055
+ over the stages of the passes that will be run, use :func:`.generate_preset_pass_manager` to build a
1056
+ :class:`~.transpiler.StagedPassManager` first, which you can then modify.
284
1057
 
285
- Annotated Operations
286
- --------------------
1058
+ The full transpilation and compilation machinery is described in detail in the
1059
+ :mod:`qiskit.transpiler` module documentation, and detail on all the passes built into Qiskit is
1060
+ available in :mod:`qiskit.transpiler.passes`.
287
1061
 
288
- .. autosummary::
289
- :toctree: ../stubs/
290
1062
 
1063
+ .. _circuit-simulation:
291
1064
 
292
- AnnotatedOperation
293
- InverseModifier
294
- ControlModifier
295
- PowerModifier
1065
+ Simulating circuits
1066
+ -------------------
296
1067
 
297
- Control Flow Operations
298
- -----------------------
1068
+ ..
1069
+ Note that this is just a "jumping-off" section - this should just provide an overview of links
1070
+ to where the real information is.
299
1071
 
300
- .. autosummary::
301
- :toctree: ../stubs/
302
1072
 
303
- ControlFlowOp
304
- IfElseOp
305
- WhileLoopOp
306
- ForLoopOp
307
- SwitchCaseOp
308
- BreakLoopOp
309
- ContinueLoopOp
1073
+ While not part of the :mod:`qiskit.circuit` interface, one of the most common needs is to get quick
1074
+ simulation results for :class:`QuantumCircuit` objects. This section provides a quick jumping-off
1075
+ point to other places in the documentation to find the relevant information.
310
1076
 
311
- The :class:`.SwitchCaseOp` also understands a special value:
1077
+ For unitary circuits, you can simulate the effects on the :math:`\lvert0\dotsm0\rangle` state by
1078
+ passing the :class:`QuantumCircuit` directly to the :class:`~.quantum_info.Statevector` default
1079
+ constructor. You can similar get a unitary matrix representing the circuit as an operator by
1080
+ passing it to the :class:`~.quantum_info.Operator` default constructor. If you have a physical
1081
+ circuit, you may want to instead pass it to :meth:`.Operator.from_circuit` method to apply
1082
+ transformations from the :attr:`QuantumCircuit.layout` to map it back to the "abstract" qubit space.
312
1083
 
313
- .. py:data:: CASE_DEFAULT
1084
+ For a more backend-like simulation experience, there are simulator-backed implementations of all the
1085
+ Qiskit hardware interfaces. In particular, you might be interested in:
314
1086
 
315
- A special object that represents the "default" case of a switch statement. If you use this as a
316
- case target, it must be the last case, and will match anything that wasn't already matched. For
317
- example::
1087
+ * :class:`.BasicProvider` and the raw backends it can return to you.
1088
+ * :class:`.StatevectorSimulator` for a backend-like wrapper around :class:`.Statevector`
1089
+ * The :mod:`qiskit_aer` for full, high-performance simulation capabilities.
1090
+ * :class:`.StatevectorSampler` and :class:`.StatevectorEstimator` for simulator-backed reference
1091
+ implementations of the :ref:`Qiskit Primitives <qiskit-primitives>`.
318
1092
 
319
- from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
320
- from qiskit.circuit import SwitchCaseOp, CASE_DEFAULT
321
1093
 
322
- body0 = QuantumCircuit(2, 2)
323
- body0.x(0)
324
- body1 = QuantumCircuit(2, 2)
325
- body1.z(0)
326
- body2 = QuantumCircuit(2, 2)
327
- body2.cx(0, 1)
1094
+ Defining equivalence relationships
1095
+ ----------------------------------
328
1096
 
329
- qr, cr = QuantumRegister(2), ClassicalRegister(2)
330
- qc = QuantumCircuit(qr, cr)
331
- qc.switch(cr, [(0, body0), (1, body1), (CASE_DEFAULT, body2)], qr, cr)
1097
+ A common task in mapping abstract circuits to physical hardware and optimizing the result is to find
1098
+ equivalence relations that map a gate to a different basis set. Qiskit stores this information in a
1099
+ database class called :class:`EquivalenceLibrary`.
332
1100
 
333
- When using the builder interface of :meth:`.QuantumCircuit.switch`, this can also be accessed as
334
- the ``DEFAULT`` attribute of the bound case-builder object, such as::
1101
+ .. autosummary::
1102
+ :toctree: ../stubs/
335
1103
 
336
- from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
1104
+ EquivalenceLibrary
337
1105
 
338
- qr, cr = QuantumRegister(2), ClassicalRegister(2)
339
- qc = QuantumCircuit(qr, cr)
340
- with qc.switch(cr) as case:
341
- with case(0):
342
- qc.x(0)
343
- with case(1):
344
- qc.z(0)
345
- with case(case.DEFAULT):
346
- qc.cx(0, 1)
1106
+ Qiskit ships with a large set of predefined equivalence relationships for all of its standard gates.
1107
+ This base library is called :data:`StandardEquivalenceLibrary`, and should be treated as immutable.
347
1108
 
1109
+ .. py:data:: StandardEquivalenceLibrary
348
1110
 
349
- Parametric Quantum Circuits
350
- ---------------------------
1111
+ A :class:`EquivalenceLibrary` that stores of all Qiskit's built-in standard gate relationships.
1112
+ You should not mutate this, but instead either create your own :class:`EquivalenceLibrary` using
1113
+ this one as its ``base``, or modify the global-state :data:`SessionEquivalenceLibrary`.
351
1114
 
352
- .. autosummary::
353
- :toctree: ../stubs/
1115
+ Qiskit also defines a shared global-state object, :data:`SessionEquivalenceLibrary`, which is the
1116
+ default equivalences used by various places in Qiskit, most notably the :class:`.BasisTranslator`
1117
+ transpiler pass. You should feel free to add your own equivalences to this using its
1118
+ :meth:`~EquivalenceLibrary.add_equivalence` method, and they will be automatically picked up by
1119
+ default instances of the :class:`.BasisTranslator`.
354
1120
 
355
- Parameter
356
- ParameterVector
357
- ParameterExpression
1121
+ .. py:data:: SessionEquivalenceLibrary
358
1122
 
359
- Gate Commutation
360
- ----------------
1123
+ The default instance of :class:`EquivalenceLibrary`, which will be used by most Qiskit objects
1124
+ if no library is manually specified. You can feel free to add equivalences to this using
1125
+ :meth:`~EquivalenceLibrary.add_equivalence`. It inherits all the built-in rules of
1126
+ :data:`StandardEquivalenceLibrary`.
361
1127
 
362
- .. autosummary::
363
- :toctree: ../stubs/
364
1128
 
365
- CommutationChecker
366
1129
 
1130
+ Generating random circuits
1131
+ --------------------------
367
1132
 
368
- Random Circuits
369
- ---------------
1133
+ ..
1134
+ If we expand these capabilities in the future, it's probably best to move it to its own
1135
+ module-level documentation page than to expand this "inline" module documentation.
370
1136
 
371
1137
  .. currentmodule:: qiskit.circuit.random
372
1138
  .. autofunction:: random_circuit
373
1139
  .. currentmodule:: qiskit.circuit
374
1140
 
1141
+
375
1142
  Exceptions
376
- ----------
1143
+ ==========
377
1144
 
378
1145
  Almost all circuit functions and methods will raise a :exc:`CircuitError` when encountering an error
379
1146
  that is particular to usage of Qiskit (as opposed to regular typing or indexing problems, which will
380
1147
  typically raise the corresponding standard Python error).
381
1148
 
382
1149
  .. autoexception:: CircuitError
1150
+
1151
+
1152
+ .. _circuit-conventions:
1153
+
1154
+ Circuit conventions
1155
+ ===================
1156
+
1157
+ When constructing circuits out of abstract objects and more concrete matrices, there are several
1158
+ possible conventions around bit-labelling, bit-ordering, and how the abstract tensor product is
1159
+ realized in concrete matrix algebra.
1160
+
1161
+ Qiskit's conventions are:
1162
+
1163
+ * in bitstring representations, bits are labelled with the right-most bit in the string called
1164
+ :math:`0` and the left-most bit in the string of :math:`n` bits called :math:`n - 1`.
1165
+
1166
+ * when using integers as bit-specifier indices in circuit-construction functions, the integer is
1167
+ treated as an index into :attr:`QuantumCircuit.qubits` (or :attr:`~QuantumCircuit.clbits`).
1168
+
1169
+ * when drawing circuits, we put the lowest-index bits on top.
1170
+
1171
+ * in statevector representations, we realize the abstract tensor product as the Kronecker product,
1172
+ and order the arguments to this such that the amplitude of computational-basis state
1173
+ :math:`\lvert x\rangle`, where :math:`x` is the bitstring interpreted as an integer, is at
1174
+ location ``statevector[x]``.
1175
+
1176
+ * when controlling a gate, the control qubit(s) is placed first in the argument list, *e.g.* in the
1177
+ call ``qc.cx(0, 1)``, qubit 0 will be the control and qubit 1 will be the target. Similarly, in
1178
+ the manual call ``qc.append(CXGate(), [0, 1])``, qubit 0 will be the control and qubit 1 will be
1179
+ the target.
1180
+
1181
+ Let us illustrate these conventions with some examples.
1182
+
1183
+ Bit labelling
1184
+ -------------
1185
+
1186
+ Take the circuit:
1187
+
1188
+ .. plot::
1189
+ :include-source:
1190
+ :nofigs:
1191
+ :context:
1192
+ :show-source-link: False
1193
+
1194
+ from qiskit import QuantumCircuit
1195
+
1196
+ qc = QuantumCircuit(5, 5)
1197
+ qc.x(0)
1198
+ qc.x(1)
1199
+ qc.x(4)
1200
+ qc.measure(range(5), range(5))
1201
+
1202
+ This flips the states of qubits 0, 1 and 4 from :math:`\lvert0\rangle` to :math:`\lvert1\rangle`,
1203
+ then measures all qubits :math:`n` into the corresponding clbit :math:`n` using the computational
1204
+ (:math:`Z`) basis. If simulated noiselessly, the bitstring output from this circuit will be
1205
+ :math:`10011` every time; qubits 0, 1, and 4 are flipped, and the "one" values in the bitstring are
1206
+ in the zeroth, first and fourth digits *from the right*.
1207
+
1208
+ In Qiskit, we would write the qubit state immediately before the measurement in ket-notation
1209
+ shorthand as :math:`\lvert10011\rangle`. Note that the ket label matches the classical bitstring,
1210
+ and has the numeric binary value of 19.
1211
+
1212
+ If we draw this circuit, we will see that Qiskit places the zeroth qubit on the top of the circuit
1213
+ drawing:
1214
+
1215
+ .. plot::
1216
+ :include-source:
1217
+ :context:
1218
+ :show-source-link: False
1219
+
1220
+ qc.draw("mpl")
1221
+
1222
+
1223
+ Matrix representations
1224
+ ----------------------
1225
+
1226
+ Statevectors are defined in the convention that for a two-level system, the relationship between
1227
+ abstract representation and matrix representation is such that
1228
+
1229
+ .. math::
1230
+
1231
+ \alpha\lvert0\rangle + \beta\lvert1\rangle
1232
+ \leftrightarrow \begin{pmatrix} \alpha \\ \beta \end{pmatrix}
1233
+
1234
+ where :math:`\alpha` and :math:`\beta` are complex numbers. We store the statevector as a 1D Numpy
1235
+ :class:`~numpy.ndarray` with data ``sv = [alpha, beta]``, *i.e.* ``sv[0] == alpha`` and ``sv[1] ==
1236
+ beta``; note that the indices into the statevector match the ket labels.
1237
+
1238
+ We construct `the tensor product of two qubit states
1239
+ <https://en.wikipedia.org/wiki/Tensor_product>`_ in matrix algebra using `the Kronecker product
1240
+ <https://en.wikipedia.org/wiki/Kronecker_product>`_, with qubit 0 on the right and qubit 1 on the
1241
+ left, such that the :math:`Z` basis state :math:`\lvert x\rangle` (where :math:`x` is the integer
1242
+ interpretation of the bitstring) has its non-zero term in the statevector ``sv`` at ``sv[x]``::
1243
+
1244
+ import numpy
1245
+ from qiskit import QuantumCircuit
1246
+ from qiskit.quantum_info import Statevector
1247
+
1248
+ state_0 = [1, 0] # defined representation of |0>
1249
+ state_1 = [0, 1] # defined representation of |1>
1250
+
1251
+ # Circuit that creates basis state |10011>, where
1252
+ # binary 10011 has the decimal value 19.
1253
+ qc = QuantumCircuit(5)
1254
+ qc.x(0)
1255
+ qc.x(1)
1256
+ qc.x(4)
1257
+ qiskit_sv = Statevector(qc)
1258
+
1259
+ # List index 'n' corresponds to qubit 'n'.
1260
+ individual_states = [
1261
+ state_1,
1262
+ state_1,
1263
+ state_0,
1264
+ state_0,
1265
+ state_1,
1266
+ ]
1267
+ # Start from a scalar.
1268
+ manual_sv = [1]
1269
+ for qubit_state in individual_states:
1270
+ # Each new qubit goes "on the left".
1271
+ manual_sv = numpy.kron(qubit_state, manual_sv)
1272
+
1273
+ # Now `qiskit_sv` and `manual_sv` are the same, and:
1274
+ assert manual_sv[19] == 1
1275
+ assert qiskit_sv[19] == 1
1276
+
1277
+ This feeds through to the matrix representation of operators, and joins with the conventions on bit
1278
+ orders for controlled operators. For example, the matrix form of :class:`.CXGate` is::
1279
+
1280
+ import numpy
1281
+ from qiskit.circuit.library import CXGate
1282
+
1283
+ numpy.array(CXGate())
1284
+
1285
+ .. math::
1286
+
1287
+ \operatorname{array}(CX) =
1288
+ \begin{pmatrix}
1289
+ 1 & 0 & 0 & 0 \\
1290
+ 0 & 0 & 0 & 1 \\
1291
+ 0 & 0 & 1 & 0 \\
1292
+ 0 & 1 & 0 & 0
1293
+ \end{pmatrix}
1294
+
1295
+ This might be different to other matrix representations you have seen for :math:`CX`, but recall
1296
+ that the choice of matrix representation is conventional, and this form matches Qiskit's conventions
1297
+ of *control qubits come first* and *the tensor product is represented such that there is a
1298
+ correspondence between the index of the "one amplitude" and the bitstring value of a state*.
1299
+
1300
+ In the case of multiple controls for a gate, such as for :class:`.CCXGate`, the ``ctrl_state``
1301
+ argument is interpreted as the bitstring value of the control qubits, using the same zero-based
1302
+ labelling conventions. For example, given that the default ``ctrl_state`` is the all-ones
1303
+ bitstring, we can see that the matrix form of :class:`.CCXGate` with ``ctrl_state = 1`` is the same
1304
+ as if we took the all-ones control-state :class:`.CCXGate`, but flipped the value of the higher
1305
+ indexed control qubit on entry and exist to the gate::
1306
+
1307
+ from qiskit import QuantumCircuit
1308
+ from qiskit.quantum_info import Operator
1309
+
1310
+ # Build the natural representation of `CCX` with the
1311
+ # control qubits being `[0, 1]`, relative to the
1312
+ # bitstring state "01", such that qubit 0 must be in |1>
1313
+ # and qubit 1 must be in |0>. The target qubit is 2.
1314
+ ccx_natural = QuantumCircuit(3)
1315
+ ccx_natural.ccx(0, 1, 2, ctrl_state=1)
1316
+
1317
+ # Build the same circuit in terms of the all-ones CCX.
1318
+ # Note that we flip _qubit 1_, because that's the one
1319
+ # that differs from the all-ones state.
1320
+ ccx_relative = QuantumCircuit(3)
1321
+ ccx_relative.x(1)
1322
+ ccx_relative.ccx(0, 1, 2)
1323
+ ccx_relative.x(1)
1324
+
1325
+ assert Operator(ccx_relative) == Operator(ccx_natural)
1326
+
1327
+ In both these cases, the matrix form of :class:`.CCXGate` in ``ctrl_state = 1`` is:
1328
+
1329
+ .. math::
1330
+
1331
+ \operatorname{array}\bigl(CCX(\text{ctrl\_state}=1)\bigr) =
1332
+ \begin{pmatrix}
1333
+ 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
1334
+ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
1335
+ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
1336
+ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
1337
+ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
1338
+ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
1339
+ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
1340
+ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1
1341
+ \end{pmatrix}
383
1342
  """
384
1343
 
385
1344
  from .exceptions import CircuitError
1345
+ from . import _utils
386
1346
  from .quantumcircuit import QuantumCircuit
387
1347
  from .classicalregister import ClassicalRegister, Clbit
388
1348
  from .quantumregister import QuantumRegister, Qubit, AncillaRegister, AncillaQubit
@@ -398,6 +1358,7 @@ from .barrier import Barrier
398
1358
  from .delay import Delay
399
1359
  from .measure import Measure
400
1360
  from .reset import Reset
1361
+ from .store import Store
401
1362
  from .parameter import Parameter
402
1363
  from .parametervector import ParameterVector
403
1364
  from .parameterexpression import ParameterExpression
@@ -406,6 +1367,7 @@ from .equivalence import EquivalenceLibrary
406
1367
  from .bit import Bit
407
1368
  from .register import Register
408
1369
  from . import library
1370
+ from .equivalence_library import StandardEquivalenceLibrary, SessionEquivalenceLibrary
409
1371
  from .commutation_checker import CommutationChecker
410
1372
 
411
1373
  from .controlflow import (