qiskit 1.0.2__cp38-abi3-win32.whl → 1.1.0__cp38-abi3-win32.whl

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