-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
quantumcircuit.py
6793 lines (5587 loc) · 286 KB
/
quantumcircuit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=bad-docstring-quotes,invalid-name
"""Quantum circuit object."""
from __future__ import annotations
import collections.abc
import copy as _copy
import itertools
import multiprocessing as mp
import typing
from collections import OrderedDict, defaultdict, namedtuple
from typing import (
Union,
Optional,
Tuple,
Type,
TypeVar,
Sequence,
Callable,
Mapping,
Iterable,
Any,
DefaultDict,
Literal,
overload,
)
import numpy as np
from qiskit._accelerate.circuit import CircuitData
from qiskit._accelerate.circuit import StandardGate
from qiskit.exceptions import QiskitError
from qiskit.utils.multiprocessing import is_main_process
from qiskit.circuit.instruction import Instruction
from qiskit.circuit.gate import Gate
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.exceptions import CircuitError
from qiskit.utils import deprecate_func
from . import _classical_resource_map
from .controlflow import ControlFlowOp, _builder_utils
from .controlflow.builder import CircuitScopeInterface, ControlFlowBuilderBlock
from .controlflow.break_loop import BreakLoopOp, BreakLoopPlaceholder
from .controlflow.continue_loop import ContinueLoopOp, ContinueLoopPlaceholder
from .controlflow.for_loop import ForLoopOp, ForLoopContext
from .controlflow.if_else import IfElseOp, IfContext
from .controlflow.switch_case import SwitchCaseOp, SwitchContext
from .controlflow.while_loop import WhileLoopOp, WhileLoopContext
from .classical import expr, types
from .parameterexpression import ParameterExpression, ParameterValueType
from .quantumregister import QuantumRegister, Qubit, AncillaRegister, AncillaQubit
from .classicalregister import ClassicalRegister, Clbit
from .parametertable import ParameterView
from .parametervector import ParameterVector
from .instructionset import InstructionSet
from .operation import Operation
from .register import Register
from .bit import Bit
from .quantumcircuitdata import QuantumCircuitData, CircuitInstruction
from .delay import Delay
from .store import Store
if typing.TYPE_CHECKING:
import qiskit # pylint: disable=cyclic-import
from qiskit.transpiler.layout import TranspileLayout # pylint: disable=cyclic-import
from qiskit.quantum_info.operators.base_operator import BaseOperator
from qiskit.quantum_info.states.statevector import Statevector # pylint: disable=cyclic-import
BitLocations = namedtuple("BitLocations", ("index", "registers"))
# The following types are not marked private to avoid leaking this "private/public" abstraction out
# into the documentation. They are not imported by circuit.__init__, nor are they meant to be.
# Arbitrary type variables for marking up generics.
S = TypeVar("S")
T = TypeVar("T")
# Types that can be coerced to a valid Qubit specifier in a circuit.
QubitSpecifier = Union[
Qubit,
QuantumRegister,
int,
slice,
Sequence[Union[Qubit, int]],
]
# Types that can be coerced to a valid Clbit specifier in a circuit.
ClbitSpecifier = Union[
Clbit,
ClassicalRegister,
int,
slice,
Sequence[Union[Clbit, int]],
]
# Generic type which is either :obj:`~Qubit` or :obj:`~Clbit`, used to specify types of functions
# which operate on either type of bit, but not both at the same time.
BitType = TypeVar("BitType", Qubit, Clbit)
# NOTE:
#
# If you're adding methods or attributes to `QuantumCircuit`, be sure to update the class docstring
# to document them in a suitable place. The class is huge, so we do its documentation manually so
# it has at least some amount of organizational structure.
class QuantumCircuit:
"""Core Qiskit representation of a quantum circuit.
.. note::
For more details setting the :class:`QuantumCircuit` in context of all of the data
structures that go with it, how it fits into the rest of the :mod:`qiskit` package, and the
different regimes of quantum-circuit descriptions in Qiskit, see the module-level
documentation of :mod:`qiskit.circuit`.
Circuit attributes
==================
:class:`QuantumCircuit` has a small number of public attributes, which are mostly older
functionality. Most of its functionality is accessed through methods.
A small handful of the attributes are intentionally mutable, the rest are data attributes that
should be considered immutable.
========================= ======================================================================
Mutable attribute Summary
========================= ======================================================================
:attr:`global_phase` The global phase of the circuit, measured in radians.
:attr:`metadata` Arbitrary user mapping, which Qiskit will preserve through the
transpiler, but otherwise completely ignore.
:attr:`name` An optional string name for the circuit.
========================= ======================================================================
========================= ======================================================================
Immutable data attribute Summary
========================= ======================================================================
:attr:`ancillas` List of :class:`AncillaQubit`\\ s tracked by the circuit.
:attr:`calibrations` Custom user-supplied pulse calibrations for individual instructions.
:attr:`cregs` List of :class:`ClassicalRegister`\\ s tracked by the circuit.
:attr:`clbits` List of :class:`Clbit`\\ s tracked by the circuit.
:attr:`data` List of individual :class:`CircuitInstruction`\\ s that make up the
circuit.
:attr:`duration` Total duration of the circuit, added by scheduling transpiler passes.
:attr:`layout` Hardware layout and routing information added by the transpiler.
:attr:`num_ancillas` The number of ancilla qubits in the circuit.
:attr:`num_clbits` The number of clbits in the circuit.
:attr:`num_captured_vars` Number of captured real-time classical variables.
:attr:`num_declared_vars` Number of locally declared real-time classical variables in the outer
circuit scope.
:attr:`num_input_vars` Number of input real-time classical variables.
:attr:`num_parameters` Number of compile-time :class:`Parameter`\\ s in the circuit.
:attr:`num_qubits` Number of qubits in the circuit.
:attr:`num_vars` Total number of real-time classical variables in the outer circuit
scope.
:attr:`op_start_times` Start times of scheduled operations, added by scheduling transpiler
passes.
:attr:`parameters` Ordered set-like view of the compile-time :class:`Parameter`\\ s
tracked by the circuit.
:attr:`qregs` List of :class:`QuantumRegister`\\ s tracked by the circuit.
:attr:`qubits` List of :class:`Qubit`\\ s tracked by the circuit.
:attr:`unit` The unit of the :attr:`duration` field.
========================= ======================================================================
The core attribute is :attr:`data`. This is a sequence-like object that exposes the
:class:`CircuitInstruction`\\ s contained in an ordered form. You generally should not mutate
this object directly; :class:`QuantumCircuit` is only designed for append-only operations (which
should use :meth:`append`). Most operations that mutate circuits in place should be written as
transpiler passes (:mod:`qiskit.transpiler`).
.. autoattribute:: data
Alongside the :attr:`data`, the :attr:`global_phase` of a circuit can have some impact on its
output, if the circuit is used to describe a :class:`.Gate` that may be controlled. This is
measured in radians and is directly settable.
.. autoattribute:: global_phase
The :attr:`name` of a circuit becomes the name of the :class:`~.circuit.Instruction` or
:class:`.Gate` resulting from :meth:`to_instruction` and :meth:`to_gate` calls, which can be
handy for visualizations.
.. autoattribute:: name
You can attach arbitrary :attr:`metadata` to a circuit. No part of core Qiskit will inspect
this or change its behavior based on metadata, but it will be faithfully passed through the
transpiler, so you can tag your circuits yourself. When serializing a circuit with QPY (see
:mod:`qiskit.qpy`), the metadata will be JSON-serialized and you may need to pass a custom
serializer to handle non-JSON-compatible objects within it (see :func:`.qpy.dump` for more
detail). This field is ignored during export to OpenQASM 2 or 3.
.. autoattribute:: metadata
:class:`QuantumCircuit` exposes data attributes tracking its internal quantum and classical bits
and registers. These appear as Python :class:`list`\\ s, but you should treat them as
immutable; changing them will *at best* have no effect, and more likely will simply corrupt
the internal data of the :class:`QuantumCircuit`.
.. autoattribute:: qregs
.. autoattribute:: cregs
.. autoattribute:: qubits
.. autoattribute:: ancillas
.. autoattribute:: clbits
The :ref:`compile-time parameters <circuit-compile-time-parameters>` present in instructions on
the circuit are available in :attr:`parameters`. This has a canonical order (mostly lexical,
except in the case of :class:`.ParameterVector`), which matches the order that parameters will
be assigned when using the list forms of :meth:`assign_parameters`, but also supports
:class:`set`-like constant-time membership testing.
.. autoattribute:: parameters
The storage of any :ref:`manual pulse-level calibrations <circuit-calibrations>` for individual
instructions on the circuit is in :attr:`calibrations`. This presents as a :class:`dict`, but
should not be mutated directly; use the methods discussed in :ref:`circuit-calibrations`.
.. autoattribute:: calibrations
If you have transpiled your circuit, so you have a physical circuit, you can inspect the
:attr:`layout` attribute for information stored by the transpiler about how the virtual qubits
of the source circuit map to the hardware qubits of your physical circuit, both at the start and
end of the circuit.
.. autoattribute:: layout
If your circuit was also *scheduled* as part of a transpilation, it will expose the individual
timings of each instruction, along with the total :attr:`duration` of the circuit.
.. autoattribute:: duration
.. autoattribute:: unit
.. autoattribute:: op_start_times
Finally, :class:`QuantumCircuit` exposes several simple properties as dynamic read-only numeric
attributes.
.. autoattribute:: num_ancillas
.. autoattribute:: num_clbits
.. autoattribute:: num_captured_vars
.. autoattribute:: num_declared_vars
.. autoattribute:: num_input_vars
.. autoattribute:: num_parameters
.. autoattribute:: num_qubits
.. autoattribute:: num_vars
Creating new circuits
=====================
========================= =====================================================================
Method Summary
========================= =====================================================================
:meth:`__init__` Default constructor of no-instruction circuits.
:meth:`copy` Make a complete copy of an existing circuit.
:meth:`copy_empty_like` Copy data objects from one circuit into a new one without any
instructions.
:meth:`from_instructions` Infer data objects needed from a list of instructions.
:meth:`from_qasm_file` Legacy interface to :func:`.qasm2.load`.
:meth:`from_qasm_str` Legacy interface to :func:`.qasm2.loads`.
========================= =====================================================================
The default constructor (``QuantumCircuit(...)``) produces a circuit with no initial
instructions. The arguments to the default constructor can be used to seed the circuit with
quantum and classical data storage, and to provide a name, global phase and arbitrary metadata.
All of these fields can be expanded later.
.. automethod:: __init__
If you have an existing circuit, you can produce a copy of it using :meth:`copy`, including all
its instructions. This is useful if you want to keep partial circuits while extending another,
or to have a version you can mutate in-place while leaving the prior one intact.
.. automethod:: copy
Similarly, if you want a circuit that contains all the same data objects (bits, registers,
variables, etc) but with none of the instructions, you can use :meth:`copy_empty_like`. This is
quite common when you want to build up a new layer of a circuit to then use apply onto the back
with :meth:`compose`, or to do a full rewrite of a circuit's instructions.
.. automethod:: copy_empty_like
In some cases, it is most convenient to generate a list of :class:`.CircuitInstruction`\\ s
separately to an entire circuit context, and then to build a circuit from this. The
:meth:`from_instructions` constructor will automatically capture all :class:`.Qubit` and
:class:`.Clbit` instances used in the instructions, and create a new :class:`QuantumCircuit`
object that has the correct resources and all the instructions.
.. automethod:: from_instructions
:class:`QuantumCircuit` also still has two constructor methods that are legacy wrappers around
the importers in :mod:`qiskit.qasm2`. These automatically apply :ref:`the legacy compatibility
settings <qasm2-legacy-compatibility>` of :func:`~.qasm2.load` and :func:`~.qasm2.loads`.
.. automethod:: from_qasm_file
.. automethod:: from_qasm_str
Data objects on circuits
========================
.. _circuit-adding-data-objects:
Adding data objects
-------------------
============================= =================================================================
Method Adds this kind of data
============================= =================================================================
:meth:`add_bits` :class:`.Qubit`\\ s and :class:`.Clbit`\\ s.
:meth:`add_register` :class:`.QuantumRegister` and :class:`.ClassicalRegister`.
:meth:`add_var` :class:`~.expr.Var` nodes with local scope and initializers.
:meth:`add_input` :class:`~.expr.Var` nodes that are treated as circuit inputs.
:meth:`add_capture` :class:`~.expr.Var` nodes captured from containing scopes.
:meth:`add_uninitialized_var` :class:`~.expr.Var` nodes with local scope and undefined state.
============================= =================================================================
Typically you add most of the data objects (:class:`.Qubit`, :class:`.Clbit`,
:class:`.ClassicalRegister`, etc) to the circuit as part of using the :meth:`__init__` default
constructor, or :meth:`copy_empty_like`. However, it is also possible to add these afterwards.
Typed classical data, such as standalone :class:`~.expr.Var` nodes (see
:ref:`circuit-repr-real-time-classical`), can be both constructed and added with separate
methods.
New registerless :class:`.Qubit` and :class:`.Clbit` objects are added using :meth:`add_bits`.
These objects must not already be present in the circuit. You can check if a bit exists in the
circuit already using :meth:`find_bit`.
.. automethod:: add_bits
Registers are added to the circuit with :meth:`add_register`. In this method, it is not an
error if some of the bits are already present in the circuit. In this case, the register will
be an "alias" over the bits. This is not generally well-supported by hardware backends; it is
probably best to stay away from relying on it. The registers a given bit is in are part of the
return of :meth:`find_bit`.
.. automethod:: add_register
:ref:`Real-time, typed classical data <circuit-repr-real-time-classical>` is represented on the
circuit by :class:`~.expr.Var` nodes with a well-defined :class:`~.types.Type`. It is possible
to instantiate these separately to a circuit (see :meth:`.Var.new`), but it is often more
convenient to use circuit methods that will automatically manage the types and expression
initialization for you. The two most common methods are :meth:`add_var` (locally scoped
variables) and :meth:`add_input` (inputs to the circuit).
.. automethod:: add_var
.. automethod:: add_input
In addition, there are two lower-level methods that can be useful for programmatic generation of
circuits. When working interactively, you will most likely not need these; most uses of
:meth:`add_uninitialized_var` are part of :meth:`copy_empty_like`, and most uses of
:meth:`add_capture` would be better off using :ref:`the control-flow builder interface
<circuit-control-flow-methods>`.
.. automethod:: add_uninitialized_var
.. automethod:: add_capture
Working with bits and registers
-------------------------------
A :class:`.Bit` instance is, on its own, just a unique handle for circuits to use in their own
contexts. If you have got a :class:`.Bit` instance and a circuit, just can find the contexts
that the bit exists in using :meth:`find_bit`, such as its integer index in the circuit and any
registers it is contained in.
.. automethod:: find_bit
Similarly, you can query a circuit to see if a register has already been added to it by using
:meth:`has_register`.
.. automethod:: has_register
Working with compile-time parameters
------------------------------------
.. seealso::
:ref:`circuit-compile-time-parameters`
A more complete discussion of what compile-time parametrization is, and how it fits into
Qiskit's data model.
Unlike bits, registers, and real-time typed classical data, compile-time symbolic parameters are
not manually added to a circuit. Their presence is inferred by being contained in operations
added to circuits and the global phase. An ordered list of all parameters currently in a
circuit is at :attr:`QuantumCircuit.parameters`.
The most common operation on :class:`.Parameter` instances is to replace them in symbolic
operations with some numeric value, or another symbolic expression. This is done with
:meth:`assign_parameters`.
.. automethod:: assign_parameters
The circuit tracks parameters by :class:`.Parameter` instances themselves, and forbids having
multiple parameters of the same name to avoid some problems when interoperating with OpenQASM or
other external formats. You can use :meth:`has_parameter` and :meth:`get_parameter` to query
the circuit for a parameter with the given string name.
.. automethod:: has_parameter
.. automethod:: get_parameter
.. _circuit-real-time-methods:
Working with real-time typed classical data
-------------------------------------------
.. seealso::
:mod:`qiskit.circuit.classical`
Module-level documentation for how the variable-, expression- and type-systems work, the
objects used to represent them, and the classical operations available.
:ref:`circuit-repr-real-time-classical`
A discussion of how real-time data fits into the entire :mod:`qiskit.circuit` data model
as a whole.
:ref:`circuit-adding-data-objects`
The methods for adding new :class:`~.expr.Var` variables to a circuit after
initialization.
You can retrive a :class:`~.expr.Var` instance attached to a circuit by using its variable name
using :meth:`get_var`, or check if a circuit contains a given variable with :meth:`has_var`.
.. automethod:: get_var
.. automethod:: has_var
There are also several iterator methods that you can use to get the full set of variables
tracked by a circuit. At least one of :meth:`iter_input_vars` and :meth:`iter_captured_vars`
will be empty, as inputs and captures are mutually exclusive. All of the iterators have
corresponding dynamic properties on :class:`QuantumCircuit` that contain their length:
:attr:`num_vars`, :attr:`num_input_vars`, :attr:`num_captured_vars` and
:attr:`num_declared_vars`.
.. automethod:: iter_vars
.. automethod:: iter_input_vars
.. automethod:: iter_captured_vars
.. automethod:: iter_declared_vars
.. _circuit-adding-operations:
Adding operations to circuits
=============================
You can add anything that implements the :class:`.Operation` interface to a circuit as a single
instruction, though most things you will want to add will be :class:`~.circuit.Instruction` or
:class:`~.circuit.Gate` instances.
.. seealso::
:ref:`circuit-operations-instructions`
The :mod:`qiskit.circuit`-level documentation on the different interfaces that Qiskit
uses to define circuit-level instructions.
.. _circuit-append-compose:
Methods to add general operations
---------------------------------
These are the base methods that handle adding any object, including user-defined ones, onto
circuits.
=============== ===============================================================================
Method When to use it
=============== ===============================================================================
:meth:`append` Add an instruction as a single object onto a circuit.
:meth:`_append` Same as :meth:`append`, but a low-level interface that elides almost all error
checking.
:meth:`compose` Inline the instructions from one circuit onto another.
:meth:`tensor` Like :meth:`compose`, but strictly for joining circuits that act on disjoint
qubits.
=============== ===============================================================================
:class:`QuantumCircuit` has two main ways that you will add more operations onto a circuit.
Which to use depends on whether you want to add your object as a single "instruction"
(:meth:`append`), or whether you want to join the instructions from two circuits together
(:meth:`compose`).
A single instruction or operation appears as a single entry in the :attr:`data` of the circuit,
and as a single box when drawn in the circuit visualizers (see :meth:`draw`). A single
instruction is the "unit" that a hardware backend might be defined in terms of (see
:class:`.Target`). An :class:`~.circuit.Instruction` can come with a
:attr:`~.circuit.Instruction.definition`, which is one rule the transpiler (see
:mod:`qiskit.transpiler`) will be able to fall back on to decompose it for hardware, if needed.
An :class:`.Operation` that is not also an :class:`~.circuit.Instruction` can
only be decomposed if it has some associated high-level synthesis method registered for it (see
:mod:`qiskit.transpiler.passes.synthesis.plugin`).
A :class:`QuantumCircuit` alone is not a single :class:`~.circuit.Instruction`; it is rather
more complicated, since it can, in general, represent a complete program with typed classical
memory inputs and outputs, and control flow. Qiskit's (and most hardware's) data model does not
yet have the concept of re-usable callable subroutines with virtual quantum operands. You can
convert simple circuits that act only on qubits with unitary operations into a :class:`.Gate`
using :meth:`to_gate`, and simple circuits acting only on qubits and clbits into a
:class:`~.circuit.Instruction` with :meth:`to_instruction`.
When you have an :class:`.Operation`, :class:`~.circuit.Instruction`, or :class:`.Gate`, add it
to the circuit, specifying the qubit and clbit arguments with :meth:`append`.
.. automethod:: append
:meth:`append` does quite substantial error checking to ensure that you cannot accidentally
break the data model of :class:`QuantumCircuit`. If you are programmatically generating a
circuit from known-good data, you can elide much of this error checking by using the fast-path
appender :meth:`_append`, but at the risk that the caller is responsible for ensuring they are
passing only valid data.
.. automethod:: _append
In other cases, you may want to join two circuits together, applying the instructions from one
circuit onto specified qubits and clbits on another circuit. This "inlining" operation is
called :meth:`compose` in Qiskit. :meth:`compose` is, in general, more powerful than
a :meth:`to_instruction`-plus-:meth:`append` combination for joining two circuits, because it
can also link typed classical data together, and allows for circuit control-flow operations to
be joined onto another circuit.
The downsides to :meth:`compose` are that it is a more complex operation that can involve more
rewriting of the operand, and that it necessarily must move data from one circuit object to
another. If you are building up a circuit for yourself and raw performance is a core goal,
consider passing around your base circuit and having different parts of your algorithm write
directly to the base circuit, rather than building a temporary layer circuit.
.. automethod:: compose
If you are trying to join two circuits that will apply to completely disjoint qubits and clbits,
:meth:`tensor` is a convenient wrapper around manually adding bit objects and calling
:meth:`compose`.
.. automethod:: tensor
As some rules of thumb:
* If you have a single :class:`.Operation`, :class:`~.circuit.Instruction` or :class:`.Gate`,
you should definitely use :meth:`append` or :meth:`_append`.
* If you have a :class:`QuantumCircuit` that represents a single atomic instruction for a larger
circuit that you want to re-use, you probably want to call :meth:`to_instruction` or
:meth:`to_gate`, and then apply the result of that to the circuit using :meth:`append`.
* If you have a :class:`QuantumCircuit` that represents a larger "layer" of another circuit, or
contains typed classical variables or control flow, you should use :meth:`compose` to merge it
onto another circuit.
* :meth:`tensor` is wanted far more rarely than either :meth:`append` or :meth:`compose`.
Internally, it is mostly a wrapper around :meth:`add_bits` and :meth:`compose`.
Some potential pitfalls to beware of:
* Even if you re-use a custom :class:`~.circuit.Instruction` during circuit construction, the
transpiler will generally have to "unroll" each invocation of it to its inner decomposition
before beginning work on it. This should not prevent you from using the
:meth:`to_instruction`-plus-:meth:`append` pattern, as the transpiler will improve in this
regard over time.
* :meth:`compose` will, by default, produce a new circuit for backwards compatibility. This is
more expensive, and not usually what you want, so you should set ``inplace=True``.
* Both :meth:`append` and :meth:`compose` (but not :meth:`_append`) have a ``copy`` keyword
argument that defaults to ``True``. In these cases, the incoming :class:`.Operation`
instances will be copied if Qiskit detects that the objects have mutability about them (such
as taking gate parameters). If you are sure that you will not re-use the objects again in
other places, you should set ``copy=False`` to prevent this copying, which can be a
substantial speed-up for large objects.
Methods to add standard instructions
------------------------------------
The :class:`QuantumCircuit` class has helper methods to add many of the Qiskit standard-library
instructions and gates onto a circuit. These are generally equivalent to manually constructing
an instance of the relevent :mod:`qiskit.circuit.library` object, then passing that to
:meth:`append` with the remaining arguments placed into the ``qargs`` and ``cargs`` fields as
appropriate.
The following methods apply special non-unitary :class:`~.circuit.Instruction` operations to the
circuit:
=============================== ====================================================
:class:`QuantumCircuit` method :mod:`qiskit.circuit` :class:`~.circuit.Instruction`
=============================== ====================================================
:meth:`barrier` :class:`Barrier`
:meth:`delay` :class:`Delay`
:meth:`initialize` :class:`~library.Initialize`
:meth:`measure` :class:`Measure`
:meth:`reset` :class:`Reset`
:meth:`store` :class:`Store`
=============================== ====================================================
These methods apply uncontrolled unitary :class:`.Gate` instances to the circuit:
=============================== ============================================
:class:`QuantumCircuit` method :mod:`qiskit.circuit.library` :class:`.Gate`
=============================== ============================================
:meth:`dcx` :class:`~library.DCXGate`
:meth:`ecr` :class:`~library.ECRGate`
:meth:`h` :class:`~library.HGate`
:meth:`id` :class:`~library.IGate`
:meth:`iswap` :class:`~library.iSwapGate`
:meth:`ms` :class:`~library.MSGate`
:meth:`p` :class:`~library.PhaseGate`
:meth:`pauli` :class:`~library.PauliGate`
:meth:`prepare_state` :class:`~library.StatePreparation`
:meth:`r` :class:`~library.RGate`
:meth:`rcccx` :class:`~library.RC3XGate`
:meth:`rccx` :class:`~library.RCCXGate`
:meth:`rv` :class:`~library.RVGate`
:meth:`rx` :class:`~library.RXGate`
:meth:`rxx` :class:`~library.RXXGate`
:meth:`ry` :class:`~library.RYGate`
:meth:`ryy` :class:`~library.RYYGate`
:meth:`rz` :class:`~library.RZGate`
:meth:`rzx` :class:`~library.RZXGate`
:meth:`rzz` :class:`~library.RZZGate`
:meth:`s` :class:`~library.SGate`
:meth:`sdg` :class:`~library.SdgGate`
:meth:`swap` :class:`~library.SwapGate`
:meth:`sx` :class:`~library.SXGate`
:meth:`sxdg` :class:`~library.SXdgGate`
:meth:`t` :class:`~library.TGate`
:meth:`tdg` :class:`~library.TdgGate`
:meth:`u` :class:`~library.UGate`
:meth:`unitary` :class:`~library.UnitaryGate`
:meth:`x` :class:`~library.XGate`
:meth:`y` :class:`~library.YGate`
:meth:`z` :class:`~library.ZGate`
=============================== ============================================
The following methods apply :class:`Gate` instances that are also controlled gates, so are
direct subclasses of :class:`ControlledGate`:
=============================== ======================================================
:class:`QuantumCircuit` method :mod:`qiskit.circuit.library` :class:`.ControlledGate`
=============================== ======================================================
:meth:`ccx` :class:`~library.CCXGate`
:meth:`ccz` :class:`~library.CCZGate`
:meth:`ch` :class:`~library.CHGate`
:meth:`cp` :class:`~library.CPhaseGate`
:meth:`crx` :class:`~library.CRXGate`
:meth:`cry` :class:`~library.CRYGate`
:meth:`crz` :class:`~library.CRZGate`
:meth:`cs` :class:`~library.CSGate`
:meth:`csdg` :class:`~library.CSdgGate`
:meth:`cswap` :class:`~library.CSwapGate`
:meth:`csx` :class:`~library.CSXGate`
:meth:`cu` :class:`~library.CUGate`
:meth:`cx` :class:`~library.CXGate`
:meth:`cy` :class:`~library.CYGate`
:meth:`cz` :class:`~library.CZGate`
=============================== ======================================================
Finally, these methods apply particular generalized multiply controlled gates to the circuit,
often with eager syntheses. They are listed in terms of the *base* gate they are controlling,
since their exact output is often a synthesized version of a gate.
=============================== =================================================
:class:`QuantumCircuit` method Base :mod:`qiskit.circuit.library` :class:`.Gate`
=============================== =================================================
:meth:`mcp` :class:`~library.PhaseGate`
:meth:`mcrx` :class:`~library.RXGate`
:meth:`mcry` :class:`~library.RYGate`
:meth:`mcrz` :class:`~library.RZGate`
:meth:`mcx` :class:`~library.XGate`
=============================== =================================================
The rest of this section is the API listing of all the individual methods; the tables above are
summaries whose links will jump you to the correct place.
.. automethod:: barrier
.. automethod:: ccx
.. automethod:: ccz
.. automethod:: ch
.. automethod:: cp
.. automethod:: crx
.. automethod:: cry
.. automethod:: crz
.. automethod:: cs
.. automethod:: csdg
.. automethod:: cswap
.. automethod:: csx
.. automethod:: cu
.. automethod:: cx
.. automethod:: cy
.. automethod:: cz
.. automethod:: dcx
.. automethod:: delay
.. automethod:: ecr
.. automethod:: h
.. automethod:: id
.. automethod:: initialize
.. automethod:: iswap
.. automethod:: mcp
.. automethod:: mcrx
.. automethod:: mcry
.. automethod:: mcrz
.. automethod:: mcx
.. automethod:: measure
.. automethod:: ms
.. automethod:: p
.. automethod:: pauli
.. automethod:: prepare_state
.. automethod:: r
.. automethod:: rcccx
.. automethod:: rccx
.. automethod:: reset
.. automethod:: rv
.. automethod:: rx
.. automethod:: rxx
.. automethod:: ry
.. automethod:: ryy
.. automethod:: rz
.. automethod:: rzx
.. automethod:: rzz
.. automethod:: s
.. automethod:: sdg
.. automethod:: store
.. automethod:: swap
.. automethod:: sx
.. automethod:: sxdg
.. automethod:: t