qiskit 1.1.0rc1__cp38-abi3-macosx_10_9_universal2.whl → 1.1.2__cp38-abi3-macosx_10_9_universal2.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.
- qiskit/VERSION.txt +1 -1
- qiskit/_accelerate.abi3.so +0 -0
- qiskit/assembler/__init__.py +5 -10
- qiskit/circuit/__init__.py +21 -153
- qiskit/circuit/_classical_resource_map.py +3 -0
- qiskit/circuit/classical/expr/__init__.py +1 -1
- qiskit/circuit/classical/types/__init__.py +5 -4
- qiskit/circuit/classicalfunction/__init__.py +9 -0
- qiskit/circuit/library/__init__.py +3 -19
- qiskit/circuit/library/data_preparation/pauli_feature_map.py +1 -1
- qiskit/circuit/library/n_local/two_local.py +1 -1
- qiskit/circuit/library/standard_gates/x.py +2 -0
- qiskit/circuit/parameterexpression.py +3 -0
- qiskit/circuit/parametervector.py +22 -16
- qiskit/circuit/quantumcircuit.py +1100 -200
- qiskit/converters/__init__.py +17 -2
- qiskit/dagcircuit/dagcircuit.py +8 -1
- qiskit/passmanager/passmanager.py +11 -11
- qiskit/primitives/__init__.py +15 -9
- qiskit/primitives/containers/__init__.py +1 -0
- qiskit/primitives/containers/bit_array.py +6 -2
- qiskit/primitives/containers/shape.py +3 -3
- qiskit/providers/__init__.py +49 -17
- qiskit/providers/backend.py +0 -6
- qiskit/providers/basic_provider/__init__.py +2 -23
- qiskit/providers/fake_provider/__init__.py +1 -1
- qiskit/providers/fake_provider/generic_backend_v2.py +5 -0
- qiskit/providers/models/__init__.py +2 -2
- qiskit/pulse/builder.py +2 -2
- qiskit/pulse/schedule.py +3 -3
- qiskit/qasm2/parse.py +8 -0
- qiskit/qasm3/exporter.py +2 -2
- qiskit/qobj/converters/pulse_instruction.py +6 -6
- qiskit/qpy/__init__.py +60 -62
- qiskit/qpy/binary_io/value.py +1 -1
- qiskit/quantum_info/operators/symplectic/pauli.py +18 -13
- qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py +8 -4
- qiskit/result/__init__.py +6 -0
- qiskit/scheduler/__init__.py +10 -1
- qiskit/scheduler/methods/__init__.py +1 -8
- qiskit/synthesis/__init__.py +1 -6
- qiskit/synthesis/discrete_basis/generate_basis_approximations.py +1 -1
- qiskit/synthesis/discrete_basis/solovay_kitaev.py +22 -12
- qiskit/transpiler/__init__.py +5 -5
- qiskit/transpiler/layout.py +3 -3
- qiskit/transpiler/passes/__init__.py +4 -2
- qiskit/transpiler/passes/basis/basis_translator.py +2 -2
- qiskit/transpiler/passes/layout/vf2_layout.py +10 -4
- qiskit/transpiler/passes/layout/vf2_utils.py +2 -2
- qiskit/transpiler/passes/optimization/collect_cliffords.py +6 -15
- qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py +8 -1
- qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py +5 -1
- qiskit/transpiler/passes/routing/star_prerouting.py +5 -5
- qiskit/transpiler/passes/synthesis/unitary_synthesis.py +3 -0
- qiskit/transpiler/preset_passmanagers/__init__.py +29 -3
- qiskit/transpiler/target.py +1 -1
- qiskit/utils/__init__.py +3 -2
- qiskit/utils/parallel.py +24 -15
- qiskit/visualization/bloch.py +44 -1
- qiskit/visualization/dag_visualization.py +10 -3
- qiskit/visualization/gate_map.py +9 -1
- qiskit/visualization/pass_manager_visualization.py +9 -9
- qiskit/visualization/pulse_v2/device_info.py +58 -31
- {qiskit-1.1.0rc1.dist-info → qiskit-1.1.2.dist-info}/METADATA +18 -18
- {qiskit-1.1.0rc1.dist-info → qiskit-1.1.2.dist-info}/RECORD +69 -69
- {qiskit-1.1.0rc1.dist-info → qiskit-1.1.2.dist-info}/WHEEL +1 -1
- {qiskit-1.1.0rc1.dist-info → qiskit-1.1.2.dist-info}/LICENSE.txt +0 -0
- {qiskit-1.1.0rc1.dist-info → qiskit-1.1.2.dist-info}/entry_points.txt +0 -0
- {qiskit-1.1.0rc1.dist-info → qiskit-1.1.2.dist-info}/top_level.txt +0 -0
qiskit/circuit/quantumcircuit.py
CHANGED
@@ -45,7 +45,7 @@ from qiskit.circuit.parameter import Parameter
|
|
45
45
|
from qiskit.circuit.exceptions import CircuitError
|
46
46
|
from . import _classical_resource_map
|
47
47
|
from ._utils import sort_parameters
|
48
|
-
from .controlflow import ControlFlowOp
|
48
|
+
from .controlflow import ControlFlowOp, _builder_utils
|
49
49
|
from .controlflow.builder import CircuitScopeInterface, ControlFlowBuilderBlock
|
50
50
|
from .controlflow.break_loop import BreakLoopOp, BreakLoopPlaceholder
|
51
51
|
from .controlflow.continue_loop import ContinueLoopOp, ContinueLoopPlaceholder
|
@@ -106,113 +106,878 @@ ClbitSpecifier = Union[
|
|
106
106
|
BitType = TypeVar("BitType", Qubit, Clbit)
|
107
107
|
|
108
108
|
|
109
|
+
# NOTE:
|
110
|
+
#
|
111
|
+
# If you're adding methods or attributes to `QuantumCircuit`, be sure to update the class docstring
|
112
|
+
# to document them in a suitable place. The class is huge, so we do its documentation manually so
|
113
|
+
# it has at least some amount of organisational structure.
|
114
|
+
|
115
|
+
|
109
116
|
class QuantumCircuit:
|
110
|
-
"""
|
117
|
+
"""Core Qiskit representation of a quantum circuit.
|
118
|
+
|
119
|
+
.. note::
|
120
|
+
For more details setting the :class:`QuantumCircuit` in context of all of the data
|
121
|
+
structures that go with it, how it fits into the rest of the :mod:`qiskit` package, and the
|
122
|
+
different regimes of quantum-circuit descriptions in Qiskit, see the module-level
|
123
|
+
documentation of :mod:`qiskit.circuit`.
|
124
|
+
|
125
|
+
Circuit attributes
|
126
|
+
==================
|
127
|
+
|
128
|
+
:class:`QuantumCircuit` has a small number of public attributes, which are mostly older
|
129
|
+
functionality. Most of its functionality is accessed through methods.
|
130
|
+
|
131
|
+
A small handful of the attributes are intentionally mutable, the rest are data attributes that
|
132
|
+
should be considered immutable.
|
133
|
+
|
134
|
+
========================= ======================================================================
|
135
|
+
Mutable attribute Summary
|
136
|
+
========================= ======================================================================
|
137
|
+
:attr:`global_phase` The global phase of the circuit, measured in radians.
|
138
|
+
:attr:`metadata` Arbitrary user mapping, which Qiskit will preserve through the
|
139
|
+
transpiler, but otherwise completely ignore.
|
140
|
+
:attr:`name` An optional string name for the circuit.
|
141
|
+
========================= ======================================================================
|
142
|
+
|
143
|
+
========================= ======================================================================
|
144
|
+
Immutable data attribute Summary
|
145
|
+
========================= ======================================================================
|
146
|
+
:attr:`ancillas` List of :class:`AncillaQubit`\\ s tracked by the circuit.
|
147
|
+
:attr:`calibrations` Custom user-supplied pulse calibrations for individual instructions.
|
148
|
+
:attr:`cregs` List of :class:`ClassicalRegister`\\ s tracked by the circuit.
|
149
|
+
|
150
|
+
:attr:`clbits` List of :class:`Clbit`\\ s tracked by the circuit.
|
151
|
+
:attr:`data` List of individual :class:`CircuitInstruction`\\ s that make up the
|
152
|
+
circuit.
|
153
|
+
:attr:`duration` Total duration of the circuit, added by scheduling transpiler passes.
|
154
|
+
|
155
|
+
:attr:`layout` Hardware layout and routing information added by the transpiler.
|
156
|
+
:attr:`num_ancillas` The number of ancilla qubits in the circuit.
|
157
|
+
:attr:`num_clbits` The number of clbits in the circuit.
|
158
|
+
:attr:`num_captured_vars` Number of captured real-time classical variables.
|
159
|
+
|
160
|
+
:attr:`num_declared_vars` Number of locally declared real-time classical variables in the outer
|
161
|
+
circuit scope.
|
162
|
+
:attr:`num_input_vars` Number of input real-time classical variables.
|
163
|
+
:attr:`num_parameters` Number of compile-time :class:`Parameter`\\ s in the circuit.
|
164
|
+
:attr:`num_qubits` Number of qubits in the circuit.
|
165
|
+
|
166
|
+
:attr:`num_vars` Total number of real-time classical variables in the outer circuit
|
167
|
+
scope.
|
168
|
+
:attr:`op_start_times` Start times of scheduled operations, added by scheduling transpiler
|
169
|
+
passes.
|
170
|
+
:attr:`parameters` Ordered set-like view of the compile-time :class:`Parameter`\\ s
|
171
|
+
tracked by the circuit.
|
172
|
+
:attr:`qregs` List of :class:`QuantumRegister`\\ s tracked by the circuit.
|
173
|
+
|
174
|
+
:attr:`qubits` List of :class:`Qubit`\\ s tracked by the circuit.
|
175
|
+
:attr:`unit` The unit of the :attr:`duration` field.
|
176
|
+
========================= ======================================================================
|
177
|
+
|
178
|
+
The core attribute is :attr:`data`. This is a sequence-like object that exposes the
|
179
|
+
:class:`CircuitInstruction`\\ s contained in an ordered form. You generally should not mutate
|
180
|
+
this object directly; :class:`QuantumCircuit` is only designed for append-only operations (which
|
181
|
+
should use :meth:`append`). Most operations that mutate circuits in place should be written as
|
182
|
+
transpiler passes (:mod:`qiskit.transpiler`).
|
183
|
+
|
184
|
+
.. autoattribute:: data
|
185
|
+
|
186
|
+
Alongside the :attr:`data`, the :attr:`global_phase` of a circuit can have some impact on its
|
187
|
+
output, if the circuit is used to describe a :class:`.Gate` that may be controlled. This is
|
188
|
+
measured in radians and is directly settable.
|
189
|
+
|
190
|
+
.. autoattribute:: global_phase
|
191
|
+
|
192
|
+
The :attr:`name` of a circuit becomes the name of the :class:`~.circuit.Instruction` or
|
193
|
+
:class:`.Gate` resulting from :meth:`to_instruction` and :meth:`to_gate` calls, which can be
|
194
|
+
handy for visualizations.
|
195
|
+
|
196
|
+
.. autoattribute:: name
|
197
|
+
|
198
|
+
You can attach arbitrary :attr:`metadata` to a circuit. No part of core Qiskit will inspect
|
199
|
+
this or change its behavior based on metadata, but it will be faithfully passed through the
|
200
|
+
transpiler, so you can tag your circuits yourself. When serializing a circuit with QPY (see
|
201
|
+
:mod:`qiskit.qpy`), the metadata will be JSON-serialized and you may need to pass a custom
|
202
|
+
serializer to handle non-JSON-compatible objects within it (see :func:`.qpy.dump` for more
|
203
|
+
detail). This field is ignored during export to OpenQASM 2 or 3.
|
204
|
+
|
205
|
+
.. autoattribute:: metadata
|
206
|
+
|
207
|
+
:class:`QuantumCircuit` exposes data attributes tracking its internal quantum and classical bits
|
208
|
+
and registers. These appear as Python :class:`list`\\ s, but you should treat them as
|
209
|
+
immutable; changing them will *at best* have no effect, and more likely will simply corrupt
|
210
|
+
the internal data of the :class:`QuantumCircuit`.
|
211
|
+
|
212
|
+
.. autoattribute:: qregs
|
213
|
+
.. autoattribute:: cregs
|
214
|
+
.. autoattribute:: qubits
|
215
|
+
.. autoattribute:: ancillas
|
216
|
+
.. autoattribute:: clbits
|
217
|
+
|
218
|
+
The :ref:`compile-time parameters <circuit-compile-time-parameters>` present in instructions on
|
219
|
+
the circuit are available in :attr:`parameters`. This has a canonical order (mostly lexical,
|
220
|
+
except in the case of :class:`.ParameterVector`), which matches the order that parameters will
|
221
|
+
be assigned when using the list forms of :meth:`assign_parameters`, but also supports
|
222
|
+
:class:`set`-like constant-time membership testing.
|
223
|
+
|
224
|
+
.. autoattribute:: parameters
|
225
|
+
|
226
|
+
The storage of any :ref:`manual pulse-level calibrations <circuit-calibrations>` for individual
|
227
|
+
instructions on the circuit is in :attr:`calibrations`. This presents as a :class:`dict`, but
|
228
|
+
should not be mutated directly; use the methods discussed in :ref:`circuit-calibrations`.
|
229
|
+
|
230
|
+
.. autoattribute:: calibrations
|
231
|
+
|
232
|
+
If you have transpiled your circuit, so you have a physical circuit, you can inspect the
|
233
|
+
:attr:`layout` attribute for information stored by the transpiler about how the virtual qubits
|
234
|
+
of the source circuit map to the hardware qubits of your physical circuit, both at the start and
|
235
|
+
end of the circuit.
|
236
|
+
|
237
|
+
.. autoattribute:: layout
|
238
|
+
|
239
|
+
If your circuit was also *scheduled* as part of a transpilation, it will expose the individual
|
240
|
+
timings of each instruction, along with the total :attr:`duration` of the circuit.
|
241
|
+
|
242
|
+
.. autoattribute:: duration
|
243
|
+
.. autoattribute:: unit
|
244
|
+
.. autoattribute:: op_start_times
|
245
|
+
|
246
|
+
Finally, :class:`QuantumCircuit` exposes several simple properties as dynamic read-only numeric
|
247
|
+
attributes.
|
248
|
+
|
249
|
+
.. autoattribute:: num_ancillas
|
250
|
+
.. autoattribute:: num_clbits
|
251
|
+
.. autoattribute:: num_captured_vars
|
252
|
+
.. autoattribute:: num_declared_vars
|
253
|
+
.. autoattribute:: num_input_vars
|
254
|
+
.. autoattribute:: num_parameters
|
255
|
+
.. autoattribute:: num_qubits
|
256
|
+
.. autoattribute:: num_vars
|
257
|
+
|
258
|
+
Creating new circuits
|
259
|
+
=====================
|
260
|
+
|
261
|
+
========================= =====================================================================
|
262
|
+
Method Summary
|
263
|
+
========================= =====================================================================
|
264
|
+
:meth:`__init__` Default constructor of no-instruction circuits.
|
265
|
+
:meth:`copy` Make a complete copy of an existing circuit.
|
266
|
+
:meth:`copy_empty_like` Copy data objects from one circuit into a new one without any
|
267
|
+
instructions.
|
268
|
+
:meth:`from_instructions` Infer data objects needed from a list of instructions.
|
269
|
+
:meth:`from_qasm_file` Legacy interface to :func:`.qasm2.load`.
|
270
|
+
:meth:`from_qasm_str` Legacy interface to :func:`.qasm2.loads`.
|
271
|
+
========================= =====================================================================
|
272
|
+
|
273
|
+
The default constructor (``QuantumCircuit(...)``) produces a circuit with no initial
|
274
|
+
instructions. The arguments to the default constructor can be used to seed the circuit with
|
275
|
+
quantum and classical data storage, and to provide a name, global phase and arbitrary metadata.
|
276
|
+
All of these fields can be expanded later.
|
277
|
+
|
278
|
+
.. automethod:: __init__
|
279
|
+
|
280
|
+
If you have an existing circuit, you can produce a copy of it using :meth:`copy`, including all
|
281
|
+
its instructions. This is useful if you want to keep partial circuits while extending another,
|
282
|
+
or to have a version you can mutate in-place while leaving the prior one intact.
|
111
283
|
|
112
|
-
|
284
|
+
.. automethod:: copy
|
113
285
|
|
114
|
-
|
115
|
-
|
116
|
-
|
286
|
+
Similarly, if you want a circuit that contains all the same data objects (bits, registers,
|
287
|
+
variables, etc) but with none of the instructions, you can use :meth:`copy_empty_like`. This is
|
288
|
+
quite common when you want to build up a new layer of a circuit to then use apply onto the back
|
289
|
+
with :meth:`compose`, or to do a full rewrite of a circuit's instructions.
|
290
|
+
|
291
|
+
.. automethod:: copy_empty_like
|
292
|
+
|
293
|
+
In some cases, it is most convenient to generate a list of :class:`.CircuitInstruction`\\ s
|
294
|
+
separately to an entire circuit context, and then to build a circuit from this. The
|
295
|
+
:meth:`from_instructions` constructor will automatically capture all :class:`.Qubit` and
|
296
|
+
:class:`.Clbit` instances used in the instructions, and create a new :class:`QuantumCircuit`
|
297
|
+
object that has the correct resources and all the instructions.
|
298
|
+
|
299
|
+
.. automethod:: from_instructions
|
300
|
+
|
301
|
+
:class:`QuantumCircuit` also still has two constructor methods that are legacy wrappers around
|
302
|
+
the importers in :mod:`qiskit.qasm2`. These automatically apply :ref:`the legacy compatibility
|
303
|
+
settings <qasm2-legacy-compatibility>` of :func:`~.qasm2.load` and :func:`~.qasm2.loads`.
|
304
|
+
|
305
|
+
.. automethod:: from_qasm_file
|
306
|
+
.. automethod:: from_qasm_str
|
307
|
+
|
308
|
+
Data objects on circuits
|
309
|
+
========================
|
117
310
|
|
118
|
-
|
119
|
-
|
311
|
+
.. _circuit-adding-data-objects:
|
312
|
+
|
313
|
+
Adding data objects
|
314
|
+
-------------------
|
120
315
|
|
121
|
-
|
316
|
+
============================= =================================================================
|
317
|
+
Method Adds this kind of data
|
318
|
+
============================= =================================================================
|
319
|
+
:meth:`add_bits` :class:`.Qubit`\\ s and :class:`.Clbit`\\ s.
|
320
|
+
:meth:`add_register` :class:`.QuantumRegister` and :class:`.ClassicalRegister`.
|
321
|
+
:meth:`add_var` :class:`~.expr.Var` nodes with local scope and initializers.
|
322
|
+
:meth:`add_input` :class:`~.expr.Var` nodes that are treated as circuit inputs.
|
323
|
+
:meth:`add_capture` :class:`~.expr.Var` nodes captured from containing scopes.
|
324
|
+
:meth:`add_uninitialized_var` :class:`~.expr.Var` nodes with local scope and undefined state.
|
325
|
+
============================= =================================================================
|
122
326
|
|
123
|
-
|
124
|
-
|
125
|
-
|
327
|
+
Typically you add most of the data objects (:class:`.Qubit`, :class:`.Clbit`,
|
328
|
+
:class:`.ClassicalRegister`, etc) to the circuit as part of using the :meth:`__init__` default
|
329
|
+
constructor, or :meth:`copy_empty_like`. However, it is also possible to add these afterwards.
|
330
|
+
Typed classical data, such as standalone :class:`~.expr.Var` nodes (see
|
331
|
+
:ref:`circuit-repr-real-time-classical`), can be both constructed and added with separate
|
332
|
+
methods.
|
126
333
|
|
127
|
-
|
128
|
-
|
129
|
-
|
334
|
+
New registerless :class:`.Qubit` and :class:`.Clbit` objects are added using :meth:`add_bits`.
|
335
|
+
These objects must not already be present in the circuit. You can check if a bit exists in the
|
336
|
+
circuit already using :meth:`find_bit`.
|
337
|
+
|
338
|
+
.. automethod:: add_bits
|
339
|
+
|
340
|
+
Registers are added to the circuit with :meth:`add_register`. In this method, it is not an
|
341
|
+
error if some of the bits are already present in the circuit. In this case, the register will
|
342
|
+
be an "alias" over the bits. This is not generally well-supported by hardware backends; it is
|
343
|
+
probably best to stay away from relying on it. The registers a given bit is in are part of the
|
344
|
+
return of :meth:`find_bit`.
|
130
345
|
|
131
|
-
|
346
|
+
.. automethod:: add_register
|
132
347
|
|
133
|
-
|
134
|
-
|
348
|
+
:ref:`Real-time, typed classical data <circuit-repr-real-time-classical>` is represented on the
|
349
|
+
circuit by :class:`~.expr.Var` nodes with a well-defined :class:`~.types.Type`. It is possible
|
350
|
+
to instantiate these separately to a circuit (see :meth:`.Var.new`), but it is often more
|
351
|
+
convenient to use circuit methods that will automatically manage the types and expression
|
352
|
+
initialization for you. The two most common methods are :meth:`add_var` (locally scoped
|
353
|
+
variables) and :meth:`add_input` (inputs to the circuit).
|
135
354
|
|
136
|
-
|
137
|
-
|
355
|
+
.. automethod:: add_var
|
356
|
+
.. automethod:: add_input
|
138
357
|
|
358
|
+
In addition, there are two lower-level methods that can be useful for programmatic generation of
|
359
|
+
circuits. When working interactively, you will most likely not need these; most uses of
|
360
|
+
:meth:`add_uninitialized_var` are part of :meth:`copy_empty_like`, and most uses of
|
361
|
+
:meth:`add_capture` would be better off using :ref:`the control-flow builder interface
|
362
|
+
<circuit-control-flow-methods>`.
|
139
363
|
|
140
|
-
|
141
|
-
|
142
|
-
global_phase (float or ParameterExpression): The global phase of the circuit in radians.
|
143
|
-
metadata (dict): Arbitrary key value metadata to associate with the
|
144
|
-
circuit. This gets stored as free-form data in a dict in the
|
145
|
-
:attr:`~qiskit.circuit.QuantumCircuit.metadata` attribute. It will
|
146
|
-
not be directly used in the circuit.
|
147
|
-
inputs: any variables to declare as ``input`` real-time variables for this circuit. These
|
148
|
-
should already be existing :class:`.expr.Var` nodes that you build from somewhere else;
|
149
|
-
if you need to create the inputs as well, use :meth:`QuantumCircuit.add_input`. The
|
150
|
-
variables given in this argument will be passed directly to :meth:`add_input`. A
|
151
|
-
circuit cannot have both ``inputs`` and ``captures``.
|
152
|
-
captures: any variables that that this circuit scope should capture from a containing scope.
|
153
|
-
The variables given here will be passed directly to :meth:`add_capture`. A circuit
|
154
|
-
cannot have both ``inputs`` and ``captures``.
|
155
|
-
declarations: any variables that this circuit should declare and initialize immediately.
|
156
|
-
You can order this input so that later declarations depend on earlier ones (including
|
157
|
-
inputs or captures). If you need to depend on values that will be computed later at
|
158
|
-
runtime, use :meth:`add_var` at an appropriate point in the circuit execution.
|
364
|
+
.. automethod:: add_uninitialized_var
|
365
|
+
.. automethod:: add_capture
|
159
366
|
|
160
|
-
|
161
|
-
|
162
|
-
:meth:`add_var`, which you can use directly if this is the first time you are creating
|
163
|
-
the variable.
|
367
|
+
Working with bits and registers
|
368
|
+
-------------------------------
|
164
369
|
|
165
|
-
|
166
|
-
|
167
|
-
|
370
|
+
A :class:`.Bit` instance is, on its own, just a unique handle for circuits to use in their own
|
371
|
+
contexts. If you have got a :class:`.Bit` instance and a cirucit, just can find the contexts
|
372
|
+
that the bit exists in using :meth:`find_bit`, such as its integer index in the circuit and any
|
373
|
+
registers it is contained in.
|
374
|
+
|
375
|
+
.. automethod:: find_bit
|
376
|
+
|
377
|
+
Similarly, you can query a circuit to see if a register has already been added to it by using
|
378
|
+
:meth:`has_register`.
|
379
|
+
|
380
|
+
.. automethod:: has_register
|
381
|
+
|
382
|
+
Working with compile-time parameters
|
383
|
+
------------------------------------
|
384
|
+
|
385
|
+
.. seealso::
|
386
|
+
:ref:`circuit-compile-time-parameters`
|
387
|
+
A more complete discussion of what compile-time parametrization is, and how it fits into
|
388
|
+
Qiskit's data model.
|
389
|
+
|
390
|
+
Unlike bits, registers, and real-time typed classical data, compile-time symbolic parameters are
|
391
|
+
not manually added to a circuit. Their presence is inferred by being contained in operations
|
392
|
+
added to circuits and the global phase. An ordered list of all parameters currently in a
|
393
|
+
circuit is at :attr:`QuantumCircuit.parameters`.
|
394
|
+
|
395
|
+
The most common operation on :class:`.Parameter` instances is to replace them in symbolic
|
396
|
+
operations with some numeric value, or another symbolic expression. This is done with
|
397
|
+
:meth:`assign_parameters`.
|
398
|
+
|
399
|
+
.. automethod:: assign_parameters
|
400
|
+
|
401
|
+
The circuit tracks parameters by :class:`.Parameter` instances themselves, and forbids having
|
402
|
+
multiple parameters of the same name to avoid some problems when interoperating with OpenQASM or
|
403
|
+
other external formats. You can use :meth:`has_parameter` and :meth:`get_parameter` to query
|
404
|
+
the circuit for a parameter with the given string name.
|
405
|
+
|
406
|
+
.. automethod:: has_parameter
|
407
|
+
.. automethod:: get_parameter
|
408
|
+
|
409
|
+
.. _circuit-real-time-methods:
|
410
|
+
|
411
|
+
Working with real-time typed classical data
|
412
|
+
-------------------------------------------
|
413
|
+
|
414
|
+
.. seealso::
|
415
|
+
:mod:`qiskit.circuit.classical`
|
416
|
+
Module-level documentation for how the variable-, expression- and type-systems work, the
|
417
|
+
objects used to represent them, and the classical operations available.
|
418
|
+
|
419
|
+
:ref:`circuit-repr-real-time-classical`
|
420
|
+
A discussion of how real-time data fits into the entire :mod:`qiskit.circuit` data model
|
421
|
+
as a whole.
|
422
|
+
|
423
|
+
:ref:`circuit-adding-data-objects`
|
424
|
+
The methods for adding new :class:`~.expr.Var` variables to a circuit after
|
425
|
+
initialization.
|
426
|
+
|
427
|
+
You can retrive a :class:`~.expr.Var` instance attached to a circuit by using its variable name
|
428
|
+
using :meth:`get_var`, or check if a circuit contains a given variable with :meth:`has_var`.
|
429
|
+
|
430
|
+
.. automethod:: get_var
|
431
|
+
.. automethod:: has_var
|
432
|
+
|
433
|
+
There are also several iterator methods that you can use to get the full set of variables
|
434
|
+
tracked by a circuit. At least one of :meth:`iter_input_vars` and :meth:`iter_captured_vars`
|
435
|
+
will be empty, as inputs and captures are mutually exclusive. All of the iterators have
|
436
|
+
corresponding dynamic properties on :class:`QuantumCircuit` that contain their length:
|
437
|
+
:attr:`num_vars`, :attr:`num_input_vars`, :attr:`num_captured_vars` and
|
438
|
+
:attr:`num_declared_vars`.
|
439
|
+
|
440
|
+
.. automethod:: iter_vars
|
441
|
+
.. automethod:: iter_input_vars
|
442
|
+
.. automethod:: iter_captured_vars
|
443
|
+
.. automethod:: iter_declared_vars
|
444
|
+
|
445
|
+
|
446
|
+
.. _circuit-adding-operations:
|
447
|
+
|
448
|
+
Adding operations to circuits
|
449
|
+
=============================
|
450
|
+
|
451
|
+
You can add anything that implements the :class:`.Operation` interface to a circuit as a single
|
452
|
+
instruction, though most things you will want to add will be :class:`~.circuit.Instruction` or
|
453
|
+
:class:`~.circuit.Gate` instances.
|
454
|
+
|
455
|
+
.. seealso::
|
456
|
+
:ref:`circuit-operations-instructions`
|
457
|
+
The :mod:`qiskit.circuit`-level documentation on the different interfaces that Qiskit
|
458
|
+
uses to define circuit-level instructions.
|
459
|
+
|
460
|
+
.. _circuit-append-compose:
|
461
|
+
|
462
|
+
Methods to add general operations
|
463
|
+
---------------------------------
|
464
|
+
|
465
|
+
These are the base methods that handle adding any object, including user-defined ones, onto
|
466
|
+
circuits.
|
467
|
+
|
468
|
+
=============== ===============================================================================
|
469
|
+
Method When to use it
|
470
|
+
=============== ===============================================================================
|
471
|
+
:meth:`append` Add an instruction as a single object onto a circuit.
|
472
|
+
:meth:`_append` Same as :meth:`append`, but a low-level interface that elides almost all error
|
473
|
+
checking.
|
474
|
+
:meth:`compose` Inline the instructions from one circuit onto another.
|
475
|
+
:meth:`tensor` Like :meth:`compose`, but strictly for joining circuits that act on disjoint
|
476
|
+
qubits.
|
477
|
+
=============== ===============================================================================
|
478
|
+
|
479
|
+
:class:`QuantumCircuit` has two main ways that you will add more operations onto a circuit.
|
480
|
+
Which to use depends on whether you want to add your object as a single "instruction"
|
481
|
+
(:meth:`append`), or whether you want to join the instructions from two circuits together
|
482
|
+
(:meth:`compose`).
|
483
|
+
|
484
|
+
A single instruction or operation appears as a single entry in the :attr:`data` of the circuit,
|
485
|
+
and as a single box when drawn in the circuit visualizers (see :meth:`draw`). A single
|
486
|
+
instruction is the "unit" that a hardware backend might be defined in terms of (see
|
487
|
+
:class:`.Target`). An :class:`~.circuit.Instruction` can come with a
|
488
|
+
:attr:`~.circuit.Instruction.definition`, which is one rule the transpiler (see
|
489
|
+
:mod:`qiskit.transpiler`) will be able to fall back on to decompose it for hardware, if needed.
|
490
|
+
An :class:`.Operation` that is not also an :class:`~.circuit.Instruction` can
|
491
|
+
only be decomposed if it has some associated high-level synthesis method registered for it (see
|
492
|
+
:mod:`qiskit.transpiler.passes.synthesis.plugin`).
|
493
|
+
|
494
|
+
A :class:`QuantumCircuit` alone is not a single :class:`~.circuit.Instruction`; it is rather
|
495
|
+
more complicated, since it can, in general, represent a complete program with typed classical
|
496
|
+
memory inputs and outputs, and control flow. Qiskit's (and most hardware's) data model does not
|
497
|
+
yet have the concept of re-usable callable subroutines with virtual quantum operands. You can
|
498
|
+
convert simple circuits that act only on qubits with unitary operations into a :class:`.Gate`
|
499
|
+
using :meth:`to_gate`, and simple circuits acting only on qubits and clbits into a
|
500
|
+
:class:`~.circuit.Instruction` with :meth:`to_instruction`.
|
501
|
+
|
502
|
+
When you have an :class:`.Operation`, :class:`~.circuit.Instruction`, or :class:`.Gate`, add it
|
503
|
+
to the circuit, specifying the qubit and clbit arguments with :meth:`append`.
|
504
|
+
|
505
|
+
.. automethod:: append
|
506
|
+
|
507
|
+
:meth:`append` does quite substantial error checking to ensure that you cannot accidentally
|
508
|
+
break the data model of :class:`QuantumCircuit`. If you are programmatically generating a
|
509
|
+
circuit from known-good data, you can elide much of this error checking by using the fast-path
|
510
|
+
appender :meth:`_append`, but at the risk that the caller is responsible for ensuring they are
|
511
|
+
passing only valid data.
|
512
|
+
|
513
|
+
.. automethod:: _append
|
514
|
+
|
515
|
+
In other cases, you may want to join two circuits together, applying the instructions from one
|
516
|
+
circuit onto specified qubits and clbits on another circuit. This "inlining" operation is
|
517
|
+
called :meth:`compose` in Qiskit. :meth:`compose` is, in general, more powerful than
|
518
|
+
a :meth:`to_instruction`-plus-:meth:`append` combination for joining two circuits, because it
|
519
|
+
can also link typed classical data together, and allows for circuit control-flow operations to
|
520
|
+
be joined onto another circuit.
|
521
|
+
|
522
|
+
The downsides to :meth:`compose` are that it is a more complex operation that can involve more
|
523
|
+
rewriting of the operand, and that it necessarily must move data from one circuit object to
|
524
|
+
another. If you are building up a circuit for yourself and raw performance is a core goal,
|
525
|
+
consider passing around your base circuit and having different parts of your algorithm write
|
526
|
+
directly to the base circuit, rather than building a temporary layer circuit.
|
527
|
+
|
528
|
+
.. automethod:: compose
|
529
|
+
|
530
|
+
If you are trying to join two circuits that will apply to completely disjoint qubits and clbits,
|
531
|
+
:meth:`tensor` is a convenient wrapper around manually adding bit objects and calling
|
532
|
+
:meth:`compose`.
|
533
|
+
|
534
|
+
.. automethod:: tensor
|
535
|
+
|
536
|
+
As some rules of thumb:
|
537
|
+
|
538
|
+
* If you have a single :class:`.Operation`, :class:`~.circuit.Instruction` or :class:`.Gate`,
|
539
|
+
you should definitely use :meth:`append` or :meth:`_append`.
|
540
|
+
* If you have a :class:`QuantumCircuit` that represents a single atomic instruction for a larger
|
541
|
+
circuit that you want to re-use, you probably want to call :meth:`to_instruction` or
|
542
|
+
:meth:`to_gate`, and then apply the result of that to the circuit using :meth:`append`.
|
543
|
+
* If you have a :class:`QuantumCircuit` that represents a larger "layer" of another circuit, or
|
544
|
+
contains typed classical variables or control flow, you should use :meth:`compose` to merge it
|
545
|
+
onto another circuit.
|
546
|
+
* :meth:`tensor` is wanted far more rarely than either :meth:`append` or :meth:`compose`.
|
547
|
+
Internally, it is mostly a wrapper around :meth:`add_bits` and :meth:`compose`.
|
548
|
+
|
549
|
+
Some potential pitfalls to beware of:
|
550
|
+
|
551
|
+
* Even if you re-use a custom :class:`~.circuit.Instruction` during circuit construction, the
|
552
|
+
transpiler will generally have to "unroll" each invocation of it to its inner decomposition
|
553
|
+
before beginning work on it. This should not prevent you from using the
|
554
|
+
:meth:`to_instruction`-plus-:meth:`append` pattern, as the transpiler will improve in this
|
555
|
+
regard over time.
|
556
|
+
* :meth:`compose` will, by default, produce a new circuit for backwards compatibility. This is
|
557
|
+
more expensive, and not usually what you want, so you should set ``inplace=True``.
|
558
|
+
* Both :meth:`append` and :meth:`compose` (but not :meth:`_append`) have a ``copy`` keyword
|
559
|
+
argument that defaults to ``True``. In these cases, the incoming :class:`.Operation`
|
560
|
+
instances will be copied if Qiskit detects that the objects have mutability about them (such
|
561
|
+
as taking gate parameters). If you are sure that you will not re-use the objects again in
|
562
|
+
other places, you should set ``copy=False`` to prevent this copying, which can be a
|
563
|
+
substantial speed-up for large objects.
|
564
|
+
|
565
|
+
Methods to add standard instructions
|
566
|
+
------------------------------------
|
567
|
+
|
568
|
+
The :class:`QuantumCircuit` class has helper methods to add many of the Qiskit standard-library
|
569
|
+
instructions and gates onto a circuit. These are generally equivalent to manually constructing
|
570
|
+
an instance of the relevent :mod:`qiskit.circuit.library` object, then passing that to
|
571
|
+
:meth:`append` with the remaining arguments placed into the ``qargs`` and ``cargs`` fields as
|
572
|
+
appropriate.
|
573
|
+
|
574
|
+
The following methods apply special non-unitary :class:`~.circuit.Instruction` operations to the
|
575
|
+
circuit:
|
576
|
+
|
577
|
+
=============================== ====================================================
|
578
|
+
:class:`QuantumCircuit` method :mod:`qiskit.circuit` :class:`~.circuit.Instruction`
|
579
|
+
=============================== ====================================================
|
580
|
+
:meth:`barrier` :class:`Barrier`
|
581
|
+
:meth:`delay` :class:`Delay`
|
582
|
+
:meth:`initialize` :class:`~library.Initialize`
|
583
|
+
:meth:`measure` :class:`Measure`
|
584
|
+
:meth:`reset` :class:`Reset`
|
585
|
+
:meth:`store` :class:`Store`
|
586
|
+
=============================== ====================================================
|
587
|
+
|
588
|
+
These methods apply uncontrolled unitary :class:`.Gate` instances to the circuit:
|
589
|
+
|
590
|
+
=============================== ============================================
|
591
|
+
:class:`QuantumCircuit` method :mod:`qiskit.circuit.library` :class:`.Gate`
|
592
|
+
=============================== ============================================
|
593
|
+
:meth:`dcx` :class:`~library.DCXGate`
|
594
|
+
:meth:`ecr` :class:`~library.ECRGate`
|
595
|
+
:meth:`h` :class:`~library.HGate`
|
596
|
+
:meth:`id` :class:`~library.IGate`
|
597
|
+
:meth:`iswap` :class:`~library.iSwapGate`
|
598
|
+
:meth:`ms` :class:`~library.MSGate`
|
599
|
+
:meth:`p` :class:`~library.PhaseGate`
|
600
|
+
:meth:`pauli` :class:`~library.PauliGate`
|
601
|
+
:meth:`prepare_state` :class:`~library.StatePreparation`
|
602
|
+
:meth:`r` :class:`~library.RGate`
|
603
|
+
:meth:`rcccx` :class:`~library.RC3XGate`
|
604
|
+
:meth:`rccx` :class:`~library.RCCXGate`
|
605
|
+
:meth:`rv` :class:`~library.RVGate`
|
606
|
+
:meth:`rx` :class:`~library.RXGate`
|
607
|
+
:meth:`rxx` :class:`~library.RXXGate`
|
608
|
+
:meth:`ry` :class:`~library.RYGate`
|
609
|
+
:meth:`ryy` :class:`~library.RYYGate`
|
610
|
+
:meth:`rz` :class:`~library.RZGate`
|
611
|
+
:meth:`rzx` :class:`~library.RZXGate`
|
612
|
+
:meth:`rzz` :class:`~library.RZZGate`
|
613
|
+
:meth:`s` :class:`~library.SGate`
|
614
|
+
:meth:`sdg` :class:`~library.SdgGate`
|
615
|
+
:meth:`swap` :class:`~library.SwapGate`
|
616
|
+
:meth:`sx` :class:`~library.SXGate`
|
617
|
+
:meth:`sxdg` :class:`~library.SXdgGate`
|
618
|
+
:meth:`t` :class:`~library.TGate`
|
619
|
+
:meth:`tdg` :class:`~library.TdgGate`
|
620
|
+
:meth:`u` :class:`~library.UGate`
|
621
|
+
:meth:`unitary` :class:`~library.UnitaryGate`
|
622
|
+
:meth:`x` :class:`~library.XGate`
|
623
|
+
:meth:`y` :class:`~library.YGate`
|
624
|
+
:meth:`z` :class:`~library.ZGate`
|
625
|
+
=============================== ============================================
|
626
|
+
|
627
|
+
The following methods apply :class:`Gate` instances that are also controlled gates, so are
|
628
|
+
direct subclasses of :class:`ControlledGate`:
|
629
|
+
|
630
|
+
=============================== ======================================================
|
631
|
+
:class:`QuantumCircuit` method :mod:`qiskit.circuit.library` :class:`.ControlledGate`
|
632
|
+
=============================== ======================================================
|
633
|
+
:meth:`ccx` :class:`~library.CCXGate`
|
634
|
+
:meth:`ccz` :class:`~library.CCZGate`
|
635
|
+
:meth:`ch` :class:`~library.CHGate`
|
636
|
+
:meth:`cp` :class:`~library.CPhaseGate`
|
637
|
+
:meth:`crx` :class:`~library.CRXGate`
|
638
|
+
:meth:`cry` :class:`~library.CRYGate`
|
639
|
+
:meth:`crz` :class:`~library.CRZGate`
|
640
|
+
:meth:`cs` :class:`~library.CSGate`
|
641
|
+
:meth:`csdg` :class:`~library.CSdgGate`
|
642
|
+
:meth:`cswap` :class:`~library.CSwapGate`
|
643
|
+
:meth:`csx` :class:`~library.CSXGate`
|
644
|
+
:meth:`cu` :class:`~library.CUGate`
|
645
|
+
:meth:`cx` :class:`~library.CXGate`
|
646
|
+
:meth:`cy` :class:`~library.CYGate`
|
647
|
+
:meth:`cz` :class:`~library.CZGate`
|
648
|
+
=============================== ======================================================
|
649
|
+
|
650
|
+
Finally, these methods apply particular generalized multiply controlled gates to the circuit,
|
651
|
+
often with eager syntheses. They are listed in terms of the *base* gate they are controlling,
|
652
|
+
since their exact output is often a synthesised version of a gate.
|
653
|
+
|
654
|
+
=============================== =================================================
|
655
|
+
:class:`QuantumCircuit` method Base :mod:`qiskit.circuit.library` :class:`.Gate`
|
656
|
+
=============================== =================================================
|
657
|
+
:meth:`mcp` :class:`~library.PhaseGate`
|
658
|
+
:meth:`mcrx` :class:`~library.RXGate`
|
659
|
+
:meth:`mcry` :class:`~library.RYGate`
|
660
|
+
:meth:`mcrz` :class:`~library.RZGate`
|
661
|
+
:meth:`mcx` :class:`~library.XGate`
|
662
|
+
=============================== =================================================
|
663
|
+
|
664
|
+
The rest of this section is the API listing of all the individual methods; the tables above are
|
665
|
+
summaries whose links will jump you to the correct place.
|
666
|
+
|
667
|
+
.. automethod:: barrier
|
668
|
+
.. automethod:: ccx
|
669
|
+
.. automethod:: ccz
|
670
|
+
.. automethod:: ch
|
671
|
+
.. automethod:: cp
|
672
|
+
.. automethod:: crx
|
673
|
+
.. automethod:: cry
|
674
|
+
.. automethod:: crz
|
675
|
+
.. automethod:: cs
|
676
|
+
.. automethod:: csdg
|
677
|
+
.. automethod:: cswap
|
678
|
+
.. automethod:: csx
|
679
|
+
.. automethod:: cu
|
680
|
+
.. automethod:: cx
|
681
|
+
.. automethod:: cy
|
682
|
+
.. automethod:: cz
|
683
|
+
.. automethod:: dcx
|
684
|
+
.. automethod:: delay
|
685
|
+
.. automethod:: ecr
|
686
|
+
.. automethod:: h
|
687
|
+
.. automethod:: id
|
688
|
+
.. automethod:: initialize
|
689
|
+
.. automethod:: iswap
|
690
|
+
.. automethod:: mcp
|
691
|
+
.. automethod:: mcrx
|
692
|
+
.. automethod:: mcry
|
693
|
+
.. automethod:: mcrz
|
694
|
+
.. automethod:: mcx
|
695
|
+
.. automethod:: measure
|
696
|
+
.. automethod:: ms
|
697
|
+
.. automethod:: p
|
698
|
+
.. automethod:: pauli
|
699
|
+
.. automethod:: prepare_state
|
700
|
+
.. automethod:: r
|
701
|
+
.. automethod:: rcccx
|
702
|
+
.. automethod:: rccx
|
703
|
+
.. automethod:: reset
|
704
|
+
.. automethod:: rv
|
705
|
+
.. automethod:: rx
|
706
|
+
.. automethod:: rxx
|
707
|
+
.. automethod:: ry
|
708
|
+
.. automethod:: ryy
|
709
|
+
.. automethod:: rz
|
710
|
+
.. automethod:: rzx
|
711
|
+
.. automethod:: rzz
|
712
|
+
.. automethod:: s
|
713
|
+
.. automethod:: sdg
|
714
|
+
.. automethod:: store
|
715
|
+
.. automethod:: swap
|
716
|
+
.. automethod:: sx
|
717
|
+
.. automethod:: sxdg
|
718
|
+
.. automethod:: t
|
719
|
+
.. automethod:: tdg
|
720
|
+
.. automethod:: u
|
721
|
+
.. automethod:: unitary
|
722
|
+
.. automethod:: x
|
723
|
+
.. automethod:: y
|
724
|
+
.. automethod:: z
|
725
|
+
|
726
|
+
|
727
|
+
.. _circuit-control-flow-methods:
|
728
|
+
|
729
|
+
Adding control flow to circuits
|
730
|
+
-------------------------------
|
731
|
+
|
732
|
+
.. seealso::
|
733
|
+
:ref:`circuit-control-flow-repr`
|
734
|
+
|
735
|
+
Discussion of how control-flow operations are represented in the whole :mod:`qiskit.circuit`
|
736
|
+
context.
|
737
|
+
|
738
|
+
============================== ================================================================
|
739
|
+
:class:`QuantumCircuit` method Control-flow instruction
|
740
|
+
============================== ================================================================
|
741
|
+
:meth:`if_test` :class:`.IfElseOp` with only a ``True`` body.
|
742
|
+
:meth:`if_else` :class:`.IfElseOp` with both ``True`` and ``False`` bodies.
|
743
|
+
:meth:`while_loop` :class:`.WhileLoopOp`.
|
744
|
+
:meth:`switch` :class:`.SwitchCaseOp`.
|
745
|
+
:meth:`for_loop` :class:`.ForLoopOp`.
|
746
|
+
:meth:`break_loop` :class:`.BreakLoopOp`.
|
747
|
+
:meth:`continue_loop` :class:`.ContinueLoopOp`.
|
748
|
+
============================== ================================================================
|
749
|
+
|
750
|
+
:class:`QuantumCircuit` has corresponding methods for all of the control-flow operations that
|
751
|
+
are supported by Qiskit. These have two forms for calling them. The first is a very
|
752
|
+
straightfowards convenience wrapper that takes in the block bodies of the instructions as
|
753
|
+
:class:`QuantumCircuit` arguments, and simply constructs and appends the corresponding
|
754
|
+
:class:`.ControlFlowOp`.
|
755
|
+
|
756
|
+
The second form, which we strongly recommend you use for constructing control flow, is called
|
757
|
+
*the builder interface*. Here, the methods take only the real-time discriminant of the
|
758
|
+
operation, and return `context managers
|
759
|
+
<https://docs.python.org/3/library/stdtypes.html#typecontextmanager>`__ that you enter using
|
760
|
+
``with``. You can then use regular :class:`QuantumCircuit` methods within those blocks to build
|
761
|
+
up the control-flow bodies, and Qiskit will automatically track which of the data resources are
|
762
|
+
needed for the inner blocks, building the complete :class:`.ControlFlowOp` as you leave the
|
763
|
+
``with`` statement. It is far simpler and less error-prone to build control flow
|
764
|
+
programmatically this way.
|
765
|
+
|
766
|
+
..
|
767
|
+
TODO: expand the examples of the builder interface.
|
768
|
+
|
769
|
+
.. automethod:: break_loop
|
770
|
+
.. automethod:: continue_loop
|
771
|
+
.. automethod:: for_loop
|
772
|
+
.. automethod:: if_else
|
773
|
+
.. automethod:: if_test
|
774
|
+
.. automethod:: switch
|
775
|
+
.. automethod:: while_loop
|
776
|
+
|
777
|
+
|
778
|
+
Converting circuits to single objects
|
779
|
+
-------------------------------------
|
780
|
+
|
781
|
+
As discussed in :ref:`circuit-append-compose`, you can convert a circuit to either an
|
782
|
+
:class:`~.circuit.Instruction` or a :class:`.Gate` using two helper methods.
|
783
|
+
|
784
|
+
.. automethod:: to_instruction
|
785
|
+
.. automethod:: to_gate
|
786
|
+
|
787
|
+
|
788
|
+
Helper mutation methods
|
789
|
+
-----------------------
|
790
|
+
|
791
|
+
There are two higher-level methods on :class:`QuantumCircuit` for appending measurements to the
|
792
|
+
end of a circuit. Note that by default, these also add an extra register.
|
793
|
+
|
794
|
+
.. automethod:: measure_active
|
795
|
+
.. automethod:: measure_all
|
796
|
+
|
797
|
+
There are two "subtractive" methods on :class:`QuantumCircuit` as well. This is not a use-case
|
798
|
+
that :class:`QuantumCircuit` is designed for; typically you should just look to use
|
799
|
+
:meth:`copy_empty_like` in place of :meth:`clear`, and run :meth:`remove_final_measurements` as
|
800
|
+
its transpiler-pass form :class:`.RemoveFinalMeasurements`.
|
801
|
+
|
802
|
+
.. automethod:: clear
|
803
|
+
.. automethod:: remove_final_measurements
|
804
|
+
|
805
|
+
.. _circuit-calibrations:
|
806
|
+
|
807
|
+
Manual calibration of instructions
|
808
|
+
----------------------------------
|
809
|
+
|
810
|
+
:class:`QuantumCircuit` can store :attr:`calibrations` of instructions that define the pulses
|
811
|
+
used to run them on one particular hardware backend. You can
|
812
|
+
|
813
|
+
.. automethod:: add_calibration
|
814
|
+
.. automethod:: has_calibration_for
|
815
|
+
|
816
|
+
|
817
|
+
Circuit properties
|
818
|
+
==================
|
819
|
+
|
820
|
+
Simple circuit metrics
|
821
|
+
----------------------
|
822
|
+
|
823
|
+
When constructing quantum circuits, there are several properties that help quantify
|
824
|
+
the "size" of the circuits, and their ability to be run on a noisy quantum device.
|
825
|
+
Some of these, like number of qubits, are straightforward to understand, while others
|
826
|
+
like depth and number of tensor components require a bit more explanation. Here we will
|
827
|
+
explain all of these properties, and, in preparation for understanding how circuits change
|
828
|
+
when run on actual devices, highlight the conditions under which they change.
|
829
|
+
|
830
|
+
Consider the following circuit:
|
831
|
+
|
832
|
+
.. plot::
|
833
|
+
:include-source:
|
834
|
+
|
835
|
+
from qiskit import QuantumCircuit
|
836
|
+
qc = QuantumCircuit(12)
|
837
|
+
for idx in range(5):
|
838
|
+
qc.h(idx)
|
839
|
+
qc.cx(idx, idx+5)
|
840
|
+
|
841
|
+
qc.cx(1, 7)
|
842
|
+
qc.x(8)
|
843
|
+
qc.cx(1, 9)
|
844
|
+
qc.x(7)
|
845
|
+
qc.cx(1, 11)
|
846
|
+
qc.swap(6, 11)
|
847
|
+
qc.swap(6, 9)
|
848
|
+
qc.swap(6, 10)
|
849
|
+
qc.x(6)
|
850
|
+
qc.draw('mpl')
|
851
|
+
|
852
|
+
From the plot, it is easy to see that this circuit has 12 qubits, and a collection of
|
853
|
+
Hadamard, CNOT, X, and SWAP gates. But how to quantify this programmatically? Because we
|
854
|
+
can do single-qubit gates on all the qubits simultaneously, the number of qubits in this
|
855
|
+
circuit is equal to the :meth:`width` of the circuit::
|
856
|
+
|
857
|
+
assert qc.width() == 12
|
858
|
+
|
859
|
+
We can also just get the number of qubits directly using :attr:`num_qubits`::
|
860
|
+
|
861
|
+
assert qc.num_qubits == 12
|
862
|
+
|
863
|
+
.. important::
|
864
|
+
|
865
|
+
For a quantum circuit composed from just qubits, the circuit width is equal
|
866
|
+
to the number of qubits. This is the definition used in quantum computing. However,
|
867
|
+
for more complicated circuits with classical registers, and classically controlled gates,
|
868
|
+
this equivalence breaks down. As such, from now on we will not refer to the number of
|
869
|
+
qubits in a quantum circuit as the width.
|
870
|
+
|
871
|
+
It is also straightforward to get the number and type of the gates in a circuit using
|
872
|
+
:meth:`count_ops`::
|
873
|
+
|
874
|
+
qc.count_ops()
|
875
|
+
|
876
|
+
.. parsed-literal::
|
168
877
|
|
169
|
-
|
878
|
+
OrderedDict([('cx', 8), ('h', 5), ('x', 3), ('swap', 3)])
|
170
879
|
|
171
|
-
|
880
|
+
We can also get just the raw count of operations by computing the circuits
|
881
|
+
:meth:`size`::
|
172
882
|
|
173
|
-
|
174
|
-
:include-source:
|
883
|
+
assert qc.size() == 19
|
175
884
|
|
176
|
-
|
885
|
+
A particularly important circuit property is known as the circuit :meth:`depth`. The depth
|
886
|
+
of a quantum circuit is a measure of how many "layers" of quantum gates, executed in
|
887
|
+
parallel, it takes to complete the computation defined by the circuit. Because quantum
|
888
|
+
gates take time to implement, the depth of a circuit roughly corresponds to the amount of
|
889
|
+
time it takes the quantum computer to execute the circuit. Thus, the depth of a circuit
|
890
|
+
is one important quantity used to measure if a quantum circuit can be run on a device.
|
177
891
|
|
178
|
-
|
179
|
-
|
180
|
-
|
181
|
-
|
182
|
-
|
892
|
+
The depth of a quantum circuit has a mathematical definition as the longest path in a
|
893
|
+
directed acyclic graph (DAG). However, such a definition is a bit hard to grasp, even for
|
894
|
+
experts. Fortunately, the depth of a circuit can be easily understood by anyone familiar
|
895
|
+
with playing `Tetris <https://en.wikipedia.org/wiki/Tetris>`_. Lets see how to compute this
|
896
|
+
graphically:
|
183
897
|
|
184
|
-
|
898
|
+
.. image:: /source_images/depth.gif
|
185
899
|
|
186
|
-
|
900
|
+
We can verify our graphical result using :meth:`QuantumCircuit.depth`::
|
187
901
|
|
188
|
-
|
902
|
+
assert qc.depth() == 9
|
189
903
|
|
190
|
-
|
191
|
-
|
192
|
-
|
193
|
-
|
904
|
+
.. automethod:: count_ops
|
905
|
+
.. automethod:: depth
|
906
|
+
.. automethod:: get_instructions
|
907
|
+
.. automethod:: num_connected_components
|
908
|
+
.. automethod:: num_nonlocal_gates
|
909
|
+
.. automethod:: num_tensor_factors
|
910
|
+
.. automethod:: num_unitary_factors
|
911
|
+
.. automethod:: size
|
912
|
+
.. automethod:: width
|
194
913
|
|
195
|
-
|
914
|
+
Accessing scheduling information
|
915
|
+
--------------------------------
|
196
916
|
|
197
|
-
|
198
|
-
|
917
|
+
If a :class:`QuantumCircuit` has been scheduled as part of a transpilation pipeline, the timing
|
918
|
+
information for individual qubits can be accessed. The whole-circuit timing information is
|
919
|
+
available through the :attr:`duration`, :attr:`unit` and :attr:`op_start_times` attributes.
|
920
|
+
|
921
|
+
.. automethod:: qubit_duration
|
922
|
+
.. automethod:: qubit_start_time
|
923
|
+
.. automethod:: qubit_stop_time
|
924
|
+
|
925
|
+
Instruction-like methods
|
926
|
+
========================
|
199
927
|
|
200
|
-
|
928
|
+
..
|
929
|
+
These methods really shouldn't be on `QuantumCircuit` at all. They're generally more
|
930
|
+
appropriate as `Instruction` or `Gate` methods. `reverse_ops` shouldn't be a method _full
|
931
|
+
stop_---it was copying a `DAGCircuit` method from an implementation detail of the original
|
932
|
+
`SabreLayout` pass in Qiskit.
|
933
|
+
|
934
|
+
:class:`QuantumCircuit` also contains a small number of methods that are very
|
935
|
+
:class:`~.circuit.Instruction`-like in detail. You may well find better integration and more
|
936
|
+
API support if you first convert your circuit to an :class:`~.circuit.Instruction`
|
937
|
+
(:meth:`to_instruction`) or :class:`.Gate` (:meth:`to_gate`) as appropriate, then call the
|
938
|
+
corresponding method.
|
201
939
|
|
202
|
-
|
203
|
-
|
204
|
-
|
205
|
-
|
940
|
+
.. automethod:: control
|
941
|
+
.. automethod:: inverse
|
942
|
+
.. automethod:: power
|
943
|
+
.. automethod:: repeat
|
944
|
+
.. automethod:: reverse_ops
|
206
945
|
|
207
|
-
|
208
|
-
|
209
|
-
qc.h(qr[0:3])
|
210
|
-
qc.cx(qr[0:3], anc[0])
|
211
|
-
qc.h(qr[0:3])
|
212
|
-
qc.barrier(qr)
|
213
|
-
qc.measure(qr, cr)
|
946
|
+
Visualization
|
947
|
+
=============
|
214
948
|
|
215
|
-
|
949
|
+
Qiskit includes some drawing tools to give you a quick feel for what your circuit looks like.
|
950
|
+
This tooling is primarily targeted at producing either a `Matplotlib
|
951
|
+
<https://matplotlib.org/>`__- or text-based drawing. There is also a lesser-featured LaTeX
|
952
|
+
backend for drawing, but this is only for simple circuits, and is not as actively maintained.
|
953
|
+
|
954
|
+
.. seealso::
|
955
|
+
:mod:`qiskit.visualization`
|
956
|
+
The primary documentation for all of Qiskit's visualization tooling.
|
957
|
+
|
958
|
+
.. automethod:: draw
|
959
|
+
|
960
|
+
In addition to the core :meth:`draw` driver, there are two visualization-related helper methods,
|
961
|
+
which are mostly useful for quickly unwrapping some inner instructions or reversing the
|
962
|
+
:ref:`qubit-labelling conventions <circuit-conventions>` in the drawing. For more general
|
963
|
+
mutation, including basis-gate rewriting, you should use the transpiler
|
964
|
+
(:mod:`qiskit.transpiler`).
|
965
|
+
|
966
|
+
.. automethod:: decompose
|
967
|
+
.. automethod:: reverse_bits
|
968
|
+
|
969
|
+
Internal utilities
|
970
|
+
==================
|
971
|
+
|
972
|
+
These functions are not intended for public use, but were accidentally left documented in the
|
973
|
+
public API during the 1.0 release. They will be removed in Qiskit 2.0, but will be supported
|
974
|
+
until then.
|
975
|
+
|
976
|
+
.. automethod:: cast
|
977
|
+
.. automethod:: cbit_argument_conversion
|
978
|
+
.. automethod:: cls_instances
|
979
|
+
.. automethod:: cls_prefix
|
980
|
+
.. automethod:: qbit_argument_conversion
|
216
981
|
"""
|
217
982
|
|
218
983
|
instances = 0
|
@@ -228,6 +993,69 @@ class QuantumCircuit:
|
|
228
993
|
captures: Iterable[expr.Var] = (),
|
229
994
|
declarations: Mapping[expr.Var, expr.Expr] | Iterable[Tuple[expr.Var, expr.Expr]] = (),
|
230
995
|
):
|
996
|
+
"""
|
997
|
+
Default constructor of :class:`QuantumCircuit`.
|
998
|
+
|
999
|
+
..
|
1000
|
+
`QuantumCirucit` documents its `__init__` method explicitly, unlike most classes where
|
1001
|
+
it's implicitly appended to the class-level documentation, just because the class is so
|
1002
|
+
huge and has a lot of introductory material to its class docstring.
|
1003
|
+
|
1004
|
+
Args:
|
1005
|
+
regs: The registers to be included in the circuit.
|
1006
|
+
|
1007
|
+
* If a list of :class:`~.Register` objects, represents the :class:`.QuantumRegister`
|
1008
|
+
and/or :class:`.ClassicalRegister` objects to include in the circuit.
|
1009
|
+
|
1010
|
+
For example:
|
1011
|
+
|
1012
|
+
* ``QuantumCircuit(QuantumRegister(4))``
|
1013
|
+
* ``QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))``
|
1014
|
+
* ``QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))``
|
1015
|
+
|
1016
|
+
* If a list of ``int``, the amount of qubits and/or classical bits to include in
|
1017
|
+
the circuit. It can either be a single int for just the number of quantum bits,
|
1018
|
+
or 2 ints for the number of quantum bits and classical bits, respectively.
|
1019
|
+
|
1020
|
+
For example:
|
1021
|
+
|
1022
|
+
* ``QuantumCircuit(4) # A QuantumCircuit with 4 qubits``
|
1023
|
+
* ``QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits``
|
1024
|
+
|
1025
|
+
* If a list of python lists containing :class:`.Bit` objects, a collection of
|
1026
|
+
:class:`.Bit` s to be added to the circuit.
|
1027
|
+
|
1028
|
+
name: the name of the quantum circuit. If not set, an automatically generated string
|
1029
|
+
will be assigned.
|
1030
|
+
global_phase: The global phase of the circuit in radians.
|
1031
|
+
metadata: Arbitrary key value metadata to associate with the circuit. This gets
|
1032
|
+
stored as free-form data in a dict in the
|
1033
|
+
:attr:`~qiskit.circuit.QuantumCircuit.metadata` attribute. It will not be directly
|
1034
|
+
used in the circuit.
|
1035
|
+
inputs: any variables to declare as ``input`` runtime variables for this circuit. These
|
1036
|
+
should already be existing :class:`.expr.Var` nodes that you build from somewhere
|
1037
|
+
else; if you need to create the inputs as well, use
|
1038
|
+
:meth:`QuantumCircuit.add_input`. The variables given in this argument will be
|
1039
|
+
passed directly to :meth:`add_input`. A circuit cannot have both ``inputs`` and
|
1040
|
+
``captures``.
|
1041
|
+
captures: any variables that that this circuit scope should capture from a containing
|
1042
|
+
scope. The variables given here will be passed directly to :meth:`add_capture`. A
|
1043
|
+
circuit cannot have both ``inputs`` and ``captures``.
|
1044
|
+
declarations: any variables that this circuit should declare and initialize immediately.
|
1045
|
+
You can order this input so that later declarations depend on earlier ones
|
1046
|
+
(including inputs or captures). If you need to depend on values that will be
|
1047
|
+
computed later at runtime, use :meth:`add_var` at an appropriate point in the
|
1048
|
+
circuit execution.
|
1049
|
+
|
1050
|
+
This argument is intended for convenient circuit initialization when you already
|
1051
|
+
have a set of created variables. The variables used here will be directly passed to
|
1052
|
+
:meth:`add_var`, which you can use directly if this is the first time you are
|
1053
|
+
creating the variable.
|
1054
|
+
|
1055
|
+
Raises:
|
1056
|
+
CircuitError: if the circuit name, if given, is not valid.
|
1057
|
+
CircuitError: if both ``inputs`` and ``captures`` are given.
|
1058
|
+
"""
|
231
1059
|
if any(not isinstance(reg, (list, QuantumRegister, ClassicalRegister)) for reg in regs):
|
232
1060
|
# check if inputs are integers, but also allow e.g. 2.0
|
233
1061
|
|
@@ -244,6 +1072,8 @@ class QuantumCircuit:
|
|
244
1072
|
|
245
1073
|
regs = tuple(int(reg) for reg in regs) # cast to int
|
246
1074
|
self._base_name = None
|
1075
|
+
self.name: str
|
1076
|
+
"""A human-readable name for the circuit."""
|
247
1077
|
if name is None:
|
248
1078
|
self._base_name = self.cls_prefix()
|
249
1079
|
self._name_update()
|
@@ -273,7 +1103,11 @@ class QuantumCircuit:
|
|
273
1103
|
] = []
|
274
1104
|
|
275
1105
|
self.qregs: list[QuantumRegister] = []
|
1106
|
+
"""A list of the :class:`QuantumRegister`\\ s in this circuit. You should not mutate
|
1107
|
+
this."""
|
276
1108
|
self.cregs: list[ClassicalRegister] = []
|
1109
|
+
"""A list of the :class:`ClassicalRegister`\\ s in this circuit. You should not mutate
|
1110
|
+
this."""
|
277
1111
|
|
278
1112
|
# Dict mapping Qubit or Clbit instances to tuple comprised of 0) the
|
279
1113
|
# corresponding index in circuit.{qubits,clbits} and 1) a list of
|
@@ -314,9 +1148,16 @@ class QuantumCircuit:
|
|
314
1148
|
for var, initial in declarations:
|
315
1149
|
self.add_var(var, initial)
|
316
1150
|
|
317
|
-
self.duration = None
|
1151
|
+
self.duration: int | float | None = None
|
1152
|
+
"""The total duration of the circuit, set by a scheduling transpiler pass. Its unit is
|
1153
|
+
specified by :attr:`unit`."""
|
318
1154
|
self.unit = "dt"
|
1155
|
+
"""The unit that :attr:`duration` is specified in."""
|
319
1156
|
self.metadata = {} if metadata is None else metadata
|
1157
|
+
"""Arbitrary user-defined metadata for the circuit.
|
1158
|
+
|
1159
|
+
Qiskit will not examine the content of this mapping, but it will pass it through the
|
1160
|
+
transpiler and reattach it to the output, so you can track your own metadata."""
|
320
1161
|
|
321
1162
|
@staticmethod
|
322
1163
|
def from_instructions(
|
@@ -333,7 +1174,7 @@ class QuantumCircuit:
|
|
333
1174
|
global_phase: ParameterValueType = 0,
|
334
1175
|
metadata: dict | None = None,
|
335
1176
|
) -> "QuantumCircuit":
|
336
|
-
"""Construct a circuit from an iterable of
|
1177
|
+
"""Construct a circuit from an iterable of :class:`.CircuitInstruction`\\ s.
|
337
1178
|
|
338
1179
|
Args:
|
339
1180
|
instructions: The instructions to add to the circuit.
|
@@ -390,7 +1231,7 @@ class QuantumCircuit:
|
|
390
1231
|
|
391
1232
|
@property
|
392
1233
|
def data(self) -> QuantumCircuitData:
|
393
|
-
"""
|
1234
|
+
"""The circuit data (instructions and context).
|
394
1235
|
|
395
1236
|
Returns:
|
396
1237
|
QuantumCircuitData: a list-like object containing the :class:`.CircuitInstruction`\\ s
|
@@ -884,9 +1725,13 @@ class QuantumCircuit:
|
|
884
1725
|
var_remap: Mapping[str | expr.Var, str | expr.Var] | None = None,
|
885
1726
|
inline_captures: bool = False,
|
886
1727
|
) -> Optional["QuantumCircuit"]:
|
887
|
-
"""
|
1728
|
+
"""Apply the instructions from one circuit onto specified qubits and/or clbits on another.
|
888
1729
|
|
889
|
-
|
1730
|
+
.. note::
|
1731
|
+
|
1732
|
+
By default, this creates a new circuit object, leaving ``self`` untouched. For most
|
1733
|
+
uses of this function, it is far more efficient to set ``inplace=True`` and modify the
|
1734
|
+
base circuit in-place.
|
890
1735
|
|
891
1736
|
When dealing with realtime variables (:class:`.expr.Var` instances), there are two principal
|
892
1737
|
strategies for using :meth:`compose`:
|
@@ -915,8 +1760,6 @@ class QuantumCircuit:
|
|
915
1760
|
front (bool): If True, front composition will be performed. This is not possible within
|
916
1761
|
control-flow builder context managers.
|
917
1762
|
inplace (bool): If True, modify the object. Otherwise return composed circuit.
|
918
|
-
wrap (bool): If True, wraps the other circuit into a gate (or instruction, depending on
|
919
|
-
whether it contains only unitary instructions) before composing it onto self.
|
920
1763
|
copy (bool): If ``True`` (the default), then the input is treated as shared, and any
|
921
1764
|
contained instructions will be copied, if they might need to be mutated in the
|
922
1765
|
future. You can set this to ``False`` if the input should be considered owned by
|
@@ -941,6 +1784,11 @@ class QuantumCircuit:
|
|
941
1784
|
|
942
1785
|
If this is ``False`` (the default), then all variables in ``other`` will be required
|
943
1786
|
to be distinct from those in ``self``, and new declarations will be made for them.
|
1787
|
+
wrap (bool): If True, wraps the other circuit into a gate (or instruction, depending on
|
1788
|
+
whether it contains only unitary instructions) before composing it onto self.
|
1789
|
+
Rather than using this option, it is almost always better to manually control this
|
1790
|
+
yourself by using :meth:`to_instruction` or :meth:`to_gate`, and then call
|
1791
|
+
:meth:`append`.
|
944
1792
|
|
945
1793
|
Returns:
|
946
1794
|
QuantumCircuit: the composed circuit (returns None if inplace==True).
|
@@ -1294,23 +2142,20 @@ class QuantumCircuit:
|
|
1294
2142
|
|
1295
2143
|
@property
|
1296
2144
|
def qubits(self) -> list[Qubit]:
|
1297
|
-
"""
|
1298
|
-
|
1299
|
-
"""
|
2145
|
+
"""A list of :class:`Qubit`\\ s in the order that they were added. You should not mutate
|
2146
|
+
this."""
|
1300
2147
|
return self._data.qubits
|
1301
2148
|
|
1302
2149
|
@property
|
1303
2150
|
def clbits(self) -> list[Clbit]:
|
1304
|
-
"""
|
1305
|
-
|
1306
|
-
"""
|
2151
|
+
"""A list of :class:`Clbit`\\ s in the order that they were added. You should not mutate
|
2152
|
+
this."""
|
1307
2153
|
return self._data.clbits
|
1308
2154
|
|
1309
2155
|
@property
|
1310
2156
|
def ancillas(self) -> list[AncillaQubit]:
|
1311
|
-
"""
|
1312
|
-
|
1313
|
-
"""
|
2157
|
+
"""A list of :class:`AncillaQubit`\\ s in the order that they were added. You should not
|
2158
|
+
mutate this."""
|
1314
2159
|
return self._ancillas
|
1315
2160
|
|
1316
2161
|
@property
|
@@ -1557,33 +2402,31 @@ class QuantumCircuit:
|
|
1557
2402
|
|
1558
2403
|
# Preferred new style.
|
1559
2404
|
@typing.overload
|
1560
|
-
def _append(
|
1561
|
-
self, instruction: CircuitInstruction, _qargs: None = None, _cargs: None = None
|
1562
|
-
) -> CircuitInstruction: ...
|
2405
|
+
def _append(self, instruction: CircuitInstruction) -> CircuitInstruction: ...
|
1563
2406
|
|
1564
2407
|
# To-be-deprecated old style.
|
1565
2408
|
@typing.overload
|
1566
2409
|
def _append(
|
1567
2410
|
self,
|
1568
|
-
|
2411
|
+
instruction: Operation,
|
1569
2412
|
qargs: Sequence[Qubit],
|
1570
2413
|
cargs: Sequence[Clbit],
|
1571
2414
|
) -> Operation: ...
|
1572
2415
|
|
1573
|
-
def _append(
|
1574
|
-
self,
|
1575
|
-
instruction: CircuitInstruction | Instruction,
|
1576
|
-
qargs: Sequence[Qubit] | None = None,
|
1577
|
-
cargs: Sequence[Clbit] | None = None,
|
1578
|
-
):
|
2416
|
+
def _append(self, instruction, qargs=(), cargs=()):
|
1579
2417
|
"""Append an instruction to the end of the circuit, modifying the circuit in place.
|
1580
2418
|
|
1581
2419
|
.. warning::
|
1582
2420
|
|
1583
2421
|
This is an internal fast-path function, and it is the responsibility of the caller to
|
1584
2422
|
ensure that all the arguments are valid; there is no error checking here. In
|
1585
|
-
particular
|
1586
|
-
|
2423
|
+
particular:
|
2424
|
+
|
2425
|
+
* all the qubits and clbits must already exist in the circuit and there can be no
|
2426
|
+
duplicates in the list.
|
2427
|
+
* any control-flow operations or classically conditioned instructions must act only on
|
2428
|
+
variables present in the circuit.
|
2429
|
+
* the circuit must not be within a control-flow builder context.
|
1587
2430
|
|
1588
2431
|
.. note::
|
1589
2432
|
|
@@ -1596,12 +2439,18 @@ class QuantumCircuit:
|
|
1596
2439
|
constructs of the control-flow builder interface.
|
1597
2440
|
|
1598
2441
|
Args:
|
1599
|
-
instruction:
|
1600
|
-
|
1601
|
-
|
2442
|
+
instruction: A complete well-formed :class:`.CircuitInstruction` of the operation and
|
2443
|
+
its context to be added.
|
2444
|
+
|
2445
|
+
In the legacy compatibility form, this can be a bare :class:`.Operation`, in which
|
2446
|
+
case ``qargs`` and ``cargs`` must be explicitly given.
|
2447
|
+
qargs: Legacy argument for qubits to attach the bare :class:`.Operation` to. Ignored if
|
2448
|
+
the first argument is in the preferential :class:`.CircuitInstruction` form.
|
2449
|
+
cargs: Legacy argument for clbits to attach the bare :class:`.Operation` to. Ignored if
|
2450
|
+
the first argument is in the preferential :class:`.CircuitInstruction` form.
|
1602
2451
|
|
1603
2452
|
Returns:
|
1604
|
-
|
2453
|
+
CircuitInstruction: a handle to the instruction that was just added.
|
1605
2454
|
|
1606
2455
|
:meta public:
|
1607
2456
|
"""
|
@@ -2114,24 +2963,52 @@ class QuantumCircuit:
|
|
2114
2963
|
def find_bit(self, bit: Bit) -> BitLocations:
|
2115
2964
|
"""Find locations in the circuit which can be used to reference a given :obj:`~Bit`.
|
2116
2965
|
|
2966
|
+
In particular, this function can find the integer index of a qubit, which corresponds to its
|
2967
|
+
hardware index for a transpiled circuit.
|
2968
|
+
|
2969
|
+
.. note::
|
2970
|
+
The circuit index of a :class:`.AncillaQubit` will be its index in :attr:`qubits`, not
|
2971
|
+
:attr:`ancillas`.
|
2972
|
+
|
2117
2973
|
Args:
|
2118
2974
|
bit (Bit): The bit to locate.
|
2119
2975
|
|
2120
2976
|
Returns:
|
2121
2977
|
namedtuple(int, List[Tuple(Register, int)]): A 2-tuple. The first element (``index``)
|
2122
|
-
|
2123
|
-
|
2124
|
-
|
2125
|
-
|
2126
|
-
|
2127
|
-
|
2128
|
-
Notes:
|
2129
|
-
The circuit index of an :obj:`~AncillaQubit` will be its index in
|
2130
|
-
:obj:`~QuantumCircuit.qubits`, not :obj:`~QuantumCircuit.ancillas`.
|
2978
|
+
contains the index at which the ``Bit`` can be found (in either
|
2979
|
+
:obj:`~QuantumCircuit.qubits`, :obj:`~QuantumCircuit.clbits`, depending on its
|
2980
|
+
type). The second element (``registers``) is a list of ``(register, index)``
|
2981
|
+
pairs with an entry for each :obj:`~Register` in the circuit which contains the
|
2982
|
+
:obj:`~Bit` (and the index in the :obj:`~Register` at which it can be found).
|
2131
2983
|
|
2132
2984
|
Raises:
|
2133
2985
|
CircuitError: If the supplied :obj:`~Bit` was of an unknown type.
|
2134
2986
|
CircuitError: If the supplied :obj:`~Bit` could not be found on the circuit.
|
2987
|
+
|
2988
|
+
Examples:
|
2989
|
+
Loop through a circuit, getting the qubit and clbit indices of each operation::
|
2990
|
+
|
2991
|
+
from qiskit.circuit import QuantumCircuit, Qubit
|
2992
|
+
|
2993
|
+
qc = QuantumCircuit(3, 3)
|
2994
|
+
qc.h(0)
|
2995
|
+
qc.cx(0, 1)
|
2996
|
+
qc.cx(1, 2)
|
2997
|
+
qc.measure([0, 1, 2], [0, 1, 2])
|
2998
|
+
|
2999
|
+
# The `.qubits` and `.clbits` fields are not integers.
|
3000
|
+
assert isinstance(qc.data[0].qubits[0], Qubit)
|
3001
|
+
# ... but we can use `find_bit` to retrieve them.
|
3002
|
+
assert qc.find_bit(qc.data[0].qubits[0]).index == 0
|
3003
|
+
|
3004
|
+
simple = [
|
3005
|
+
(
|
3006
|
+
instruction.operation.name,
|
3007
|
+
[qc.find_bit(bit).index for bit in instruction.qubits],
|
3008
|
+
[qc.find_bit(bit).index for bit in instruction.clbits],
|
3009
|
+
)
|
3010
|
+
for instruction in qc.data
|
3011
|
+
]
|
2135
3012
|
"""
|
2136
3013
|
|
2137
3014
|
try:
|
@@ -2157,18 +3034,22 @@ class QuantumCircuit:
|
|
2157
3034
|
parameter_map: dict[Parameter, ParameterValueType] | None = None,
|
2158
3035
|
label: str | None = None,
|
2159
3036
|
) -> Instruction:
|
2160
|
-
"""Create an Instruction out of this circuit.
|
3037
|
+
"""Create an :class:`~.circuit.Instruction` out of this circuit.
|
3038
|
+
|
3039
|
+
.. seealso::
|
3040
|
+
:func:`circuit_to_instruction`
|
3041
|
+
The underlying driver of this method.
|
2161
3042
|
|
2162
3043
|
Args:
|
2163
|
-
parameter_map
|
3044
|
+
parameter_map: For parameterized circuits, a mapping from
|
2164
3045
|
parameters in the circuit to parameters to be used in the
|
2165
3046
|
instruction. If None, existing circuit parameters will also
|
2166
3047
|
parameterize the instruction.
|
2167
|
-
label
|
3048
|
+
label: Optional gate label.
|
2168
3049
|
|
2169
3050
|
Returns:
|
2170
|
-
qiskit.circuit.Instruction: a composite instruction encapsulating this circuit
|
2171
|
-
|
3051
|
+
qiskit.circuit.Instruction: a composite instruction encapsulating this circuit (can be
|
3052
|
+
decomposed back).
|
2172
3053
|
"""
|
2173
3054
|
from qiskit.converters.circuit_to_instruction import circuit_to_instruction
|
2174
3055
|
|
@@ -2179,18 +3060,21 @@ class QuantumCircuit:
|
|
2179
3060
|
parameter_map: dict[Parameter, ParameterValueType] | None = None,
|
2180
3061
|
label: str | None = None,
|
2181
3062
|
) -> Gate:
|
2182
|
-
"""Create a Gate out of this circuit.
|
3063
|
+
"""Create a :class:`.Gate` out of this circuit. The circuit must act only qubits and
|
3064
|
+
contain only unitary operations.
|
3065
|
+
|
3066
|
+
.. seealso::
|
3067
|
+
:func:`circuit_to_gate`
|
3068
|
+
The underlying driver of this method.
|
2183
3069
|
|
2184
3070
|
Args:
|
2185
|
-
parameter_map
|
2186
|
-
|
2187
|
-
|
2188
|
-
|
2189
|
-
label (str): Optional gate label.
|
3071
|
+
parameter_map: For parameterized circuits, a mapping from parameters in the circuit to
|
3072
|
+
parameters to be used in the gate. If ``None``, existing circuit parameters will
|
3073
|
+
also parameterize the gate.
|
3074
|
+
label : Optional gate label.
|
2190
3075
|
|
2191
3076
|
Returns:
|
2192
|
-
Gate: a composite gate encapsulating this circuit
|
2193
|
-
(can be decomposed back)
|
3077
|
+
Gate: a composite gate encapsulating this circuit (can be decomposed back).
|
2194
3078
|
"""
|
2195
3079
|
from qiskit.converters.circuit_to_gate import circuit_to_gate
|
2196
3080
|
|
@@ -2417,79 +3301,74 @@ class QuantumCircuit:
|
|
2417
3301
|
|
2418
3302
|
def depth(
|
2419
3303
|
self,
|
2420
|
-
filter_function: Callable[
|
3304
|
+
filter_function: Callable[[CircuitInstruction], bool] = lambda x: not getattr(
|
2421
3305
|
x.operation, "_directive", False
|
2422
3306
|
),
|
2423
3307
|
) -> int:
|
2424
3308
|
"""Return circuit depth (i.e., length of critical path).
|
2425
3309
|
|
3310
|
+
.. warning::
|
3311
|
+
This operation is not well defined if the circuit contains control-flow operations.
|
3312
|
+
|
2426
3313
|
Args:
|
2427
|
-
filter_function
|
2428
|
-
Should take as
|
2429
|
-
Instructions for which the function returns False are ignored in the
|
2430
|
-
computation of the circuit depth.
|
2431
|
-
|
3314
|
+
filter_function: A function to decide which instructions count to increase depth.
|
3315
|
+
Should take as a single positional input a :class:`CircuitInstruction`.
|
3316
|
+
Instructions for which the function returns ``False`` are ignored in the
|
3317
|
+
computation of the circuit depth. By default filters out "directives", such as
|
3318
|
+
:class:`.Barrier`.
|
2432
3319
|
|
2433
3320
|
Returns:
|
2434
3321
|
int: Depth of circuit.
|
2435
3322
|
|
2436
|
-
|
2437
|
-
|
2438
|
-
|
3323
|
+
Examples:
|
3324
|
+
Simple calculation of total circuit depth::
|
3325
|
+
|
3326
|
+
from qiskit.circuit import QuantumCircuit
|
3327
|
+
qc = QuantumCircuit(4)
|
3328
|
+
qc.h(0)
|
3329
|
+
qc.cx(0, 1)
|
3330
|
+
qc.h(2)
|
3331
|
+
qc.cx(2, 3)
|
3332
|
+
assert qc.depth() == 2
|
3333
|
+
|
3334
|
+
Modifying the previous example to only calculate the depth of multi-qubit gates::
|
3335
|
+
|
3336
|
+
assert qc.depth(lambda instr: len(instr.qubits) > 1) == 1
|
2439
3337
|
"""
|
2440
|
-
|
2441
|
-
|
2442
|
-
bit_indices: dict[Qubit | Clbit, int] = {
|
2443
|
-
bit: idx for idx, bit in enumerate(self.qubits + self.clbits)
|
3338
|
+
obj_depths = {
|
3339
|
+
obj: 0 for objects in (self.qubits, self.clbits, self.iter_vars()) for obj in objects
|
2444
3340
|
}
|
2445
3341
|
|
2446
|
-
|
2447
|
-
|
2448
|
-
|
3342
|
+
def update_from_expr(objects, node):
|
3343
|
+
for var in expr.iter_vars(node):
|
3344
|
+
if var.standalone:
|
3345
|
+
objects.add(var)
|
3346
|
+
else:
|
3347
|
+
objects.update(_builder_utils.node_resources(var).clbits)
|
2449
3348
|
|
2450
|
-
# A list that holds the height of each qubit
|
2451
|
-
# and classical bit.
|
2452
|
-
op_stack = [0] * len(bit_indices)
|
2453
|
-
|
2454
|
-
# Here we are playing a modified version of
|
2455
|
-
# Tetris where we stack gates, but multi-qubit
|
2456
|
-
# gates, or measurements have a block for each
|
2457
|
-
# qubit or cbit that are connected by a virtual
|
2458
|
-
# line so that they all stacked at the same depth.
|
2459
|
-
# Conditional gates act on all cbits in the register
|
2460
|
-
# they are conditioned on.
|
2461
|
-
# The max stack height is the circuit depth.
|
2462
3349
|
for instruction in self._data:
|
2463
|
-
|
2464
|
-
|
2465
|
-
|
2466
|
-
|
2467
|
-
|
2468
|
-
reg_ints.append(bit_indices[reg])
|
2469
|
-
if filter_function(instruction):
|
2470
|
-
levels.append(op_stack[reg_ints[ind]] + 1)
|
2471
|
-
else:
|
2472
|
-
levels.append(op_stack[reg_ints[ind]])
|
2473
|
-
# Assuming here that there is no conditional
|
2474
|
-
# snapshots or barriers ever.
|
2475
|
-
if getattr(instruction.operation, "condition", None):
|
2476
|
-
# Controls operate over all bits of a classical register
|
2477
|
-
# or over a single bit
|
2478
|
-
if isinstance(instruction.operation.condition[0], Clbit):
|
2479
|
-
condition_bits = [instruction.operation.condition[0]]
|
3350
|
+
objects = set(itertools.chain(instruction.qubits, instruction.clbits))
|
3351
|
+
if (condition := getattr(instruction.operation, "condition", None)) is not None:
|
3352
|
+
objects.update(_builder_utils.condition_resources(condition).clbits)
|
3353
|
+
if isinstance(condition, expr.Expr):
|
3354
|
+
update_from_expr(objects, condition)
|
2480
3355
|
else:
|
2481
|
-
|
2482
|
-
|
2483
|
-
|
2484
|
-
|
2485
|
-
|
2486
|
-
|
2487
|
-
|
2488
|
-
|
2489
|
-
|
2490
|
-
|
2491
|
-
|
2492
|
-
|
3356
|
+
objects.update(_builder_utils.condition_resources(condition).clbits)
|
3357
|
+
elif isinstance(instruction.operation, SwitchCaseOp):
|
3358
|
+
update_from_expr(objects, expr.lift(instruction.operation.target))
|
3359
|
+
elif isinstance(instruction.operation, Store):
|
3360
|
+
update_from_expr(objects, instruction.operation.lvalue)
|
3361
|
+
update_from_expr(objects, instruction.operation.rvalue)
|
3362
|
+
|
3363
|
+
# If we're counting this as adding to depth, do so. If not, it still functions as a
|
3364
|
+
# data synchronisation point between the objects (think "barrier"), so the depths still
|
3365
|
+
# get updated to match the current max over the affected objects.
|
3366
|
+
new_depth = max((obj_depths[obj] for obj in objects), default=0)
|
3367
|
+
if filter_function(instruction):
|
3368
|
+
new_depth += 1
|
3369
|
+
for obj in objects:
|
3370
|
+
obj_depths[obj] = new_depth
|
3371
|
+
return max(obj_depths.values(), default=0)
|
2493
3372
|
|
2494
3373
|
def width(self) -> int:
|
2495
3374
|
"""Return number of qubits plus clbits in circuit.
|
@@ -2761,6 +3640,8 @@ class QuantumCircuit:
|
|
2761
3640
|
[(ParameterTable.GLOBAL_PHASE, None)]
|
2762
3641
|
)
|
2763
3642
|
cpy._data = CircuitData(self._data.qubits, self._data.clbits)
|
3643
|
+
# Invalidate parameters caching.
|
3644
|
+
cpy._parameters = None
|
2764
3645
|
|
2765
3646
|
cpy._calibrations = _copy.deepcopy(self._calibrations)
|
2766
3647
|
cpy._metadata = _copy.deepcopy(self._metadata)
|
@@ -2773,6 +3654,11 @@ class QuantumCircuit:
|
|
2773
3654
|
"""Clear all instructions in self.
|
2774
3655
|
|
2775
3656
|
Clearing the circuits will keep the metadata and calibrations.
|
3657
|
+
|
3658
|
+
.. seealso::
|
3659
|
+
:meth:`copy_empty_like`
|
3660
|
+
A method to produce a new circuit with no instructions and all the same tracking of
|
3661
|
+
quantum and classical typed data, but without mutating the original circuit.
|
2776
3662
|
"""
|
2777
3663
|
self._data.clear()
|
2778
3664
|
self._parameter_table.clear()
|
@@ -3007,6 +3893,28 @@ class QuantumCircuit:
|
|
3007
3893
|
Measurements and barriers are considered final if they are
|
3008
3894
|
followed by no other operations (aside from other measurements or barriers.)
|
3009
3895
|
|
3896
|
+
.. note::
|
3897
|
+
This method has rather complex behavior, particularly around the removal of newly idle
|
3898
|
+
classical bits and registers. It is much more efficient to avoid adding unnecessary
|
3899
|
+
classical data in the first place, rather than trying to remove it later.
|
3900
|
+
|
3901
|
+
.. seealso::
|
3902
|
+
:class:`.RemoveFinalMeasurements`
|
3903
|
+
A transpiler pass that removes final measurements and barriers. This does not
|
3904
|
+
remove the classical data. If this is your goal, you can call that with::
|
3905
|
+
|
3906
|
+
from qiskit.circuit import QuantumCircuit
|
3907
|
+
from qiskit.transpiler.passes import RemoveFinalMeasurements
|
3908
|
+
|
3909
|
+
qc = QuantumCircuit(2, 2)
|
3910
|
+
qc.h(0)
|
3911
|
+
qc.cx(0, 1)
|
3912
|
+
qc.barrier()
|
3913
|
+
qc.measure([0, 1], [0, 1])
|
3914
|
+
|
3915
|
+
pass_ = RemoveFinalMeasurements()
|
3916
|
+
just_bell = pass_(qc)
|
3917
|
+
|
3010
3918
|
Args:
|
3011
3919
|
inplace (bool): All measurements removed inplace or return new circuit.
|
3012
3920
|
|
@@ -3110,7 +4018,7 @@ class QuantumCircuit:
|
|
3110
4018
|
|
3111
4019
|
@property
|
3112
4020
|
def global_phase(self) -> ParameterValueType:
|
3113
|
-
"""
|
4021
|
+
"""The global phase of the current circuit scope in radians."""
|
3114
4022
|
if self._control_flow_scopes:
|
3115
4023
|
return self._control_flow_scopes[-1].global_phase
|
3116
4024
|
return self._global_phase
|
@@ -5206,15 +6114,7 @@ class QuantumCircuit:
|
|
5206
6114
|
)
|
5207
6115
|
|
5208
6116
|
@typing.overload
|
5209
|
-
def if_test(
|
5210
|
-
self,
|
5211
|
-
condition: tuple[ClassicalRegister | Clbit, int],
|
5212
|
-
true_body: None,
|
5213
|
-
qubits: None,
|
5214
|
-
clbits: None,
|
5215
|
-
*,
|
5216
|
-
label: str | None,
|
5217
|
-
) -> IfContext: ...
|
6117
|
+
def if_test(self, condition: tuple[ClassicalRegister | Clbit, int]) -> IfContext: ...
|
5218
6118
|
|
5219
6119
|
@typing.overload
|
5220
6120
|
def if_test(
|