
    z	iV
             	      d   S r SSKJr  SSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKJr  SSK
JrJrJrJrJrJrJrJrJrJrJrJr  SSKJr  SSKrSSKJr  SSKJr  SS	KJr  SS
K J!r!  SSK"J#r#  SSK$J%r%  SSK&J'r'  SSK(J)r)  SSK*J+r+  SSK,J-r-J.r.  SSK/J0r0J1r1J2r2J3r3J4r4J5r5J6r6J7r7  SSK/J8r8  SSK9J:r:J;r;  SSK<J=r=J>r>  SSK?J@r@JArA  SSKBJCrCJDrD  SSKEJFrFJGrG  SSKHJIrIJJrJ  SSKKJLrLJMrM  SSKNJOrOJPrP  SSKQJRrRJSrS  SSKTJUrUJVrV  SSKWJXrXJYrY  SSKZJ[r[  SS K\J]r]  SS!K^J_r_  SS"K`Jara  SS#KbJcrcJdrd  SS$KeJfrf  SS%KgJhrh  \
R                  (       a  SSKjrjSS&KkJlrl  SS'KmJnrn  SS(KoJprp  SS)KqJrrr  \" S*5      rs\" S+5      rt\\2\1\u\v\\\2\u4      4   rw\\5\6\u\v\\\5\u4      4   rx\" S,\2\55      ry " S- S.5      rz " S/ S0\=5      r{S3S1 jr|S2 r}g)4zQuantum circuit object.    )annotationsN)OrderedDict)UnionOptionalTupleTypeTypeVarSequenceCallableMappingIterableAnyLiteraloverload)pi)CircuitData)StandardGate)BitLocations)compute_estimated_duration)QiskitError)Instruction)Gate)	Parameter)CircuitError)deprecate_funcdeprecate_arg   )BitQuantumRegisterQubitAncillaRegisterAncillaQubitClbitClassicalRegisterRegister)_classical_resource_map)ControlFlowOp_builder_utils)CircuitScopeInterfaceControlFlowBuilderBlock)BreakLoopOpBreakLoopPlaceholder)BoxOp
BoxContext)ContinueLoopOpContinueLoopPlaceholder)	ForLoopOpForLoopContext)IfElseOp	IfContext)SwitchCaseOpSwitchContext)WhileLoopOpWhileLoopContext)exprtypes)ParameterExpressionParameterValueType)ParameterView)ParameterVector)InstructionSet)	Operation)QuantumCircuitDataCircuitInstruction)Delay)Store)
AnnotationTranspileLayout)BaseOperator)StatevectorSTBitTypec                      \ rS rSrSrSrSrSSSSSSS.             SS jjr\\	" S	S
SS9S 5       5       r
\
R                  SS j5       r
\\	" S	S
SS9S 5       5       r\R                  S 5       r\ GS        GSS jj5       r\SSSSSS.             GSS jj5       r\GSS j5       r\GSS j5       r\R                  GSS j5       r\GSS j5       r\GSS j5       r\R                  GSS j5       rGS	S jrGS
S jrGSS jr\S 5       r\GSS j5       r\GS	S  j5       rGSS! jrGSS" jrGSSS#.GSS$ jjjrGSS% jrGSS& jrGSGSS' jjr SS(.GSS) jjr! GS       GSS* jjr"    GS         GSS+ jjr#     GSSSSS,.                   GSS- jjjr$GSGSS. jjr%\GSS/ j5       r&\GSS0 j5       r'\GSS1 j5       r(\GSS2 j5       r)\GSS3 j5       r*\*R                  GS S4 j5       r*\GS!S5 j5       r+\+R                  GS"S6 j5       r+\GS#S7 j5       r,\GSS8 j5       r-\GSS9 j5       r.\GSS: j5       r/\GSS; j5       r0\GSS< j5       r1\GSS= j5       r2\GSS> j5       r3\GSS? j5       r4GS$S@ jr5GS%SA jr6GS$SB jr7GS%SC jr8GS$SD jr9GS&SE jr:GS$SF jr;GS%SG jr<GS'SH jr=GS'SI jr>GS(SJ jr?GS(SK jr@GSSL jrA\BR                  GS)SM j5       rD\BR                  GS*SN j5       rDSO rD\GS+SP j5       rEGS,SQ jrFGS-SR jrG   GS.         GS/SS jjrH  GS0SST.         GS1SU jjjrI\BR                        GS2SV j5       rJ\BR                          GS3SW j5       rJGS4SSX.GS5SY jjjrJ\BR                  GS6SZ j5       rK\BR                  GS7GS8S\ jj5       rKGS7GS9S] jjrKGS:S^ jrL\BR                  GS;S_ j5       rM\BR                  GS7GS<S` jj5       rMGS7GS=Sa jjrMGS>Sb jrN\BR                  GS?Sc j5       rO\BR                  GS7GS@Sd jj5       rOGS7GS=Se jjrOGSASf jrP\BR                  GSBSg j5       rQ\BR                   GS7     GSCSh jj5       rQGS7GS=Si jjrQGSDSj jrR      GSESk jrSGSFSl jrTGSFSm jrUGSGSn jrVGSHSo jrW\BR                  GSHSp j5       rX\BR                  GSISq j5       rXSr rX\BR                  GSJSs j5       rY\BR                  GSGSKSt jj5       rY GS     GSESu jjrYGSLSv jrZGSMSw jr[GSNSx jr\GSOSy jr]  GS0     GSPSz jjr^  GS0     GSQS{ jjr_  GSR     GSSS| jjr`                  GST                                   GSUS} jjraS~ 4   GSVS jjrbS 4   GSWS jjrcGSS jrd\GSS j5       re\GSS j5       rf\GSS j5       rgGSXS jrhGSS jriGSYS jrjGSGSZS jjrkGSS jrlGSS jrmGSGS[S jjrn GSSS.     GS\S jjjroGSS jrpGS]S jrqGS^S jrrGS_S jrsGS`S jrtGSaS jruGSbGScS jjrv GSd     GSeS jjrwGSbGScS jjrx\GSfS j5       ry\GSgS j5       rz\GShS j5       r{\{R                  GSiS j5       r{\GSjS j5       r|\GSS j5       r}GSkS jr~\C GS7S[S[S.         GSlS jjj5       r\C GS7S[S[S.         GSmS jjj5       r GSSSS.         GSnS jjjrGS
S jr GSb     GSoS jjrSS.GSpS jjr  GS0       GSqS jjrGS_S jr  GS0         GSrS jjrGS_S jrGSsS jrGStS jr  GS0           GSuS jjr GS         GSvS jjr GS       GSwS jjr   GSx           GSyS jjr GS       GSzS jjr        GS{S jr          GS|S jr        GS}S jr          GS~S jr GS       GSS jjr  GS0           GSuS jjr        GSS jr GS       GSS jjr  GS0           GSuS jjr        GSS jrGSS jr  GS0           GSuS jjr        GSS jr        GSS jrGSS jrGS_S jrGS_S jr  GS0         GSrS jjr  GS0         GSrS jjrGSS jrGSS jr  GS0           GSS jjrGS_S jrGS_S jr  GS0         GSrS jjrGS_S jrGS_S jr          GSS jr  GS0                 GSS jjrGSGSS jjr  GS0         GSrS jjrGSS jr GS         GSS jjr\" SSSS9   GS           GSS jj5       rGS_S jr  GS0         GSrS jjrGS_S jr  GS0         GSrS jjr  GS0           GSS jjr      GSS jr   GSx         GSS jjr  GS     GSS jjr GS     GSS jjrGSS jrGSS jr     GS         GSS jjrGSS jrGSS jrGSS jr   GSSSSS[S.             GSS jjjr\BR                              GSS j5       r\BR                              GSS j5       rGSSS.S jjr\BR                                GSS j5       r\BR                                GSS j5       r GSSS.S jjr\BR                  GSS j5       r\BR                  SS.           GSS jj5       r   GSSS.S jjr GS             GSS jjr\BR                              GSS j5       r\BR                              GSS j5       rGSSS.S jjrGSS jrGSS jrGSS jrGSS jrGSS jrGSGSS jjrSrg(  QuantumCircuit   u  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`.

Example:

.. plot::
   :include-source:
   :nofigs:

   from qiskit import QuantumCircuit

   # Create a new circuit with two qubits
   qc = QuantumCircuit(2)

   # Add a Hadamard gate to qubit 0
   qc.h(0)

   # Perform a controlled-X gate on qubit 1, controlled by qubit 0
   qc.cx(0, 1)

   # Return a text drawing of the circuit.
   qc.draw()

.. code-block:: text

        ┌───┐
   q_0: ┤ H ├──■──
        └───┘┌─┴─┐
   q_1: ─────┤ X ├
             └───┘

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:`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.
                               This attribute is deprecated and :meth:`.estimate_duration`
                               should be used instead.

: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_captured_stretches` Number of captured stretches.
:attr:`num_declared_vars`      Number of locally declared real-time classical variables in the
                               outer circuit scope.
:attr:`num_declared_stretches` Number of locally declared stretches 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:`num_stretches`          Total number of stretches in the outer circuit scope.
:attr:`num_identifiers`        Total number of both variables and stretches in the outer
                               circuit.
: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

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_captured_stretches
.. autoattribute:: num_declared_vars
.. autoattribute:: num_declared_stretches
.. autoattribute:: num_input_vars
.. autoattribute:: num_identifiers
.. autoattribute:: num_parameters
.. autoattribute:: num_qubits
.. autoattribute:: num_stretches
.. 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_stretch`            :class:`~.expr.Stretch` nodes with local scope.
:meth:`add_input`              :class:`~.expr.Var` nodes that are treated as circuit inputs.
:meth:`add_capture`            :class:`~.expr.Var` or :class:`~.expr.Stretch` 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). Additionally, the method
:meth:`add_stretch` can be used to add stretches to the circuit.

.. automethod:: add_var
.. automethod:: add_input
.. automethod:: add_stretch

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` or :class:`~.expr.Stretch` identifiers
        to a circuit after initialization.

You can retrieve identifiers attached to a circuit (e.g. a :class:`~.expr.Var` or
:class:`~.expr.Stretch`) by name with methods :meth:`get_var`, :meth:`get_stretch`, or
:meth:`get_identifier`. You can also check if a circuit
contains a given identifier with :meth:`has_var`, :meth:`has_stretch`, or
:meth:`has_identifier`.

.. automethod:: get_var
.. automethod:: get_stretch
.. automethod:: get_identifier
.. automethod:: has_var
.. automethod:: has_stretch
.. automethod:: has_identifier


There are also several iterator methods that you can use to get the full set of identifiers
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_stretches`, :attr:`num_input_vars`, :attr:`num_captured_vars`,
:attr:`num_captured_stretches`, :attr:`num_declared_vars`, or :attr:`num_declared_stretches`.

.. automethod:: iter_vars
.. automethod:: iter_stretches
.. automethod:: iter_input_vars
.. automethod:: iter_captured_vars
.. automethod:: iter_captured_stretches
.. automethod:: iter_declared_vars
.. automethod:: iter_declared_stretches


.. _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
.. automethod:: tdg
.. automethod:: u
.. automethod:: unitary
.. automethod:: x
.. automethod:: y
.. automethod:: z


.. _circuit-control-flow-methods:

Adding control flow to circuits
-------------------------------

.. seealso::
    :ref:`circuit-control-flow-repr`

    Discussion of how control-flow operations are represented in the whole :mod:`qiskit.circuit`
    context.

==============================  ================================================================
:class:`QuantumCircuit` method  Control-flow instruction
==============================  ================================================================
:meth:`if_test`                 :class:`.IfElseOp` with only a ``True`` body
:meth:`if_else`                 :class:`.IfElseOp` with both ``True`` and ``False`` bodies
:meth:`while_loop`              :class:`.WhileLoopOp`
:meth:`switch`                  :class:`.SwitchCaseOp`
:meth:`for_loop`                :class:`.ForLoopOp`
:meth:`box`                     :class:`.BoxOp`
:meth:`break_loop`              :class:`.BreakLoopOp`
:meth:`continue_loop`           :class:`.ContinueLoopOp`
==============================  ================================================================

:class:`QuantumCircuit` has corresponding methods for all of the control-flow operations that
are supported by Qiskit.  These have two forms for calling them.  The first is a very
straightfowards convenience wrapper that takes in the block bodies of the instructions as
:class:`QuantumCircuit` arguments, and simply constructs and appends the corresponding
:class:`.ControlFlowOp`.

The second form, which we strongly recommend you use for constructing control flow, is called
*the builder interface*.  Here, the methods take only the real-time discriminant of the
operation, and return `context managers
<https://docs.python.org/3/library/stdtypes.html#typecontextmanager>`__ that you enter using
``with``.  You can then use regular :class:`QuantumCircuit` methods within those blocks to build
up the control-flow bodies, and Qiskit will automatically track which of the data resources are
needed for the inner blocks, building the complete :class:`.ControlFlowOp` as you leave the
``with`` statement.  It is far simpler and less error-prone to build control flow
programmatically this way.

When using the control-flow builder interface, you may sometimes want a qubit to be included in
a block, even though it has no operations defined.  In this case, you can use the :meth:`noop`
method.

To check whether a circuit contains a :class:`.ControlFlowOp` you can use the helper method
:meth:`.QuantumCircuit.has_control_flow_op`.

..
    TODO: expand the examples of the builder interface.

.. automethod:: box
.. automethod:: break_loop
.. automethod:: continue_loop
.. automethod:: for_loop
.. automethod:: if_else
.. automethod:: if_test
.. automethod:: switch
.. automethod:: while_loop
.. automethod:: noop
.. automethod:: has_control_flow_op


Converting circuits to single objects
-------------------------------------

As discussed in :ref:`circuit-append-compose`, you can convert a circuit to either an
:class:`~.circuit.Instruction` or a :class:`.Gate` using two helper methods.

.. automethod:: to_instruction
.. automethod:: to_gate


Helper mutation methods
-----------------------

There are two higher-level methods on :class:`QuantumCircuit` for appending measurements to the
end of a circuit.  Note that by default, these also add an extra register.

.. automethod:: measure_active
.. automethod:: measure_all

There are two "subtractive" methods on :class:`QuantumCircuit` as well.  This is not a use-case
that :class:`QuantumCircuit` is designed for; typically you should just look to use
:meth:`copy_empty_like` in place of :meth:`clear`, and run :meth:`remove_final_measurements` as
its transpiler-pass form :class:`.RemoveFinalMeasurements`.

.. automethod:: clear
.. automethod:: remove_final_measurements


Circuit properties
==================

Simple circuit metrics
----------------------

When constructing quantum circuits, there are several properties that help quantify
the "size" of the circuits, and their ability to be run on a noisy quantum device.
Some of these, like number of qubits, are straightforward to understand, while others
like depth and number of tensor components require a bit more explanation.  Here we will
explain all of these properties, and, in preparation for understanding how circuits change
when run on actual devices, highlight the conditions under which they change.

Consider the following circuit:

.. plot::
   :alt: Circuit diagram output by the previous code.
   :include-source:

   from qiskit import QuantumCircuit
   qc = QuantumCircuit(12)
   for idx in range(5):
      qc.h(idx)
      qc.cx(idx, idx+5)

   qc.cx(1, 7)
   qc.x(8)
   qc.cx(1, 9)
   qc.x(7)
   qc.cx(1, 11)
   qc.swap(6, 11)
   qc.swap(6, 9)
   qc.swap(6, 10)
   qc.x(6)
   qc.draw('mpl')

From the plot, it is easy to see that this circuit has 12 qubits, and a collection of
Hadamard, CNOT, X, and SWAP gates.  But how to quantify this programmatically? Because we
can do single-qubit gates on all the qubits simultaneously, the number of qubits in this
circuit is equal to the :meth:`width` of the circuit::

   assert qc.width() == 12

We can also just get the number of qubits directly using :attr:`num_qubits`::

   assert qc.num_qubits == 12

.. important::

   For a quantum circuit composed from just qubits, the circuit width is equal
   to the number of qubits. This is the definition used in quantum computing. However,
   for more complicated circuits with classical registers, and classically controlled gates,
   this equivalence breaks down. As such, from now on we will not refer to the number of
   qubits in a quantum circuit as the width.

It is also straightforward to get the number and type of the gates in a circuit using
:meth:`count_ops`::

   qc.count_ops()

.. code-block:: text

   OrderedDict([('cx', 8), ('h', 5), ('x', 3), ('swap', 3)])

We can also get just the raw count of operations by computing the circuits
:meth:`size`::

   assert qc.size() == 19

.. automethod:: count_ops
.. automethod:: depth
.. automethod:: get_instructions
.. automethod:: num_connected_components
.. automethod:: num_nonlocal_gates
.. automethod:: num_tensor_factors
.. automethod:: num_unitary_factors
.. automethod:: size
.. automethod:: width

Accessing scheduling information
--------------------------------

If a :class:`QuantumCircuit` has been scheduled as part of a transpilation pipeline, the timing
information for individual qubits can be accessed.  The whole-circuit timing information is
available through the :meth:`estimate_duration` method and :attr:`op_start_times` attribute.

.. automethod:: estimate_duration
.. automethod:: qubit_duration
.. automethod:: qubit_start_time
.. automethod:: qubit_stop_time


.. _circuit-abstract-physical:

Abstract and physical circuits
==============================

Circuits are a fairly low-level abstraction of quantum algorithms.  However, even within this,
there are distinctions. Quantum programmers often want to use a wide arrange of gates and
instructions, and work in a regime where all qubits and interact with all others.  Quantum
hardware, however, typically has a restrictive set of native gates, and only certain pairs of
hardware qubits can interact.  We term these two regimes "abstract circuits" and "physical
circuits", respectively.

Qiskit has two ways of distinguishing a circuit that is intended to be physical.  This is a
fuzzy check, for historical reasons; originally, Qiskit never made the distinction at all (which
is why :func:`.transpile` is called that, and not called ``compile``!).  The most explicit way
is through the :attr:`layout` attribute of circuits; if this is set, the circuit is certainly
intended to be physical.  The older, more implicit, way is the metadata of the :class:`.Qubit`
objects and :class:`.QuantumRegister` instances in the circuit.  A circuit can only be
considered (as judged by several transpiler passes) as physical if it contains exactly one
quantum register, which is called ``q`` and owns all the circuit qubits in index order.  Again
for historical reasons, this is the default for the ``QuantumCircuit(int [, int])`` form of the
default constructor.

Normally, you create a :class:`QuantumCircuit` and build it in the abstract sense (regardless of
the qubit metadata).  You then call :func:`.transpile` to compile the circuit into a
hardware-supported circuit.  However, in cases where you want to write a hardware efficient
circuit from the beginning, you can short-circuit the full compilation infrastructure using the
:meth:`ensure_physical` method.  This will ensure that, no matter how you defined the initial
qubit metadata, all requirements for the circuit to be considered physical will be satisfied,
with the qubit indices mapped to the hardware qubits.

For more complete control over choosing a virtual-to-physical mapping and routing, see :ref:`the
layout <transpiler-preset-stage-layout>` and `routing <transpiler-preset-stage-routing>` stages
of the preset compilation pipelines.

.. automethod:: ensure_physical


Instruction-like methods
========================

..
    These methods really shouldn't be on `QuantumCircuit` at all.  They're generally more
    appropriate as `Instruction` or `Gate` methods.  `reverse_ops` shouldn't be a method _full
    stop_---it was copying a `DAGCircuit` method from an implementation detail of the original
    `SabreLayout` pass in Qiskit.

:class:`QuantumCircuit` also contains a small number of methods that are very
:class:`~.circuit.Instruction`-like in detail.  You may well find better integration and more
API support if you first convert your circuit to an :class:`~.circuit.Instruction`
(:meth:`to_instruction`) or :class:`.Gate` (:meth:`to_gate`) as appropriate, then call the
corresponding method.

.. automethod:: control
.. automethod:: inverse
.. automethod:: power
.. automethod:: repeat
.. automethod:: reverse_ops

Visualization
=============

Qiskit includes some drawing tools to give you a quick feel for what your circuit looks like.
This tooling is primarily targeted at producing either a `Matplotlib
<https://matplotlib.org/>`__- or text-based drawing.  There is also a lesser-featured LaTeX
backend for drawing, but this is only for simple circuits, and is not as actively maintained.

.. seealso::
    :mod:`qiskit.visualization`
        The primary documentation for all of Qiskit's visualization tooling.

.. automethod:: draw

In addition to the core :meth:`draw` driver, there are two visualization-related helper methods,
which are mostly useful for quickly unwrapping some inner instructions or reversing the
:ref:`qubit-labelling conventions <circuit-conventions>` in the drawing.  For more general
mutation, including basis-gate rewriting, you should use the transpiler
(:mod:`qiskit.transpiler`).

.. automethod:: decompose
.. automethod:: reverse_bits
r   circuitN )nameglobal_phasemetadatainputscapturesdeclarationsc          	        [        S U 5       5      (       ab   [        S U 5       5      nU(       d6  [	        SU V	s/ s H  n	[        U	5      R                  PM     sn	 SU S35      e[        S U 5       5      nSU l        U    Uc&  U R                  5       U l        U R                  5         O,[        U[        5      (       d  [	        S	5      eXl        Xl        U R                  5         [        U 5      U l        SU l        / U l        ['        5       U l        / U l        U R,                  " U6   SU l        X l        U H  n
U R3                  U
5        M     U H  nU R5                  U5        M     [        U[6        5      (       a  UR9                  5       nU H  u  pU R;                  X5        M     SU l        S
U l        Uc  0 OUU l         g! [        [        4 a    Sn GNf = fs  sn	f )a  
Default constructor of :class:`QuantumCircuit`.

..
    `QuantumCirucit` documents its `__init__` method explicitly, unlike most classes where
    it's implicitly appended to the class-level documentation, just because the class is so
    huge and has a lot of introductory material to its class docstring.

Args:
    regs: The registers to be included in the circuit.

        * If a list of :class:`~.Register` objects, represents the :class:`.QuantumRegister`
          and/or :class:`.ClassicalRegister` objects to include in the circuit.

          For example:

            * ``QuantumCircuit(QuantumRegister(4))``
            * ``QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))``
            * ``QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))``

        * If a list of ``int``, the amount of qubits and/or classical bits to include in
          the circuit. It can either be a single int for just the number of quantum bits,
          or 2 ints for the number of quantum bits and classical bits, respectively.

          For example:

            * ``QuantumCircuit(4) # A QuantumCircuit with 4 qubits``
            * ``QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits``

        * If a list of python lists containing :class:`.Bit` objects, a collection of
          :class:`.Bit` s to be added to the circuit.

    name: the name of the quantum circuit. If not set, an automatically generated string
        will be assigned.
    global_phase: The global phase of the circuit in radians.
    metadata: Arbitrary key value metadata to associate with the circuit. This gets
        stored as free-form data in a dict in the
        :attr:`~qiskit.circuit.QuantumCircuit.metadata` attribute. It will not be directly
        used in the circuit.
    inputs: any variables to declare as ``input`` runtime variables for this circuit.  These
        should already be existing :class:`.expr.Var` nodes that you build from somewhere
        else; if you need to create the inputs as well, use
        :meth:`QuantumCircuit.add_input`.  The variables given in this argument will be
        passed directly to :meth:`add_input`.  A circuit cannot have both ``inputs`` and
        ``captures``.
    captures: any variables that this circuit scope should capture from a containing
        scope.  The variables given here will be passed directly to :meth:`add_capture`.  A
        circuit cannot have both ``inputs`` and ``captures``.
    declarations: any variables that this circuit should declare and initialize immediately.
        You can order this input so that later declarations depend on earlier ones
        (including inputs or captures). If you need to depend on values that will be
        computed later at runtime, use :meth:`add_var` at an appropriate point in the
        circuit execution.

        This argument is intended for convenient circuit initialization when you already
        have a set of created variables.  The variables used here will be directly passed to
        :meth:`add_var`, which you can use directly if this is the first time you are
        creating the variable.

Raises:
    CircuitError: if the circuit name, if given, is not valid.
    CircuitError: if both ``inputs`` and ``captures`` are given.
c              3  b   #    U  H%  n[        U[        [        [        45      (       + v   M'     g 7fN)
isinstancelistr   r$   .0regs     W/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/circuit/quantumcircuit.py	<genexpr>*QuantumCircuit.__init__.<locals>.<genexpr>h  s(     _Z^SV:cD/;L#MNNNZ^s   -/c              3  <   #    U  H  o[        U5      :H  v   M     g 7frZ   intr]   s     r`   ra   rb   l  s     $ECH_s   Fz-Circuit args must be Registers or integers. (z 'z' was provided)c              3  8   #    U  H  n[        U5      v   M     g 7frZ   rd   r]   s     r`   ra   rb   w  s     2TcST   NzFThe circuit name should be a string (or None to auto-generate a name).dt)!anyall
ValueError	TypeErrorr   type__name__tuple
_base_name_cls_prefix_name_updater[   strrR   _increment_instances_OuterCircuitScopeInterface_builder_api_op_start_times_control_flow_scopesr   _data	_ancillasadd_register_layoutrS   	add_inputadd_capturer   itemsadd_var	_duration_unitrT   )selfrR   rS   rT   rU   rV   rW   regsvalid_reg_sizer_   input_capturevarinitials                 r`   __init__QuantumCircuit.__init__  s   R _Z^___'!$$E$E!E ""C6:;dsS	**d;<Btf E    2T22D	$ <"..0DOD#&&X  #OI!!# 8=#  	! #.-
-/4 ( FNN6" GW%  lG,,'--/L(LCLL& ) 
&.H	g 	* '!&' <s   G	 G"
	GGz1.3.0zin Qiskit 3.0.0T)sinceremoval_timelineis_propertyc                    U R                   $ )zoThe total duration of the circuit, set by a scheduling transpiler pass.  Its unit is
specified by :attr:`unit`.r   r   s    r`   durationQuantumCircuit.duration  s    
 ~~    c                    Xl         g rZ   r   r   values     r`   r   r     s    r   c                    U R                   $ )z/The unit that :attr:`duration` is specified in.r   r   s    r`   unitQuantumCircuit.unit  s     zzr   c                    Xl         g rZ   r   r   s     r`   r   r     s    
r   Fc                P    [        US9nXl        U(       a  UR                  SS9  U$ )z3A private constructor from rust space circuit data.rR   Fapply_layout)rN   ry   ensure_physical)clsdatalegacy_qubitsrR   outs        r`   _from_circuit_data!QuantumCircuit._from_circuit_data  s,    
 $'	U3
r   )qubitsclbitsrR   rS   rT   c                  [        X4US9n[        5       n[        5       nU(       a-  [        U5      nUR                  U5        UR	                  U5        U(       a-  [        U5      nUR                  U5        UR	                  U5        U  H  n	[        U	[        5      (       d  [        U	6 n	U	R                   V
s/ s H  oU;  d  M
  U
PM     nn
U	R                   Vs/ s H  oU;  d  M
  UPM     nnUR                  U5        UR                  U5        UR	                  U5        UR	                  U5        UR                  U	5        M     U$ s  sn
f s  snf )a|  Construct a circuit from an iterable of :class:`.CircuitInstruction`\ s.

Args:
    instructions: The instructions to add to the circuit.
    qubits: Any qubits to add to the circuit. This argument can be used,
        for example, to enforce a particular ordering of qubits.
    clbits: Any classical bits to add to the circuit. This argument can be used,
        for example, to enforce a particular ordering of classical bits.
    name: The name of the circuit.
    global_phase: The global phase of the circuit in radians.
    metadata: Arbitrary key value metadata to associate with the circuit.

Returns:
    The quantum circuit.
)rR   rS   rT   )
rN   setr\   add_bitsupdater[   rB   r   r   _append)instructionsr   r   rR   rS   rT   rP   added_qubitsadded_clbitsinstructionqubitclbits               r`   from_instructions QuantumCircuit.from_instructions  s'   < !dPXYuu&\FV$'&\FV$''Kk+=>>0+>)4););Y);L?Xe);FY)4););Y);L?Xe);FYV$V$''OOK( (  ZYs   7	E
E
	E'Ec                    U R                   $ )a  Return any associated layout information about the circuit.

This attribute contains an optional :class:`~.TranspileLayout`
object. This is typically set on the output from :func:`~.transpile`
or :meth:`.PassManager.run` to retain information about the
permutations caused on the input circuit by transpilation.

There are two types of permutations caused by the :func:`~.transpile`
function: an initial layout that permutes the qubits based on the
selected physical qubits on the :class:`~.Target`, and a final layout,
which is an output permutation caused by :class:`~.SwapGate`\ s
inserted during routing.

Example:

    .. plot::
        :include-source:
        :nofigs:

        from qiskit import QuantumCircuit
        from qiskit.providers.fake_provider import GenericBackendV2
        from qiskit.transpiler import generate_preset_pass_manager

        # Create circuit to test transpiler on
        qc = QuantumCircuit(3, 3)
        qc.h(0)
        qc.cx(0, 1)
        qc.swap(1, 2)
        qc.cx(0, 1)

        # Add measurements to the circuit
        qc.measure([0, 1, 2], [0, 1, 2])

        # Specify the QPU to target
        backend = GenericBackendV2(3)

        # Transpile the circuit
        pass_manager = generate_preset_pass_manager(
        optimization_level=1, backend=backend
        )
        transpiled = pass_manager.run(qc)

        # Print the layout after transpilation
        print(transpiled.layout.routing_permutation())

    .. code-block:: text

        [0, 1, 2]

)r|   r   s    r`   layoutQuantumCircuit.layout+  s    h ||r   c                    [        U 5      $ )aK  The circuit data (instructions and context).

Example:

    .. plot::
        :include-source:
        :nofigs:

        from qiskit import QuantumCircuit

        qc = QuantumCircuit(2, 2)
        qc.measure([0], [1])
        print(qc.data)

    .. code-block:: text

        [CircuitInstruction(operation=Instruction(name='measure', num_qubits=1,
        num_clbits=1, params=[]), qubits=(Qubit(QuantumRegister(2, 'q'), 0),),
        clbits=(Clbit(ClassicalRegister(2, 'c'), 1),))]

Returns:
    A list-like object containing the :class:`.CircuitInstruction` instances in the circuit.
)rA   r   s    r`   r   QuantumCircuit.dataa  s    2 "$''r   c                j   [        U[        5      (       a  UR                  5       nO[        U5      nU R                  R                  5         U R                  U l        U(       d  g[        US   [        5      (       a  U H  nU R                  USS9  M     gU H  u  p#nU R                  X#USS9  M     g)aH  Sets the circuit data from a list of instructions and context.

Args:
    data_input (Iterable): A sequence of instructions with their execution contexts.  The
        elements must either be instances of :class:`.CircuitInstruction` (preferred), or a
        3-tuple of ``(instruction, qargs, cargs)`` (legacy).  In the legacy format,
        ``instruction`` must be an :class:`~.circuit.Instruction`, while ``qargs`` and
        ``cargs`` must be iterables of :class:`~.circuit.Qubit` or :class:`.Clbit`
        specifiers (similar to the allowed forms in calls to :meth:`append`).
Nr   Fcopy)	r[   r   r   r\   ry   clearrS   rB   append)r   
data_inputr   qargscargss        r`   r   r   |  s     j+..#*Jj)J

 --jm%788)Ke4  * .8)EKEB .8r   c                J    U R                   c  [        S5      eU R                   $ )u#  Return a list of operation start times.

.. note::
   This attribute computes the estimate starting time of the operations in the scheduled circuit
   and only works for simple circuits that have no control flow or other classical feed-forward
   operations.

This attribute is enabled once one of scheduling analysis passes
runs on the quantum circuit.

Example:

    .. plot::
        :include-source:
        :nofigs:

        from qiskit import QuantumCircuit
        from qiskit.providers.fake_provider import GenericBackendV2
        from qiskit.transpiler import generate_preset_pass_manager

        qc = QuantumCircuit(2)
        qc.h(0)
        qc.cx(0, 1)
        qc.measure_all()

        # Print the original circuit
        print("Original circuit:")
        print(qc)

        # Transpile the circuit with a specific basis gates list and print the resulting circuit
        backend = GenericBackendV2(2, basis_gates=['u1', 'u2', 'u3', 'cx'])
        pm = generate_preset_pass_manager(
            optimization_level=1, backend=backend, scheduling_method="alap"
        )
        transpiled_qc = pm.run(qc)
        print("Transpiled circuit with basis gates ['u1', 'u2', 'u3', 'cx']:")
        print(transpiled_qc)

        # Print the start times of each instruction in the transpiled circuit
        print("Start times of instructions in the transpiled circuit:")
        for instruction, start_time in zip(transpiled_qc.data, transpiled_qc.op_start_times):
            print(f"{instruction.operation.name}: {start_time}")

    .. code-block:: text


        Original circuit:
                ┌───┐      ░ ┌─┐
        q_0: ┤ H ├──■───░─┤M├───
                └───┘┌─┴─┐ ░ └╥┘┌─┐
        q_1: ─────┤ X ├─░──╫─┤M├
                    └───┘ ░  ║ └╥┘
        meas: 2/══════════════╩══╩═
                            0  1

        Transpiled circuit with basis gates ['u1', 'u2', 'u3', 'cx']:
                    ┌─────────┐          ░ ┌─────────────────┐┌─┐
        q_0 -> 0 ───┤ U2(0,π) ├──────■───░─┤ Delay(1255[dt]) ├┤M├
                ┌──┴─────────┴───┐┌─┴─┐ ░ └───────┬─┬───────┘└╥┘
        q_1 -> 1 ┤ Delay(196[dt]) ├┤ X ├─░─────────┤M├─────────╫─
                └────────────────┘└───┘ ░         └╥┘         ║
        meas: 2/═══════════════════════════════════╩══════════╩═
                                                    1          0

        Start times of instructions in the transpiled circuit:
        u2: 0
        delay: 0
        cx: 196
        barrier: 2098
        delay: 2098
        measure: 3353
        measure: 2098

Returns:
    List of integers representing instruction estimated start times.
    The index corresponds to the index of instruction in :attr:`QuantumCircuit.data`.

Raises:
    AttributeError: When circuit is not scheduled.
znThis circuit is not scheduled. To schedule it run the circuit through one of the transpiler scheduling passes.)rw   AttributeErrorr   s    r`   op_start_timesQuantumCircuit.op_start_times  s2    d ' b  ###r   c                    U R                   $ )aN  The user-provided metadata associated with the circuit.

The metadata for the circuit is a user-provided ``dict`` of metadata
for the circuit. It will not be used to influence the execution or
operation of the circuit, but it is expected to be passed between
all transforms of the circuit (i.e., transpilation) and that providers will
associate any circuit metadata with the results it returns from
execution of that circuit.

Example:

    .. plot::
        :include-source:
        :nofigs:

        from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit

        q = QuantumRegister(2)
        c = ClassicalRegister(2)
        qc = QuantumCircuit(q, c)

        qc.metadata = {'experiment_type': 'Bell state experiment'}

        print(qc.metadata)

    .. code-block:: text

       {'experiment_type': 'Bell state experiment'}
)	_metadatar   s    r`   rT   QuantumCircuit.metadata  s    > ~~r   c                P    [        U[        5      (       d  [        S5      eXl        g)zUpdate the circuit metadataz2Only a dictionary is accepted for circuit metadataN)r[   dictrl   r   )r   rT   s     r`   rT   r     s"     (D))PQQ!r   c                2    [        U R                  SS95      $ )Ntext)output)rs   drawr   s    r`   __str__QuantumCircuit.__str__  s    499F9+,,r   c                X    [        U[        5      (       d  gSSKJn  U" U SS9U" USS9:H  $ )NFr   circuit_to_dagcopy_operations)r[   rN   qiskit.convertersr   )r   otherr   s      r`   __eq__QuantumCircuit.__eq__  s7    %00 	5dE:n5?
 
 	
r   c           	        U R                   nUR                  U5      nU R                  R                  5       SS1-
   H1  n[	        X4[
        R                  " U R                  U   U5      5        M3     [        U5      Ul        U R                  R                  SS9Ul	        UR                  R                  [
        R                  " U R                  R                  U5      [
        R                  " U R                  R                  U5      [
        R                  " U R                  R                  U5      [
        R                  " U R                  R                  U5      S9  U$ )Nry   rv   T)deepcopy)r   r   qregscregs)	__class____new____dict__keyssetattr_copyr   ru   rv   ry   r   replace_bitsr   r   r   r   )r   memor   resultks        r`   __deepcopy__QuantumCircuit.__deepcopy__)  s     nnS!##%.(AAAFu~~dmmA.>EF B :&A zz5!!>>$**"3"3T:>>$**"3"3T:..!1!148..!1!148	 	" 	
 r   c                .    U =R                   S-  sl         g Nr   	instancesr   s    r`   rt   #QuantumCircuit._increment_instancesB  s    r   c                    U R                   $ )zMReturn the current number of instances of this class,
useful for auto naming.r   r   s    r`   _cls_instancesQuantumCircuit._cls_instancesF  s     }}r   c                    U R                   $ )z)Return the prefix to use for auto naming.)prefixr   s    r`   rq   QuantumCircuit._cls_prefixL  s     zzr   c                    [         R                  " 5       c  SnO"S[         R                  " 5       R                   3nU R                   SU R                  5        U 3U l        g)z-update name of instance using instance numberN -)multiprocessingparent_processcurrent_processpidrp   r   rR   )r   pid_names     r`   rr   QuantumCircuit._name_updateQ  sW    ))+3H?::<@@ABH'q)<)<)>(?zJ	r   c                    Sn[        U[        5      (       a  XR                  ;   a  SnU$ [        U[        5      (       a  XR                  ;   a  SnU$ )z
Test if this circuit has the register r.

Args:
    register (Register): a quantum or classical register.

Returns:
    bool: True if the register is contained in this circuit.
FT)r[   r   r   r$   r   )r   registerhas_regs      r`   has_registerQuantumCircuit.has_registerY  sN     h00X5KG  "344ZZ9OGr   r   c                  U R                   nUb  X:  a  [        SU SU S35      eU R                  bU  Ub  X:w  a  [        S5      e[	        US5      nU R
                  [        U5      :w  d  U R                  U/:w  a  [        S5      egU(       a`  S	S
KJ	n  U R
                  R                  5       nUb"  X:  a  UR                  [	        X-
  S5      5        U" [        [        U5      5      5      nOSnU R                  R                  U5        UbI  S	SKJn  U" UUR#                  5       R                  5       SUU R
                  R                  5       S9U l        g)a  Put this circuit into canonical physical form, with the given number of qubits, if it is
not already.

Several Qiskit transpiler passes only make sense when applied to circuits defined in terms
of physical qubits.  If you have manually constructed a circuit where the qubit indices
correspond to physical qubits, use this function to ensure that the metadata of the circuit
matches the canonical physical form.  This means replacing the qubit data with a single
owning register called ``"q"``, and (optionally) setting the :attr:`layout` field of the
circuit to link these physical qubits with the original virtual ones.

If the circuit does not already have a layout, this method (with ``apply_layout=True``) is
equivalent to applying the full :ref:`trivial layout method
<transpiler-preset-stage-layout-trivial>` of the preset compilation pipeline.

If the circuit is already canonically physical, nothing happens to it.  This method cannot
change the number of qubits in the circuit if it already has a :attr:`layout` set.

Args:
    num_qubits: if given, expand the circuit with ancillas up to this size.  The ancillas
        will always be the highest qubit indices of the circuit.  If not given (the
        default), the circuit stays the same width.  This option cannot be set if the
        circuit already as a :attr:`layout`.
    apply_layout: if true (the default), set the :attr:`layout` attribute of the circuit
        appropriately so that the circuit appears to have been laid out with the "trivial"
        layout, including ancilla expansion, for a backend of width ``num_qubits``.  This
        has no effect if the circuit already had a :attr:`layout`.

Returns:
    whether the circuit was modified in order to make it physical.

Raises:
    ValueError: if ``num_qubits`` is too small for the circuit.
    CircuitError: if ``num_qubits`` is set to attempt to expand the circuit, but the circuit
        already has a layout set.
Nz#cannot have fewer physical qubits (z) than virtual ()z5cannot expand a circuit that already has a set layoutqzThis circuit has a set layout, but its qubits are not in the canonical physical form.  This might indicate a faulty layout transpilation stage has been used.Fr   )LayoutancillarF   )initial_layoutinput_qubit_mappingfinal_layout_input_qubit_count_output_qubit_listT)
num_qubitsrk   r|   r   r   r   r\   r   qiskit.transpilerr	  r   extendr   	enumeratery   make_physicalrG   get_virtual_bits)	r   r  r   original_num_qubitsexpectedr	  virtualsr  rG   s	            r`   r   QuantumCircuit.ensure_physicalj  sT   H #oo!j&F5j\ B""5!6a9  <<#%**K"#Z[[&':C@H{{d8n,

xj0H #" 
 0{{'')H%**J
0PR[ \]#D8)<$=>N!N

  ,%9*-$2$C$C$E$J$J$L!#6#';;#3#3#5DL r   c                *   U R                  U R                  S-   5      n[        U R                  5       H9  nUR	                  UR                  UR                  R                  5       S95        M;     U R                  Ul        U R                  Ul	        U$ )u+  Reverse the circuit by reversing the order of instructions.

This is done by recursively reversing all instructions.
It does not invert (adjoint) any gate.

Returns:
    QuantumCircuit: the reversed circuit.

Examples:

    input:

    .. code-block:: text

             ┌───┐
        q_0: ┤ H ├─────■──────
             └───┘┌────┴─────┐
        q_1: ─────┤ RX(1.57) ├
                  └──────────┘

    output:

    .. code-block:: text

                         ┌───┐
        q_0: ─────■──────┤ H ├
             ┌────┴─────┐└───┘
        q_1: ┤ RX(1.57) ├─────
             └──────────┘
_reverse	operation)
copy_empty_likerR   reversedr   r   replacer  reverse_opsr   r   )r   reverse_circr   s      r`   r!  QuantumCircuit.reverse_ops  s{    > ++DII
,BC#DII.K  !4!4{?T?T?`?`?b!4!cd / "&!ZZr   c                4   [        [        [        U R                  5      5      [        [        U R                  5      5      U R
                  U R                  S9nUR                  SSS2   nUR                  SSS2   n[        U R                  5       H[  n[        U5       Vs/ s H   oRU R                  U5      R                     PM"     nnUR                  [        XdR
                  S95        M]     [        U R                  5       H[  n[        U5       Vs/ s H   osU R                  U5      R                     PM"     nnUR                  [        XdR
                  S95        M]     U R                   H  nUR                   Vs/ s H   oRU R                  U5      R                     PM"     n	nUR                   Vs/ s H   osU R                  U5      R                     PM"     n
nUR                  UR!                  XS95        M     U$ s  snf s  snf s  snf s  snf )up  Return a circuit with the opposite order of wires.

The circuit is "vertically" flipped. If a circuit is
defined over multiple registers, the resulting circuit will have
the same registers but with their order flipped.

This method is useful for converting a circuit written in little-endian
convention to the big-endian equivalent, and vice versa.

Returns:
    QuantumCircuit: the circuit with reversed bit order.

Examples:

    input:

    .. code-block:: text

             ┌───┐
        a_0: ┤ H ├──■─────────────────
             └───┘┌─┴─┐
        a_1: ─────┤ X ├──■────────────
                  └───┘┌─┴─┐
        a_2: ──────────┤ X ├──■───────
                       └───┘┌─┴─┐
        b_0: ───────────────┤ X ├──■──
                            └───┘┌─┴─┐
        b_1: ────────────────────┤ X ├
                                 └───┘

    output:

    .. code-block:: text

                                 ┌───┐
        b_0: ────────────────────┤ X ├
                            ┌───┐└─┬─┘
        b_1: ───────────────┤ X ├──■──
                       ┌───┐└─┬─┘
        a_0: ──────────┤ X ├──■───────
                  ┌───┐└─┬─┘
        a_1: ─────┤ X ├──■────────────
             ┌───┐└─┬─┘
        a_2: ┤ H ├──■─────────────────
             └───┘
rR   rS   N)bitsrR   r   r   )rN   r\   r  r   r   rR   rS   r   find_bitindexr{   r   r   r$   r   r   r   )r   circnew_qubit_mapnew_clbit_mapr_   r   r'  r   r   r   r   s              r`   reverse_bitsQuantumCircuit.reverse_bits  s   ^ $++&'$++&'**	
 DbD)DbD)DJJ'CKSTW=Y=%$--"6"<"<==DYo4hhGH ( DJJ'CKSTW=Y=%$--"6"<"<==DY/TIJ (  99KMXM_M_`M_EDMM%$8$>$>?M_F`MXM_M_`M_EDMM%$8$>$>?M_F`LL,,F,JK %  Z Z a`s   "'H'H'H9'Hc           	     N   [        U R                  U R                  /U R                  QU R                  Q7U R
                  S-   U R                  * S.6n[        U R                  5       H8  nUR                  UR                  UR                  R                  US9S95        M:     U$ )u  Invert (take adjoint of) this circuit.

This is done by recursively inverting all gates.

Args:
    annotated: indicates whether the inverse gate can be implemented
        as an annotated gate.

Returns:
    QuantumCircuit: the inverted circuit

Raises:
    CircuitError: if the circuit cannot be inverted.

Examples:

    input:

    .. code-block:: text

             ┌───┐
        q_0: ┤ H ├─────■──────
             └───┘┌────┴─────┐
        q_1: ─────┤ RX(1.57) ├
                  └──────────┘

    output:

    .. code-block:: text

                          ┌───┐
        q_0: ──────■──────┤ H ├
             ┌─────┴─────┐└───┘
        q_1: ┤ RX(-1.57) ├─────
             └───────────┘
_dgr%  	annotatedr  )rN   r   r   r   r   rR   rS   r  ry   r   r   r  inverse)r   r3  inverse_circr   s       r`   r4  QuantumCircuit.inverse$  s    J &KKKK
 ZZ
 ZZ	

 U"+++
 $DJJ/K  ##k.C.C.K.KV_.K.`#a 0 r   )insert_barriersc                  [        U R                  U R                  /U R                  QU R                  Q7SU R
                  SU 3-   06nUS:  al   U R                  5       n[        U5       HL  nUR                  X@R                  U R                  5        U(       d  M2  XQS-
  :w  d  M<  UR                  5         MN     U$ ! [         a    U R                  5       n Nyf = f)a  Repeat this circuit ``reps`` times.

Args:
    reps (int): How often this circuit should be repeated.
    insert_barriers (bool): Whether to include barriers between circuit repetitions.

Returns:
    QuantumCircuit: A circuit containing ``reps`` repetitions of this circuit.
rR   z**r   r   )rN   r   r   r   r   rR   to_gater   to_instructionranger   barrier)r   repsr7  repeated_circinstis         r`   repeatQuantumCircuit.repeatX  s     'KK
'+zz
48JJ
EIYYSUVZU[Q\E\
 !8-$(LLN 4[%%dKKE"?q1H}!))+ !
   -**,-s   B? ?CCc                ,   US:  aD  [        U[        [        R                  45      (       a  U(       d  U(       d  U R	                  U5      $ U R
                  S:  a  [        SU R                   35      e U R                  5       n[        U R                  U R                  /U R                  QU R                  Q76 nUR                  UR!                  XS9[#        [%        UR&                  5      5      5        U$ ! [         a  n[        S5      UeSnAff = f)a  Raise this circuit to the power of ``power``.

If ``power`` is a positive integer and both ``matrix_power`` and ``annotated``
are ``False``, this implementation defaults to calling ``repeat``. Otherwise,
the circuit is converted into a gate, and a new circuit, containing this gate
raised to the given power, is returned. The gate raised to the given power is
implemented either as a unitary gate if ``annotated`` is ``False`` or as an
annotated operation if ``annotated`` is ``True``.

Args:
    power (float): The power to raise this circuit to.
    matrix_power (bool): indicates whether the inner power gate can be implemented
        as a unitary gate.
    annotated (bool): indicates whether the inner power gate can be implemented
        as an annotated operation.

Raises:
    CircuitError: If the circuit needs to be converted to a unitary gate, but is
        not unitary.

Returns:
    QuantumCircuit: A circuit implementing this circuit raised to the power of ``power``.
r   zoCannot raise a parameterized circuit to a non-positive power or matrix-power, please bind the free parameters: zThe circuit contains non-unitary operations and cannot be raised to a power. Note that no qiskit.circuit.Instruction objects may be in the circuit for this operation.Nr2  )r[   re   npintegerrA  num_parametersr   
parametersr9  r   rN   r   r   r   r   r   powerr\   r;  r  )r   rH  matrix_powerr3  gateexpower_circuits          r`   rH  QuantumCircuit.powert  s    6 QJ53

"344 ;;u%% "E??#% 	<<>D 't{{DKKZ$**ZtzzZTZZZCT%PTP_P_J`Eab  	D 		s   4C8 8
DDDc                4    U R                  5       nUR                  XX45      n[	        U5      n[        XR                  /U R                  Q7SSU R                   306n	U	R                  XyR                  5        U	$ ! [         a  n[        S5      UeSnAff = f)aj  Control this circuit on ``num_ctrl_qubits`` qubits.

Args:
    num_ctrl_qubits (int): The number of control qubits.
    label (str): An optional label to give the controlled operation for visualization.
    ctrl_state (str or int): The control state in decimal or as a bitstring
        (e.g. '111'). If None, use ``2**num_ctrl_qubits - 1``.
    annotated: indicates whether the controlled gate should be implemented
        as an annotated gate.

Returns:
    QuantumCircuit: The controlled version of this circuit.

Raises:
    CircuitError: If the circuit contains a non-unitary operation and cannot be controlled.
zThe circuit contains non-unitary operations and cannot be controlled. Note that no qiskit.circuit.Instruction objects may be in the circuit for this operation.NrR   c_)
r9  r   r   controlr   rN   r   r   rR   r   )
r   num_ctrl_qubitslabel
ctrl_stater3  rJ  rK  controlled_gatecontrol_qregcontrolled_circs
             r`   rP  QuantumCircuit.control  s    .	<<>D ,,zU&7(++
(,


;=dii[9I
 	0F0FG  	8 		s   A< <
BBB)r   	var_remapinline_capturesc          
     	  ^^^^ U(       a#  U(       a  U R                   (       a  [        S5      eU(       d  U R                   (       a  [        S5      eU(       a  U OU R                  5       n
Tc  0 OTm      SU4S jjm[        U[        5      (       a}  U R
                  (       dl  UR
                  (       a[  U
R                   (       a  [        S5      eU
R                  UR
                  5        UR                   H  nU
R                  U5        M     U(       aV  [        U[        5      (       aA  [        S UR                   5       5      (       a  UR                  5       OUR                  5       n[        U[        5      (       d  Uc  U R                  SUR                   nUc  U R
                  SUR                   nU(       aU  U
R                   R                  TS9nU
R#                  5         U
R%                  XUTS9  U H  nU
R'                  U5        M     OU
R%                  XUTS	9  U(       a  S$ U
$ UR                  U
R                  :  d  UR                  U
R                  :  a  [        S
5      e0 nUc<  U
R                  nUR)                  [+        UR                  U
R                  5      5        OU
R-                  U5      n[/        U5      UR                  :w  a%  [        S[/        U5       SUR                   S35      e[/        [1        U5      5      [/        U5      :w  a  [        SU S35      eUR)                  [+        UR                  U5      5        Uc<  U
R
                  nUR)                  [+        UR
                  U
R
                  5      5        OU
R3                  U5      n[/        U5      UR                  :w  a%  [        S[/        U5       SUR                   S35      e[/        [1        U5      5      [/        U5      :w  a  [        SU S35      eUR)                  [+        UR
                  U
R3                  U5      5      5        SU
l        SU
l        U
=R8                  UR8                  -  sl        UR                  n SUUU4S jjmSnU(       a)  U
R                   R                  TS9nU
R#                  5         T" UU
U0 U	UUS9  U(       a  U
R;                  5       R=                  U5        U(       a  S$ U
$ )u5  Apply the instructions from one circuit onto specified qubits and/or clbits on another.

.. note::

    By default, this creates a new circuit object, leaving ``self`` untouched.  For most
    uses of this function, it is far more efficient to set ``inplace=True`` and modify the
    base circuit in-place.

When dealing with realtime variables (:class:`.expr.Var` and :class:`.expr.Stretch` instances),
there are two principal strategies for using :meth:`compose`:

1. The ``other`` circuit is treated as entirely additive, including its variables.  The
   variables in ``other`` must be entirely distinct from those in ``self`` (use
   ``var_remap`` to help with this), and all variables in ``other`` will be declared anew in
   the output with matching input/capture/local scoping to how they are in ``other``.  This
   is generally what you want if you're joining two unrelated circuits.

2. The ``other`` circuit was created as an exact extension to ``self`` to be inlined onto
   it, including acting on the existing variables in their states at the end of ``self``.
   In this case, ``other`` should be created with all these variables to be inlined declared
   as "captures", and then you can use ``inline_captures=True`` in this method to link them.
   This is generally what you want if you're building up a circuit by defining layers
   on-the-fly, or rebuilding a circuit using layers taken from itself.  You might find the
   ``vars_mode="captures"`` argument to :meth:`copy_empty_like` useful to create each
   layer's base, in this case.

Args:
    other (qiskit.circuit.Instruction or QuantumCircuit):
        (sub)circuit or instruction to compose onto self.  If not a :obj:`.QuantumCircuit`,
        this can be anything that :obj:`.append` will accept.
    qubits (list[Qubit|int]): qubits of self to compose onto.
    clbits (list[Clbit|int]): clbits of self to compose onto.
    front (bool): If ``True``, front composition will be performed.  This is not possible within
        control-flow builder context managers.
    inplace (bool): If ``True``, modify the object. Otherwise, return composed circuit.
    copy (bool): If ``True`` (the default), then the input is treated as shared, and any
        contained instructions will be copied, if they might need to be mutated in the
        future.  You can set this to ``False`` if the input should be considered owned by
        the base circuit, in order to avoid unnecessary copies; in this case, it is not
        valid to use ``other`` afterward, and some instructions may have been mutated in
        place.
    var_remap (Mapping): mapping to use to rewrite :class:`.expr.Var` and
        :class:`.expr.Stretch` nodes in ``other`` as they are inlined into ``self``.
        This can be used to avoid naming conflicts.

        Both keys and values can be given as strings or direct identifier instances.
        If a key is a string, it matches any :class:`~.expr.Var` or :class:`~.expr.Stretch`
        with the same name.  If a value is a string, whenever a new key matches it, a new
        :class:`~.expr.Var` or :class:`~.expr.Stretch` is created with the correct type.
        If a value is a :class:`~.expr.Var`, its :class:`~.expr.Expr.type` must exactly
        match that of the variable it is replacing.
    inline_captures (bool): if ``True``, then all "captured" identifier nodes in
        the ``other`` :class:`.QuantumCircuit` are assumed to refer to identifiers already
        declared in ``self`` (as any input/capture/local type), and the uses in ``other``
        will apply to the existing identifiers.  If you want to build up a layer for an
        existing circuit to use with :meth:`compose`, you might find the
        ``vars_mode="captures"`` argument to :meth:`copy_empty_like` useful.  Any remapping
        in ``vars_remap`` occurs before evaluating this variable inlining.

        If this is ``False`` (the default), then all identifiers in ``other`` will be required
        to be distinct from those in ``self``, and new declarations will be made for them.
    wrap (bool): If True, wraps the other circuit into a gate (or instruction, depending on
        whether it contains only unitary instructions) before composing it onto self.
        Rather than using this option, it is almost always better to manually control this
        yourself by using :meth:`to_instruction` or :meth:`to_gate`, and then call
        :meth:`append`.

Returns:
    QuantumCircuit: the composed circuit (returns None if inplace==True).

Raises:
    CircuitError: if no correct wire mapping can be made between the two circuits, such as
        if ``other`` is wider than ``self``.
    CircuitError: if trying to emit a new circuit while ``self`` has a partially built
        control-flow context active, such as the context-manager forms of :meth:`if_test`,
        :meth:`for_loop` and :meth:`while_loop`.
    CircuitError: if trying to compose to the front of a circuit when a control-flow builder
        block is active; there is no clear meaning to this action.

Examples:
    .. code-block:: python

        >>> lhs.compose(rhs, qubits=[3, 2], inplace=True)

    .. code-block:: text

                    ┌───┐                   ┌─────┐                ┌───┐
        lqr_1_0: ───┤ H ├───    rqr_0: ──■──┤ Tdg ├    lqr_1_0: ───┤ H ├───────────────
                    ├───┤              ┌─┴─┐└─────┘                ├───┤
        lqr_1_1: ───┤ X ├───    rqr_1: ┤ X ├───────    lqr_1_1: ───┤ X ├───────────────
                 ┌──┴───┴──┐           └───┘                    ┌──┴───┴──┐┌───┐
        lqr_1_2: ┤ U1(0.1) ├  +                     =  lqr_1_2: ┤ U1(0.1) ├┤ X ├───────
                 └─────────┘                                    └─────────┘└─┬─┘┌─────┐
        lqr_2_0: ─────■─────                           lqr_2_0: ─────■───────■──┤ Tdg ├
                    ┌─┴─┐                                          ┌─┴─┐        └─────┘
        lqr_2_1: ───┤ X ├───                           lqr_2_1: ───┤ X ├───────────────
                    └───┘                                          └───┘
        lcr_0: 0 ═══════════                           lcr_0: 0 ═══════════════════════

        lcr_1: 0 ═══════════                           lcr_1: 0 ═══════════════════════

zPCannot compose to the front of a circuit while a control-flow context is active.zJCannot emit a new composed circuit while a control-flow context is active.Nc           	     B  > UR                  U 5      =n(       a  U$ TR                  U 5      =n(       d#  TR                  U R                  5      =n(       GaB  [        U [        R                  5      (       a  [        U[        R
                  5      (       a  [        SU  SU S35      e[        U[        5      (       a)  [        R                  R                  X0R                  5      nUR                  U R                  :w  a3  [        SU R                   SU R                   SUR                   S35      eOh[        U[        R                  5      (       a  [        SU  SU S35      e[        U[        5      (       a  [        R
                  R                  U5      nOU nX1U '   U$ )Nz-mismatched identifier kinds in replacement: 'z' cannot become ''z%mismatched types in replacement for 'z': 'z,mismatched identifier kind in replacement: ')
getrR   r[   r9   VarStretchr   rs   newrm   )r   cacher   replacementrX  s       r`   replace_var+QuantumCircuit.compose.<locals>.replace_varc  s{    iin$s$
(}}S111immTWT\T\F]7]{7]c488,,!+t||<<*!!$%6{m1F  "+s33&*hhll;&I"''3883*CCHH: N!!$
*;K<L<L;MQP  4 "+txx88*!!$%6{m1F  "+s33&*ll&6&6{&C!$#Jr   z>cannot implicitly add clbits while within a control-flow scopec              3  V   #    U  H  n[        UR                  [        5      v   M!     g 7frZ   )r[   r  r   )r^   inss     r`   ra   )QuantumCircuit.compose.<locals>.<genexpr>  s     M*3z#--66*s   ')copy_instructionsr   )r   r   r   zHTrying to compose with another QuantumCircuit which has more 'in' edges.z%Number of items in qubits parameter (z2) does not match number of qubits in the circuit (z).z4Duplicate qubits referenced in 'qubits' parameter: 'r\  z%Number of items in clbits parameter (z2) does not match number of clbits in the circuit (z4Duplicate clbits referenced in 'clbits' parameter: 'rh   c                  >^^^^ U R                  5        H  nUR                  T" UT5      5        M     U(       ac  U R                  5        HN  nT" UT5      nUR                  T" UT5      5      (       a  M+  XxL a  [	        SU S35      e[	        SU SU S35      e   O/U R                  5        H  nUR                  T" UT5      5        M     U R                  5        H  nUR                  T" UT5      5        M     U R                  5        H  n	UR                  T" U	T5      5        M     UUU4S jm[        R                  " UR                  TTUR                  S9mUUU4S jn
U R                  R                  TS	9nUR!                  XVS
9  UR#                  U
5        UR%                  5       R'                  U5        g )Nz
Variable 'zt' to be inlined is not in the base circuit. If you wanted it to be automatically added, use `inline_captures=False`.zReplacement 'z' for variable 'z:' is not in the base circuit.  Is the replacement correct?c                8   > U R                  SS9nT" XTTSS9  U$ )Ndrop	vars_modeF)rY  )r  )block	new_blockbit_mapcopy_with_remappingvar_maps     r`   recurse_blockJQuantumCircuit.compose.<locals>.copy_with_remapping.<locals>.recurse_block  s/    
 "11F1C	 $EgwX]^  r   )r{   c                  > U n[        U[        5      (       a  UR                  U4S jUR                   5       5      n[        U[        [
        45      (       a!  TR                  UR                  5      Ul        O[        U[        5      (       a   TR                  UR                  5      Ul        O[        U[        5      (       a?  [        TR                  UR                  5      TR                  UR                  5      5      nOU[        U[         5      (       a@  UR"                  S:X  a0  UR%                  5       nTR                  UR&                  5      Ul        XL a  T(       a  UR%                  5       $ U$ )Nc              3  4   >#    U  H  nT" U5      v   M     g 7frZ   rQ   )r^   ro  rt  s     r`   ra   XQuantumCircuit.compose.<locals>.copy_with_remapping.<locals>.map_vars.<locals>.<genexpr>
	  s     .]Q\}U/C/CQ\s   r9   )r[   r'   replace_blocksblocksr3   r7   map_condition
_condition	conditionr5   
map_targettargetrD   map_exprlvaluervaluerC   r   r   r   )opn_opr   rt  variable_mappers     r`   map_varsEQuantumCircuit.compose.<locals>.copy_with_remapping.<locals>.map_vars	  s   dM22...]QUQ\Q\.]]D!$;(?@@)8)F)Ft)W#D,77&5&@&@&Me,, '00=?W?WX\XcXc?dD  e,,f1D99;D$3$<$<T]]$KDM&*jTtyy{CtCr   rh  r(  )iter_input_varsr}   iter_captureshas_identifierr   r~   iter_declared_varsadd_uninitialized_variter_declared_stretchesadd_stretchr&   VariableMapperr   r{   ry   r   r   map_nonstandard_ops_current_scoper  )sourcedestrq  rs  rY  
new_qubits
new_clbitsr   rb  stretchr  r   rt  r  r   rr  rc  s     ``        @@r`   rr  3QuantumCircuit.compose.<locals>.copy_with_remapping  s    --/{389 0!//1C"-c7";K..{3/HII-".",SE 2< !<# 
 ++K=8H NJ J  2 "//1C$$[g%>? 2002**;sG+DE 3!99;  Wg!>? <	! 6DD

GW4;L;LOD" "<<,,t,DL%%Z%K,,X6!((6r   )rq  rs  rY  r  r  )r   Union[expr.Var, expr.Stretch]ra  zMapping[expr.Var, expr.Var]returnzUnion[expr.Var | expr.Stretch]NN)rx   r   r   r[   rN   r   r   r   r{   rj   r   r9  r:  r   r  
num_clbitsry   r   r   r   r   zip_qbit_argument_conversionlenr   _cbit_argument_conversionr   r   rS   r  r  )r   r   r   r   frontinplacewrapr   rX  rY  r  r_   old_datar   edge_mapmapped_qubitsmapped_clbits_append_existingrr  rc  s          ``          @@r`   composeQuantumCircuit.compose  sh   l u!:!: b  444 \  tDIIK#+B	!	.!	7R!	+!	J e^,,;;5<<,,&X  ell+ ;;C%%c* ' Jun55 M%**MMM ))+  %00~%7u'7'78~%7u'7'78::??T?B

E6=#+KLL- $, EvDI"4,,doo-1A1ADOO1SZ  8:> KKMOOCdkk:; ::6BM=!U%5%55";C<N;O P??D?O?O>PPRT  3}%&#m*<<"J=/YZ[  OOCm<=> KKMOOCdkk:; ::6BM=!U%5%55";C<N;O P??D?O?O>PPRT  3}%&#m*<<"J=/YZ[  OOCd.L.LV.TUV	U/// JJ Z^A	7 A	7F "jjoooEOJJL +$$	
 !((9t(D(r   c                   U R                   UR                   -   nU R                  UR                  -   n[        U R                  5      [        UR                  5      s=:X  a  S:X  aa  O  O^U R                  S   R                  UR                  S   R                  s=:X  a  S:X  a#  O  O US:  a  [        X45      nGO-[        U5      nGO [        U R                  5      [        UR                  5      s=:X  a  S:X  a  O  OU R                  S   R                  UR                  S   R                  s=:X  a  S:X  aJ  O  OG[        U R                  UR                  -   S5      n[        / UR                  QU R                  QUP76 nOe[        UR                  U R                  UR                  U R                  /UR                  QU R                  QUR                  QU R                  Q76 nUR                  U[        UR                   5      [        UR                  5      SS9  UR                  U [        UR                   U5      [        UR                  U5      SS9  U(       a&  U R                  R                  UR                  5        gU$ )u  Tensor ``self`` with ``other``.

Remember that in the little-endian convention the leftmost operation will be at the bottom
of the circuit. See also
`the docs <https://quantum.cloud.ibm.com/docs/guides/construct-circuits>`__
for more information.

.. code-block:: text

         ┌────────┐        ┌─────┐          ┌─────┐
    q_0: ┤ bottom ├ ⊗ q_0: ┤ top ├  = q_0: ─┤ top ├──
         └────────┘        └─────┘         ┌┴─────┴─┐
                                      q_1: ┤ bottom ├
                                           └────────┘

Args:
    other (QuantumCircuit): The other circuit to tensor this circuit with.
    inplace (bool): If ``True``, modify the object. Otherwise return composed circuit.

Examples:

    .. plot::
       :alt: Circuit diagram output by the previous code.
       :include-source:

       from qiskit import QuantumCircuit
       top = QuantumCircuit(1)
       top.x(0);
       bottom = QuantumCircuit(2)
       bottom.cry(0.2, 0, 1);
       tensored = bottom.tensor(top)
       tensored.draw('mpl')

Returns:
    QuantumCircuit: The tensored circuit (returns ``None`` if ``inplace=True``).
r   r   r  measTr  N)r  r  r  r   rR   rN   r   r$   r   r   r  r;  r   r   )r   r   r  r  r  r  crs          r`   tensorQuantumCircuit.tensor2	  s   J __u'7'77
__u'7'77
 

Os5;;/414

1""ekk!n&9&9@S@ A~%j=%j1
 

Os5;;/414

1""ekk!n&9&9CVC"4??U5E5E#EvNB!@5;;@@R@D "		
 	 	 	 	D 	UE%"2"23U5;K;K5LVZ[%""J/%""J/	 	 	
 MM  /r   c                .    U R                   R                  $ )zDict mapping Clbit instances to an object comprised of `.index` the
corresponding index in circuit. and `.registers` a list of
Register-int pairs for each Register containing the Bit and its index
within that register.)ry   _clbit_indicesr   s    r`   r  QuantumCircuit._clbit_indices	       zz(((r   c                .    U R                   R                  $ )zDict mapping Qubit instances to an object comprised of `.index` the
corresponding index in circuit. and `.registers` a list of
Register-int pairs for each Register containing the Bit and its index
within that register.)ry   _qubit_indicesr   s    r`   r  QuantumCircuit._qubit_indices	  r  r   c                .    U R                   R                  $ z[A list of :class:`Qubit`\ s in the order that they were added.  You should not mutate
this.)ry   r   r   s    r`   r   QuantumCircuit.qubits	  s     zz   r   c                .    U R                   R                  $ )a  A list of :class:`Clbit`\ s in the order that they were added.  You should not mutate
this.

Example:

    .. plot::
        :include-source:
        :nofigs:
        :context: reset

        from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit

        qr1 = QuantumRegister(2)
        qr2 = QuantumRegister(1)
        cr1 = ClassicalRegister(2)
        cr2 = ClassicalRegister(1)
        qc = QuantumCircuit(qr1, qr2, cr1, cr2)

        print("List the qubits in this circuit:", qc.qubits)
        print("List the classical bits in this circuit:", qc.clbits)

    .. code-block:: text

        List the qubits in this circuit: [Qubit(QuantumRegister(2, 'q0'), 0),
        Qubit(QuantumRegister(2, 'q0'), 1), Qubit(QuantumRegister(1, 'q1'), 0)]
        List the classical bits in this circuit: [Clbit(ClassicalRegister(2, 'c0'), 0),
        Clbit(ClassicalRegister(2, 'c0'), 1), Clbit(ClassicalRegister(1, 'c1'), 0)]
)ry   r   r   s    r`   r   QuantumCircuit.clbits	  s    < zz   r   c                .    U R                   R                  $ r  ry   r   r   s    r`   r   QuantumCircuit.qregs	       zzr   c                $    XR                   l        g rZ   r  r   r   s     r`   r   r  	       

r   c                .    U R                   R                  $ )z[A list of :class:`Clbit`\ s in the order that they were added.  You should not mutate
this.ry   r   r   s    r`   r   QuantumCircuit.cregs	  r  r   c                $    XR                   l        g rZ   r  r  s     r`   r   r  	  r  r   c                    U R                   $ )zbA list of :class:`AncillaQubit`\ s in the order that they were added.  You should not
mutate this.)rz   r   s    r`   ancillasQuantumCircuit.ancillas	  s     ~~r   c                N    U R                   U R                  -   U R                  -   $ )zrThe number of real-time classical variables in the circuit.

This is the length of the :meth:`iter_vars` iterable.)num_input_varsnum_captured_varsnum_declared_varsr   s    r`   num_varsQuantumCircuit.num_vars	  s&    
 ""T%;%;;d>T>TTTr   c                4    U R                   U R                  -   $ )zcThe number of stretches in the circuit.

This is the length of the :meth:`iter_stretches` iterable.)num_captured_stretchesnum_declared_stretchesr   s    r`   num_stretchesQuantumCircuit.num_stretches	  s    
 **T-H-HHHr   c                4    U R                   U R                  -   $ )zThe number of real-time classical variables and stretches in
the circuit.

This is equal to :meth:`num_vars` + :meth:`num_stretches`.
)r  r  r   s    r`   num_identifiersQuantumCircuit.num_identifiers	  s     }}t1111r   c                .    U R                   R                  $ )zThe number of real-time classical variables in the circuit marked as circuit inputs.

This is the length of the :meth:`iter_input_vars` iterable.  If this is non-zero,
:attr:`num_captured_vars` must be zero.)ry   r  r   s    r`   r  QuantumCircuit.num_input_vars	  r  r   c                .    U R                   R                  $ )zThe number of real-time classical variables in the circuit marked as captured from an
enclosing scope.

This is the length of the :meth:`iter_captured_vars` iterable.  If this is non-zero,
:attr:`num_input_vars` must be zero.)ry   r  r   s    r`   r   QuantumCircuit.num_captured_vars	  s     zz+++r   c                .    U R                   R                  $ )zThe number of stretches in the circuit marked as captured from an
enclosing scope.

This is the length of the :meth:`iter_captured_stretches` iterable.  If this is non-zero,
:attr:`num_input_vars` must be zero.)ry   r  r   s    r`   r  %QuantumCircuit.num_captured_stretches
  s     zz000r   c                .    U R                   R                  $ )zThe number of real-time classical variables in the circuit that are declared by this
circuit scope, excluding inputs or captures.

This is the length of the :meth:`iter_declared_vars` iterable.)ry   r  r   s    r`   r   QuantumCircuit.num_declared_vars
  s     zz+++r   c                .    U R                   R                  $ )zThe number of stretches in the circuit that are declared by this
circuit scope, excluding captures.

This is the length of the :meth:`iter_declared_stretches` iterable.)ry   r  r   s    r`   r  %QuantumCircuit.num_declared_stretches
  s     zz000r   c                h   U R                   (       aB  U R                   S   n[        R                  " UR                  5       UR	                  5       5      $ [        R                  " U R
                  R                  5       U R
                  R                  5       U R
                  R                  5       5      $ )a  Get an iterable over all real-time classical variables in scope within this circuit.

This method will iterate over all variables in scope.  For more fine-grained iterators, see
:meth:`iter_declared_vars`, :meth:`iter_input_vars` and :meth:`iter_captured_vars`.r&  )	rx   	itertoolschainiter_captured_varsiter_local_varsry   get_input_varsget_captured_varsget_declared_varsr   builders     r`   	iter_varsQuantumCircuit.iter_vars
  s    
 $$//3G??7#=#=#?AXAXAZ[[JJ%%'JJ((*JJ((*
 	
r   c                6   U R                   (       aB  U R                   S   n[        R                  " UR                  5       UR	                  5       5      $ [        R                  " U R
                  R                  5       U R
                  R                  5       5      $ )zGet an iterable over all stretches in scope within this circuit.

This method will iterate over all stretches in scope.  For more fine-grained iterators, see
:meth:`iter_declared_stretches` and :meth:`iter_captured_stretches`.r&  )rx   r  r  iter_captured_stretchesiter_local_stretchesry   get_captured_stretchesget_declared_stretchesr  s     r`   iter_stretchesQuantumCircuit.iter_stretches,
  sw    
 $$//3G??//173O3O3Q  JJ--/1R1R1T
 	
r   c                    U R                   (       a  U R                   S   R                  5       $ U R                  R                  5       $ )zGet an iterable over all real-time classical variables that are declared with automatic
storage duration in this scope.  This excludes input variables (see :meth:`iter_input_vars`)
and captured variables (see :meth:`iter_captured_vars`).r&  )rx   r  ry   r  r   s    r`   r  !QuantumCircuit.iter_declared_vars:
  s:     $$,,R0@@BBzz++--r   c                    U R                   (       a  U R                   S   R                  5       $ U R                  R                  5       $ )zGet an iterable over all stretches that are declared in this scope.
This excludes captured stretches (see :meth:`iter_captured_stretches`).r&  )rx   r  ry   r  r   s    r`   r  &QuantumCircuit.iter_declared_stretchesB
  s:     $$,,R0EEGGzz0022r   c                Z    U R                   (       a  gU R                  R                  5       $ )zGet an iterable over all real-time classical variables that are declared as inputs to
this circuit scope.  This excludes locally declared variables (see
:meth:`iter_declared_vars`) and captured variables (see :meth:`iter_captured_vars`).rQ   )rx   ry   r  r   s    r`   r  QuantumCircuit.iter_input_varsI
  s#     $$zz((**r   c                L   U R                   (       aM  [        R                  " U R                   S   R                  5       U R                   S   R	                  5       5      $ [        R                  " U R
                  R                  5       U R
                  R                  5       5      $ )a  Get an iterable over all identifiers are captured by this circuit scope from a
containing scope.  This excludes input variables (see :meth:`iter_input_vars`)
and locally declared variables and stretches (see :meth:`iter_declared_vars`
and :meth:`iter_declared_stretches`).r&  )rx   r  r  r  r  ry   r  r  r   s    r`   r  QuantumCircuit.iter_capturesQ
  sy    
 $$??))"-@@B))"-EEG  tzz;;=tzz?`?`?bccr   c                    U R                   (       a  U R                   S   R                  5       $ U R                  R                  5       $ )zGet an iterable over all real-time classical variables that are captured by this circuit
scope from a containing scope.  This excludes input variables (see :meth:`iter_input_vars`)
and locally declared variables (see :meth:`iter_declared_vars`).r&  )rx   r  ry   r  r   s    r`   r  !QuantumCircuit.iter_captured_vars]
  s:     $$,,R0CCEEzz++--r   c                    U R                   (       a  U R                   S   R                  5       $ U R                  R                  5       $ )zGet an iterable over stretches that are captured by this circuit
scope from a containing scope.  This excludes locally declared stretches
(see :meth:`iter_declared_stretches`).r&  )rx   r  ry   r  r   s    r`   r  &QuantumCircuit.iter_captured_stretchese
  s:     $$,,R0HHJJzz0022r   c                $    U R                  U5      $ )z%Overload & to implement self.compose.r  r   rhss     r`   __and__QuantumCircuit.__and__m
  s    ||C  r   c                &    U R                  USS9  U $ )z/Overload &= to implement self.compose in place.Tr  r  r  s     r`   __iand__QuantumCircuit.__iand__q
  s    S$'r   c                $    U R                  U5      $ )z$Overload ^ to implement self.tensor.r  r   tops     r`   __xor__QuantumCircuit.__xor__v
  s    {{3r   c                &    U R                  USS9  U $ )z.Overload ^= to implement self.tensor in place.Tr  r  r  s     r`   __ixor__QuantumCircuit.__ixor__z
  s    C&r   c                ,    [        U R                  5      $ )z'Return number of operations in circuit.)r  ry   r   s    r`   __len__QuantumCircuit.__len__
  s    4::r   c                    g rZ   rQ   r   items     r`   __getitem__QuantumCircuit.__getitem__
  s    <?r   c                    g rZ   rQ   r  s     r`   r  r  
      DGr   c                     U R                   U   $ )zReturn indexed operation.)ry   r  s     r`   r  r  
  s    zz$r   c                D     U" U 5      $ ! [         [        4 a    U s $ f = f)z@Best effort to cast value to type. Otherwise, returns the value.)rk   rl   )r   type_s     r`   _castQuantumCircuit._cast
  s*    	<I& 	L	s   
 c                8    U R                   R                  U5      $ )z
Converts several qubit representations (such as indexes, range, etc.)
into a list of qubits.

Args:
    qubit_representation: Representation to expand.

Returns:
    The resolved instances of the qubits.
)ry   r  )r   qubit_representations     r`   r  (QuantumCircuit._qbit_argument_conversion
       zz334HIIr   c                8    U R                   R                  U5      $ )z
Converts several classical bit representations (such as indexes, range, etc.)
into a list of classical bits.

Args:
    clbit_representation: Representation to expand.

Returns:
    A list of tuples where each tuple is a classical bit.
)ry   r  )r   clbit_representations     r`   r  (QuantumCircuit._cbit_argument_conversion
  r&  r   c                    U R                  5       nUc  / nU=(       d    /  Vs/ s H  o`R                  U5      PM     nnU H  n[        R                  " X5        M     [	        UR
                  S9n	[        R                  " X/ 5       Hm  u  pjU R                  U5        [        R                  " XX4S9nUR                  USS9  U	R                  UR                  [        UR                  5      S-
  5        Mo     U	$ s  snf )zSAn internal method to bypass some checking when directly appending a standard gate.resource_requesterrR  T_standard_gater   )r  r  r   validate_parameterr?   resolve_classical_resourcebroadcast_arguments_check_dupsrB   from_standardr   _add_refr   r  )r   r  r   paramsrR  circuit_scopeqargexpanded_qargsparamr   r  r   s               r`   _append_standard_gate$QuantumCircuit._append_standard_gate
  s     ++->FKP;TV;W;488>;WE##B.  &9a9ab//BGGDT",::2VYK  T B!!-"<"<c-B\B\>]`a>ab	 H
  Xs   C;r   c               |   [        U[        5      (       a%  UR                  nUR                  nUR                  nOUn[        U[
        5      (       dm  [        US5      (       a1  UR                  5       n[        U[
        5      (       d  [        S5      eO+[        U[
        5      (       a  [        S5      e[        S5      eU R                  5       n[        USS5      =n(       at  SnU HH  n	U=(       d    [        U	[        5      n[        U	[        R                  5      (       d  M=  [        Xi5      n	MJ     U(       a  U(       a  [         R"                  " U5      n[        U[$        5      (       a  UR&                  S:X  a%  UR(                  S	:X  a  [        XeR*                  5        [,        R.                  R1                  S
 UR2                   5       5       V
s1 s H  n
U R5                  U
5      (       a  M  U
iM     sn
=n(       a  [        SU S35      eU=(       d    /  Vs/ s H  oR7                  U5      PM     nnU=(       d    /  Vs/ s H  oR9                  U5      PM     nn[;        UR<                  S9n[        U[>        5      (       a  URA                  X5      O[>        R@                  " X]U5      n[        USS5      nU Hh  u  pU RC                  U5        URE                  XS9nURG                  U5        URI                  URJ                  [M        URJ                  5      S-
  5        Mj     U$ s  sn
f s  snf s  snf )a  Append one or more instructions to the end of the circuit, modifying the circuit in
place.

The ``qargs`` and ``cargs`` will be expanded and broadcast according to the rules of the
given :class:`~.circuit.Instruction`, and any non-:class:`.Bit` specifiers (such as
integer indices) will be resolved into the relevant instances.

If a :class:`.CircuitInstruction` is given, it will be unwrapped, verified in the context of
this circuit, and a new object will be appended to the circuit.  In this case, you may not
pass ``qargs`` or ``cargs`` separately.

Args:
    instruction: :class:`~.circuit.Instruction` instance to append, or a
        :class:`.CircuitInstruction` with all its context.
    qargs: specifiers of the :class:`~.circuit.Qubit`\ s to attach instruction to.
    cargs: specifiers of the :class:`.Clbit`\ s to attach instruction to.
    copy: if ``True`` (the default), then the incoming ``instruction`` is copied before
        adding it to the circuit if it contains symbolic parameters, so it can be safely
        mutated without affecting other circuits the same instruction might be in.  If you
        are sure this instruction will not be in other circuits, you can set this ``False``
        for a small speedup.

Returns:
    qiskit.circuit.InstructionSet: a handle to the :class:`.CircuitInstruction`\ s that
    were actually added to the circuit.

Raises:
    CircuitError: if the operation passed is not an instance of :class:`~.circuit.Instruction` .
r:  z/operation.to_instruction() is not an Operation.zTObject is a subclass of Operation, please add () to pass an instance of this object.zHObject to append must be an Operation or have a to_instruction() method.r6  rQ   Fboxr9   c              3  @   #    U  H  oR                  5       v   M     g 7frZ   )r  )r^   ro  s     r`   ra   (QuantumCircuit.append.<locals>.<genexpr>  s      97Ge''))7Gs   z%Control-flow op attempts to capture 'z' which are not in this circuitr+  r(  r   )'r[   rB   r  r   r   r@   hasattrr:  r   
issubclassr  getattrr;   r9   Expr_validate_exprr   r   r'   rR   r   r   r  r  from_iterablerz  r  r  r  r?   r1  r   r2  r3  r   r   r5  r   r  )r   r   r   r   r   r  r7  r6  is_parameterr:  r   bad_capturesr8  r9  cargexpanded_cargsr   broadcast_iterbase_instructions                      r`   r   QuantumCircuit.append
  s   J k#566#--I&&E&&E#I )Y//y"233%446	!)Y77&'XYY 8 i33&; 
 #^  ++- Y"5565 L+Uz%AT/UeTYY//*=@E   !NN95	i//~~&9>>V+C}.@.@A
 %??88 97@7G7G9  C **3/	   |  #;L> J5 5 
 LQ;TV;W;488>;WKP;TV;W;488>;W%9a9ab )[11 )).I00N[ 	
 .iR@(JDT"*22$2LK  -!!-"<"<c-B\B\>]`a>ab	 )
 9  XWs   L/1L/L4L9c                   g rZ   rQ   r   r   r/  s      r`   r   QuantumCircuit._append4  s     !r   c                    g rZ   rQ   )r   r   r   r   s       r`   r   rP  :  s     r   r.  c          
     N   U(       a+  U R                   R                  U5        SU l        SU l        U$ [	        U[
        5      (       + nU(       a  [        XU5      n U R                   R                  U5        SU l        SU l        U(       a  UR                  $ U$ ! [         a    [        UR                  R                  5       VVs/ s H/  u  pg[	        U[        [        45      (       d  M"  XgR                  4PM1     Os  snnf nnnU R                   R                  X5         Nf = f)a^  Append an instruction to the end of the circuit, modifying the circuit in place.

.. warning::

    This is an internal fast-path function, and it is the responsibility of the caller to
    ensure that all the arguments are valid; there is no error checking here.  In
    particular:

    * all the qubits and clbits must already exist in the circuit and there can be no
      duplicates in the list.
    * any control-flow operations instructions must act only on variables present in the
      circuit.
    * the circuit must not be within a control-flow builder context.

.. note::

    This function may be used by callers other than :obj:`.QuantumCircuit` when the caller
    is sure that all error-checking, broadcasting and scoping has already been performed,
    and the only reference to the circuit the instructions are being appended to is within
    that same function.  In particular, it is not safe to call
    :meth:`QuantumCircuit._append` on a circuit that is received by a function argument.
    This is because :meth:`.QuantumCircuit._append` will not recognize the scoping
    constructs of the control-flow builder interface.

Args:
    instruction: A complete well-formed :class:`.CircuitInstruction` of the operation and
        its context to be added.

        In the legacy compatibility form, this can be a bare :class:`.Operation`, in which
        case ``qargs`` and ``cargs`` must be explicitly given.
    qargs: Legacy argument for qubits to attach the bare :class:`.Operation` to.  Ignored if
        the first argument is in the preferential :class:`.CircuitInstruction` form.
    cargs: Legacy argument for clbits to attach the bare :class:`.Operation` to.  Ignored if
        the first argument is in the preferential :class:`.CircuitInstruction` form.

Returns:
    CircuitInstruction: a handle to the instruction that was just added.

:meta public:
Nrh   )ry   r   r   r   r[   rB   RuntimeErrorr  r  r6  r;   rN   rG  append_manual_params)	r   r   r   r   r/  	old_styleidxr:  r6  s	            r`   r   rP  B  s   R JJk*!DNDJ";0BCC	,[GK	AJJk* 
(1{$$B{B  	A #,K,A,A,H,H"I"IJCe&9>%JK (&&'"IF 
 JJ++K@	As$   B ,D$!C=+C=<%D$#D$c                    g rZ   rQ   r   rR   defaults      r`   get_parameterQuantumCircuit.get_parameter  s    KNr   .c                    g rZ   rQ   rX  s      r`   rZ  r[    s    ORr   c                v    U R                   R                  U5      =nc  U[        L a  [        SU S35      eU$ U$ )a  Retrieve a compile-time parameter that is accessible in this circuit scope by name.

Args:
    name: the name of the parameter to retrieve.
    default: if given, this value will be returned if the parameter is not present.  If it
        is not given, a :exc:`KeyError` is raised instead.

Returns:
    The corresponding parameter.

Raises:
    KeyError: if no default is given, but the parameter does not exist in the circuit.

Examples:
    Retrieve a parameter by name from a circuit::

        from qiskit.circuit import QuantumCircuit, Parameter

        my_param = Parameter("my_param")

        # Create a parametrized circuit.
        qc = QuantumCircuit(1)
        qc.rx(my_param, 0)

        # We can use 'my_param' as a parameter, but let's say we've lost the Python object
        # and need to retrieve it.
        my_param_again = qc.get_parameter("my_param")

        assert my_param is my_param_again

    Get a variable from a circuit by name, returning some default if it is not present::

        assert qc.get_parameter("my_param", None) is my_param
        assert qc.get_parameter("unknown_param", None) is None

See also:
    :meth:`get_var`
        A similar method, but for :class:`.expr.Var` run-time variables instead of
        :class:`.Parameter` compile-time parameters.
zno parameter named '' is present)ry   get_parameter_by_nameEllipsisKeyError)r   rR   rY  	parameters       r`   rZ  r[    sG    R 99$??IH("!5dV<HIINr   c                   [        U[        5      (       a  U R                  US5      SL$ [        U[        5      =(       a    U R                  UR                  S5      U:H  $ )a  Check whether a parameter object exists in this circuit.

Args:
    name_or_param: the parameter, or name of a parameter to check.  If this is a
        :class:`.Parameter` node, the parameter must be exactly the given one for this
        function to return ``True``.

Returns:
    whether a matching parameter is assignable in this circuit.

See also:
    :meth:`QuantumCircuit.get_parameter`
        Retrieve the :class:`.Parameter` instance from this circuit by name.
    :meth:`QuantumCircuit.has_var`
        A similar method to this, but for run-time :class:`.expr.Var` variables instead of
        compile-time :class:`.Parameter`\ s.
N)r[   rs   rZ  r   rR   )r   name_or_params     r`   has_parameterQuantumCircuit.has_parameter  sY    $ mS))%%mT:$FF}i0 N""=#5#5t<M	
r   c                    g rZ   rQ   rX  s      r`   get_varQuantumCircuit.get_var  r  r   c                    g rZ   rQ   rX  s      r`   rh  ri    s    HKr   c                ~    U R                  5       R                  U5      =nb  U$ U[        L a  [        SU S35      eU$ )a  Retrieve a variable that is accessible in this circuit scope by name.

Args:
    name: the name of the variable to retrieve.
    default: if given, this value will be returned if the variable is not present.  If it
        is not given, a :exc:`KeyError` is raised instead.

Returns:
    The corresponding variable.

Raises:
    KeyError: if no default is given, but the variable does not exist.

Examples:
    Retrieve a variable by name from a circuit::

        from qiskit.circuit import QuantumCircuit

        # Create a circuit and create a variable in it.
        qc = QuantumCircuit()
        my_var = qc.add_var("my_var", False)

        # We can use 'my_var' as a variable, but let's say we've lost the Python object and
        # need to retrieve it.
        my_var_again = qc.get_var("my_var")

        assert my_var is my_var_again

    Get a variable from a circuit by name, returning some default if it is not present::

        assert qc.get_var("my_var", None) is my_var
        assert qc.get_var("unknown_variable", None) is None

See also:
    :meth:`get_parameter`
        A similar method, but for :class:`.Parameter` compile-time parameters instead of
        :class:`.expr.Var` run-time variables.
zno variable named 'r^  )r  rh  r`  ra  r   rR   rY  r   s       r`   rh  ri    sK    N &&(0066CCJh0lCDDr   c                   [        U[        5      (       a  U R                  US5      SL$ U R                  UR                  S5      U:H  $ )ah  Check whether a variable is accessible in this scope.

Args:
    name_or_var: the variable, or name of a variable to check.  If this is a
        :class:`.expr.Var` node, the variable must be exactly the given one for this
        function to return ``True``.

Returns:
    whether a matching variable is accessible.

See also:
    :meth:`QuantumCircuit.get_var`
        Retrieve the :class:`.expr.Var` instance from this circuit by name.
    :meth:`QuantumCircuit.has_parameter`
        A similar method to this, but for compile-time :class:`.Parameter`\ s instead of
        run-time :class:`.expr.Var` variables.
N)r[   rs   rh  rR   )r   name_or_vars     r`   has_varQuantumCircuit.has_var  sC    $ k3''<<T2$>>||K,,d3{BBr   c                    g rZ   rQ   rX  s      r`   get_stretchQuantumCircuit.get_stretch#  s    LOr   c                    g rZ   rQ   rX  s      r`   rr  rs  '  s    PSr   c                ~    U R                  5       R                  U5      =nb  U$ U[        L a  [        SU S35      eU$ )aA  Retrieve a stretch that is accessible in this circuit scope by name.

Args:
    name: the name of the stretch to retrieve.
    default: if given, this value will be returned if the variable is not present.  If it
        is not given, a :exc:`KeyError` is raised instead.

Returns:
    The corresponding stretch.

Raises:
    KeyError: if no default is given, but the variable does not exist.

Examples:
    Retrieve a stretch by name from a circuit::

        from qiskit.circuit import QuantumCircuit

        # Create a circuit and create a variable in it.
        qc = QuantumCircuit()
        my_stretch = qc.add_stretch("my_stretch")

        # We can use 'my_stretch' as a variable, but let's say we've lost the Python object and
        # need to retrieve it.
        my_stretch_again = qc.get_stretch("my_stretch")

        assert my_stretch is my_stretch_again

    Get a variable from a circuit by name, returning some default if it is not present::

        assert qc.get_stretch("my_stretch", None) is my_stretch
        assert qc.get_stretch("unknown_stretch", None) is None
zno stretch named 'r^  )r  rr  r`  ra  rl  s       r`   rr  rs  *  sK    D &&(44T::CGJh/v\BCCr   c                   [        U[        5      (       a  U R                  US5      SL$ U R                  UR                  S5      U:H  $ )a  Check whether a stretch is accessible in this scope.

Args:
    name_or_stretch: the stretch, or name of a stretch to check.  If this is a
        :class:`.expr.Stretch` node, the stretch must be exactly the given one for this
        function to return ``True``.

Returns:
    whether a matching stretch is accessible.

See also:
    :meth:`QuantumCircuit.get_stretch`
        Retrieve the :class:`.expr.Stretch` instance from this circuit by name.
N)r[   rs   rr  rR   )r   name_or_stretchs     r`   has_stretchQuantumCircuit.has_stretchR  sG     os++##OT:$FF 4 4d;NNr   c                    g rZ   rQ   rX  s      r`   get_identifierQuantumCircuit.get_identifiere  s    Z]r   c                    g rZ   rQ   rX  s      r`   r{  r|  i  s     ),r   c                    U R                  5       R                  U5      =nb  U$ U R                  5       R                  U5      =nb  U$ U[        L a  [	        SU S35      eU$ )aG  Retrieve an identifier that is accessible in this circuit scope by name.

This currently includes both real-time classical variables and stretches.

Args:
    name: the name of the identifier to retrieve.
    default: if given, this value will be returned if the variable is not present.  If it
        is not given, a :exc:`KeyError` is raised instead.

Returns:
    The corresponding variable.

Raises:
    KeyError: if no default is given, but the identifier does not exist.

See also:
    :meth:`get_var`
        Gets an identifier known to be a :class:`.expr.Var` instance.
    :meth:`get_stretch`
        Gets an identifier known to be a :class:`.expr.Stretch` instance.
    :meth:`get_parameter`
        A similar method, but for :class:`.Parameter` compile-time parameters instead of
        :class:`.expr.Var` run-time variables.
zno identifier named 'r^  )r  rh  rr  r`  ra  rl  s       r`   r{  r|  o  sn    2 &&(0066CCJ&&(44T::CGJh24&EFFr   c                   [        U[        5      (       a  U R                  US5      SL$ U R                  UR                  S5      U:H  $ )a  Check whether an identifier is accessible in this scope.

Args:
    name_or_ident: the instance, or name of the identifier to check.  If this is a
        :class:`.expr.Var` or :class:`.expr.Stretch` node, the matched instance must
        be exactly the given one for this function to return ``True``.

Returns:
    whether a matching identifier is accessible.

See also:
    :meth:`QuantumCircuit.get_identifier`
        Retrieve the :class:`.expr.Var` or :class:`.expr.Stretch` instance from this
        circuit by name.
    :meth:`QuantumCircuit.has_var`
        The same as this method, but ignoring anything that isn't a
        run-time :class:`expr.Var` variable.
    :meth:`QuantumCircuit.has_stretch`
        The same as this method, but ignoring anything that isn't a
        run-time :class:`expr.Stretch` variable.
    :meth:`QuantumCircuit.has_parameter`
        A similar method to this, but for compile-time :class:`.Parameter`\ s instead of
        run-time :class:`.expr.Var` variables.
N)r[   rs   r{  rR   )r   name_or_idents     r`   r  QuantumCircuit.has_identifier  sG    2 mS))&&}d;4GG""=#5#5t<MMr   c               N   [        U[        5      (       a.  Uc  [        S5      e[        R                  R                  X5      nOUnUR                  (       d  [        S5      eU R                  UR                  SS9=nb&  XC:X  a  [        SU S35      e[        SU SU S35      eU$ )	a  The common logic for preparing and validating a new :class:`~.expr.Var` for the circuit.

The given ``type_`` can be ``None`` if the variable specifier is already a :class:`.Var`,
and must be a :class:`~.types.Type` if it is a string.  The argument is ignored if the given
first argument is a :class:`.Var` already.

Returns the validated variable, which is guaranteed to be safe to add to the circuit.Nz:the type must be known when creating a 'Var' from a stringzycannot add variables that wrap `Clbit` or `ClassicalRegister` instances. Use `add_bits` or `add_register` as appropriate.rY  r\  #' is already present in the circuitcannot add '$' as its name shadows the existing ')	r[   rs   r   r9   r^  r`  
standaloner{  rR   )r   rn  r   r   previouss        r`   _prepare_new_varQuantumCircuit._prepare_new_var  s     k3''}"#_``((,,{2CC>>"H  ++CHHd+CCHP"Qse+N#OPPcU2VW_V``abcc
r   c                   [        U[        5      (       a   [        R                  R	                  U5      nOUnU R                  UR                  SS9=nb&  X2:X  a  [        SU S35      e[        SU SU S35      eU$ )zThe common logic for preparing and validating a new :class:`~.expr.Stretch` for the circuit.

Returns the validated stretch, which is guaranteed to be safe to add to the circuit.Nr  r\  r  r  r  )r[   rs   r9   r_  r`  r{  rR   r   )r   rw  r  r  s       r`   _prepare_new_stretch#QuantumCircuit._prepare_new_stretch  s     os++ll&&7G%G++GLL$+GGHT""Qwi/R#STTwi'KH:UVW  r   c                    [        U[        5      (       a   [        R                  R	                  U5      nOUnU R                  5       R                  U5        U$ )a5  Declares a new stretch scoped to this circuit.

Args:
    name_or_stretch: either a string of the stretch name, or an existing instance of
        :class:`~.expr.Stretch` to re-use.  Stretches cannot shadow names that are already in
        use within the circuit.

Returns:
    The created stretch.  If a :class:`~.expr.Stretch` instance was given, the exact same
    object will be returned.

Raises:
    CircuitError: if the stretch cannot be created due to shadowing an existing
        identifier.

Examples:
    Define and use a new stretch given just a name::

        from qiskit.circuit import QuantumCircuit, Duration
        from qiskit.circuit.classical import expr

        qc = QuantumCircuit(2)
        my_stretch = qc.add_stretch("my_stretch")

        qc.delay(expr.add(Duration.dt(200), my_stretch), 1)
)r[   rs   r9   r_  r`  r  r  )r   rw  r  s      r`   r  QuantumCircuit.add_stretch  sF    6 os++ll&&7G%G))'2r   c                  U R                  5       n[        U[        R                  5      (       a^  UR                  R
                  [        R                  L a7  [        U[        5      (       a"  [        U[        5      (       d  UR                  nOSn[        U[        R                  " X$5      5      n[        U[        5      (       a*  [        R                  R                  XR                  5      nOUR                  (       d  [        S5      eUn[!        XR5      nUR#                  U5        UR%                  ['        USS5      5        U$ )a	  Add a classical variable with automatic storage and scope to this circuit.

The variable is considered to have been "declared" at the beginning of the circuit, but it
only becomes initialized at the point of the circuit that you call this method, so it can
depend on variables defined before it.

Args:
    name_or_var: either a string of the variable name, or an existing instance of
        :class:`~.expr.Var` to re-use.  Variables cannot shadow names that are already in
        use within the circuit.
    initial: the value to initialize this variable with.  If the first argument was given
        as a string name, the type of the resulting variable is inferred from the initial
        expression; to control this more manually, either use :meth:`.Var.new` to manually
        construct a new variable with the desired type, or use :func:`.expr.cast` to cast
        the initializer to the desired type.

        This must be either a :class:`~.expr.Expr` node, or a value that can be lifted to
        one using :class:`.expr.lift`.

Returns:
    The created variable.  If a :class:`~.expr.Var` instance was given, the exact same
    object will be returned.

Raises:
    CircuitError: if the variable cannot be created due to shadowing an existing identifier.

Examples:
    Define a new variable given just a name and an initializer expression::

        from qiskit.circuit import QuantumCircuit

        qc = QuantumCircuit(2)
        my_var = qc.add_var("my_var", False)

    Reuse a variable that may have been taken from a related circuit, or otherwise
    constructed manually, and initialize it to some more complicated expression::

        from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
        from qiskit.circuit.classical import expr, types

        my_var = expr.Var.new("my_var", types.Uint(8))

        cr1 = ClassicalRegister(8, "cr1")
        cr2 = ClassicalRegister(8, "cr2")
        qc = QuantumCircuit(QuantumRegister(8), cr1, cr2)

        # Get some measurement results into each register.
        qc.h(0)
        for i in range(1, 8):
            qc.cx(0, i)
        qc.measure(range(8), cr1)

        qc.reset(range(8))
        qc.h(0)
        for i in range(1, 8):
            qc.cx(0, i)
        qc.measure(range(8), cr2)

        # Now when we add the variable, it is initialized using the real-time state of the
        # two classical registers we measured into above.
        qc.add_var(my_var, expr.bit_and(cr1, cr2))
NzHcannot add variables that wrap `Clbit` or `ClassicalRegister` instances.rQ   )r  r[   r9   r^  rm   kindr:   Uintre   boolrE  liftrs   r`  r  r   rD   r  r   rB   )r   rn  r   r7  coerce_typer   stores          r`   r   QuantumCircuit.add_var  s    B ++- {DHH--  %%37C((w--%**KK 		'0OPk3''((,,{LL9C''Z  C c#++C0/r2>?
r   c                   U R                   (       a  [        S5      eUR                  (       d  [        S5      eU R                  R	                  U5        g)ay  Add a variable with no initializer.

In most cases, you should use :meth:`add_var` to initialize the variable.  To use this
function, you must already hold a :class:`~.expr.Var` instance, as the use of the function
typically only makes sense in copying contexts.

.. warning::

    Qiskit makes no assertions about what an uninitialized variable will evaluate to at
    runtime, and some hardware may reject this as an error.

    You should treat this function with caution, and as a low-level primitive that is useful
    only in special cases of programmatically rebuilding two like circuits.

Args:
    var: the variable to add.
z<cannot add an uninitialized variable in a control-flow scopez=cannot add a variable wrapping a bit or register to a circuitN)rx   r   r  rv   r  r   r   s     r`   r  $QuantumCircuit.add_uninitialized_var\  s@    6 $$]^^~~^__//4r   c                    g rZ   rQ   r  s     r`   r~   QuantumCircuit.add_capture}  s    *-r   c                    g rZ   rQ   r   r  s     r`   r~   r    s    25r   c                   U R                   (       a]  [        U[        R                  5      (       a  U R                   S   R	                  U5        gU R                   S   R                  U5        gU R                  R                  (       a  [        S5      e[        U[        R                  5      (       a+  U R                  R                  U R                  U5      5        gU R                  R                  U R                  US5      5        g)a  Add an identifier to the circuit that it should capture from a scope it will
be contained within.

This method requires a :class:`~.expr.Var` or :class:`~.expr.Stretch` node to enforce that
you've got a handle to an identifier, because you will need to declare the same identifier
using the same object in the outer circuit.

This is a low-level method, which is only really useful if you are manually constructing
control-flow operations. You typically will not need to call this method, assuming you
are using the builder interface for control-flow scopes (``with`` context-manager statements
for :meth:`if_test` and the other scoping constructs).  The builder interface will
automatically make the inner scopes closures on your behalf by capturing any identifiers
that are used within them.

Args:
    var (Union[expr.Var, expr.Stretch]): the variable or stretch to capture from an
        enclosing scope.

Raises:
    CircuitError: if the identifier cannot be created due to shadowing an existing
        identifier.
r&  NzLcircuits with input variables cannot be enclosed, so they cannot be closures)rx   r[   r9   r_  use_stretchuse_varry   r  r   add_captured_stretchr  add_captured_varr  r  s     r`   r~   r    s    . $$ #t||,,))"-99#>  ))"-55c:::$$^  c4<<((JJ++D,E,Ec,JKJJ''(=(=c4(HIr   c                   g rZ   rQ   r   rn  r   s      r`   r}   QuantumCircuit.add_input  s    MPr   c                   g rZ   rQ   r  s      r`   r}   r    s    SVr   c               r   U R                   (       a  [        S5      eU R                  R                  (       d  U R                  R                  (       a  [        S5      e[        U[        R                  5      (       a  Ub  [        S5      eU R                  X5      nU R                  R                  U5        U$ )ag  Register a variable as an input to the circuit.

Args:
    name_or_var: either a string name, or an existing :class:`~.expr.Var` node to use as the
        input variable.
    type_: if the name is given as a string, then this must be a :class:`~.types.Type` to
        use for the variable.  If the variable is given as an existing :class:`~.expr.Var`,
        then this must not be given, and will instead be read from the object itself.

Returns:
    the variable created, or the same variable as was passed in.

Raises:
    CircuitError: if the variable cannot be created due to shadowing an existing variable.
z4cannot add an input variable in a control-flow scopezAcircuits to be enclosed with captures cannot have input variablesz1cannot give an explicit type with an existing Var)rx   r   ry   r  r  r[   r9   r^  rk   r  add_input_var)r   rn  r   r   s       r`   r}   r    s    $ $$UVV::''4::+L+Lbcck488,,1BPQQ##K7

  %
r   c                  ^ U(       d  g[        S U 5       5      (       a  [        U5      S:X  a5  [        US   [        5      (       a  US   S:X  a  SnO[	        US   S5      4nOs[        U5      S:X  aT  [        S U 5       5      (       a=  US   S:X  a  SnO[	        US   S5      4nUS   S:X  a  SnO[        US   S	5      4nX#-   nO[        S
U4 S35      eU GHg  m[        T[        5      (       aJ  [        U4S jU R                  U R                  -    5       5      (       a  [        STR                   S35      e[        T[        5      (       a5  T H/  nX@R                  ;  d  M  U R                  R                  U5        M1     [        T[        5      (       aA  [!        U SS5      b  ["        R$                  " SSS9  U R&                  R)                  T5        GM  [        T[        5      (       a  U R&                  R+                  T5        GM6  [        T[,        5      (       a  U R/                  T5        GM_  [        S5      e   g)zAdd registers.

.. warning::

    If the quantum circuit has an existing :attr:`layout` attribute, adding a
    :class:`.QuantumRegister` will only increase the number of qubits. It will
    not update the layout.
Nc              3  B   #    U  H  n[        U[        5      v   M     g 7frZ   r[   re   r]   s     r`   ra   .QuantumCircuit.add_register.<locals>.<genexpr>  s     4tz#s##t   r   r   rQ   r     c              3  B   #    U  H  n[        U[        5      v   M     g 7frZ   r  r]   s     r`   ra   r    s     'M
3(<(<r  czwQuantumCircuit parameters can be Registers or Integers. If Integers, up to 2 arguments. QuantumCircuit was called with .c              3  V   >#    U  H  nTR                   UR                   :H  v   M      g 7frZ   r   )r^   r_   r  s     r`   ra   r    s"      65Lc)5Ls   &)zregister name "z" already existsr   zATrying to add QuantumRegister to a QuantumCircuit having a layout
stacklevelzexpected a register)ri   r  r[   re   r   rj   r$   r   r%   r   r   rR   r!   r  rz   r   rC  warningswarnry   add_qregadd_cregr\   r   )r   r   r   r   bitr  s        @r`   r{   QuantumCircuit.add_register  s    4t4444yA~*T!Wc":":7a<D+DGS9;DTaC'M'M$M$M7a<9;E,T!Wc:<E7a<;=E.tAw<>E}""WIQ(  H(H--# 659ZZ$**5L6 3 3 #_X]]OCS#TUU(O44#C"5"55--c2 $ (O44440<MM[#$ 

##H-H&788

##H-Hd++h'"#8993 r   c                4   U Vs1 s H%  o"U R                   ;   d  X R                  ;   d  M#  UiM'     nnU(       a  [        SU 35      eU H  n[        U[        5      (       a  U R
                  R                  U5        [        U[        5      (       a@  [        U SS5      b  [        R                  " SSS9  U R                  R                  U5        M  [        U[        5      (       a  U R                  R                  U5        M  [        SU 35      e   gs  snf )zAdd Bits to the circuit.

.. warning::

    If the quantum circuit has an existing :attr:`layout` attribute,
    adding a :class:`.Qubit` will only increase the number of qubits.
    It will not update the layout.
z0Attempted to add bits found already in circuit: r   Nz6Trying to add bits to a QuantumCircuit having a layoutr  r  zFExpected an instance of Qubit, Clbit, or AncillaQubit, but was passed )r  r  r   r[   r"   rz   r   r    rC  r  r  ry   	add_qubitr#   	add_clbit)r   r'  r  duplicate_bitss       r`   r   QuantumCircuit.add_bits  s      
C$*=*=#=H[H[A[C4 	 
 !QR`QabccC#|,,%%c*#u%%440<MMP#$ 

$$S)C''

$$S)"4475:  
s
   "DDc                .    [        U[        5      (       a  U R                  R                  U   $ [        U[        5      (       a  U R                  R
                  U   $ [        S[        U5       35      e! [         a  n[        SU S35      UeSnAff = f)a7  Find locations in the circuit which can be used to reference a given :obj:`~Bit`.

In particular, this function can find the integer index of a qubit, which corresponds to its
hardware index for a transpiled circuit.

.. note::
    The circuit index of a :class:`.AncillaQubit` will be its index in :attr:`qubits`, not
    :attr:`ancillas`.

Args:
    bit (Bit): The bit to locate.

Returns:
    namedtuple(int, List[Tuple(Register, int)]): A 2-tuple. The first element (``index``)
    contains the index at which the ``Bit`` can be found (in either
    :obj:`~QuantumCircuit.qubits`, :obj:`~QuantumCircuit.clbits`, depending on its
    type). The second element (``registers``) is a list of ``(register, index)``
    pairs with an entry for each :obj:`~Register` in the circuit which contains the
    :obj:`~Bit` (and the index in the :obj:`~Register` at which it can be found).

Raises:
    CircuitError: If the supplied :obj:`~Bit` was of an unknown type.
    CircuitError: If the supplied :obj:`~Bit` could not be found on the circuit.

Examples:
    Loop through a circuit, getting the qubit and clbit indices of each operation::

        from qiskit.circuit import QuantumCircuit, Qubit

        qc = QuantumCircuit(3, 3)
        qc.h(0)
        qc.cx(0, 1)
        qc.cx(1, 2)
        qc.measure([0, 1, 2], [0, 1, 2])

        # The `.qubits` and `.clbits` fields are not integers.
        assert isinstance(qc.data[0].qubits[0], Qubit)
        # ... but we can use `find_bit` to retrieve them.
        assert qc.find_bit(qc.data[0].qubits[0]).index == 0

        simple = [
            (
                instruction.operation.name,
                [qc.find_bit(bit).index for bit in instruction.qubits],
                [qc.find_bit(bit).index for bit in instruction.clbits],
            )
            for instruction in qc.data
        ]
z&Could not locate bit of unknown type: zCould not locate provided bit: z*. Has it been added to the QuantumCircuit?N)	r[   r    ry   r  r#   r  r   rm   ra  )r   r  errs      r`   r)  QuantumCircuit.find_bit0  s    f
	#u%%zz0055C''zz0055"%KDQTI;#WXX 	1#6`a	s"   -A5 -A5 A5 5
B?BBc                0    [         R                  " U5        g)z6Raise exception if list of qubits contains duplicates.N)r   r3  r   r   s     r`   r3  QuantumCircuit._check_dupso  s    'r   c                    SSK Jn  U" XUS9$ )a*  Create an :class:`~.circuit.Instruction` out of this circuit.

.. seealso::
    :func:`circuit_to_instruction`
        The underlying driver of this method.

Args:
    parameter_map: For parameterized circuits, a mapping from
       parameters in the circuit to parameters to be used in the
       instruction. If None, existing circuit parameters will also
       parameterize the instruction.
    label: Optional gate label.

Returns:
    qiskit.circuit.Instruction: a composite instruction encapsulating this circuit (can be
        decomposed back).
r   )circuit_to_instructionr-  )(qiskit.converters.circuit_to_instructionr  )r   parameter_maprR  r  s       r`   r:  QuantumCircuit.to_instructions  s    . 	T%dGGr   c                    SSK Jn  U" XUS9$ )a)  Create a :class:`.Gate` out of this circuit.  The circuit must act only on qubits and
contain only unitary operations.

.. seealso::
    :func:`circuit_to_gate`
        The underlying driver of this method.

Args:
    parameter_map: For parameterized circuits, a mapping from parameters in the circuit to
        parameters to be used in the gate. If ``None``, existing circuit parameters will
        also parameterize the gate.
    label : Optional gate label.

Returns:
    Gate: a composite gate encapsulating this circuit (can be decomposed back).
r   )circuit_to_gater-  )!qiskit.converters.circuit_to_gater  )r   r  rR  r  s       r`   r9  QuantumCircuit.to_gate  s    , 	Ft%@@r   c                    SSK Jn  SSKJn  SSKJn  U" U SS9nU" USS9n[        U5       H  nUR                  U5      nM     U" USS9$ )	a  Call a decomposition pass on this circuit, to decompose one level (shallow decompose).

Args:
    gates_to_decompose: Optional subset of gates to decompose. Can be a gate type, such as
        ``HGate``, or a gate name, such as "h", or a gate label, such as "My H Gate", or a
        list of any combination of these. If a gate name is entered, it will decompose all
        gates with that name, whether the gates have labels or not. Defaults to all gates in
        the circuit.
    reps: Optional number of times the circuit should be decomposed.
        For instance, ``reps=2`` equals calling ``circuit.decompose().decompose()``.

Returns:
    QuantumCircuit: a circuit one level decomposed
r   )	Decomposer   )dag_to_circuitTr   )apply_synthesisF)(qiskit.transpiler.passes.basis.decomposer   qiskit.converters.circuit_to_dagr    qiskit.converters.dag_to_circuitr  r;  run)	r   gates_to_decomposer=  r  r   r  dagpass_r  s	            r`   	decomposeQuantumCircuit.decompose  sQ    , 	GCCT48,dCtA))C.C  c599r   c                    SSK Jn  U" U 40 SU_SU_SU_SU_SU_SU_S	U_S
U_SU	_SU
_SU_SU_SU_SU_SU_SU_SU_SU_6$ )a  Draw the quantum circuit. Use the output parameter to choose the drawing format:

**text**: ASCII art TextDrawing that can be printed in the console.

**mpl**: images with color rendered purely in Python using matplotlib.

**latex**: high-quality images compiled via latex.

**latex_source**: raw uncompiled latex output.

.. warning::

    Support for :class:`~.expr.Expr` nodes in conditions and :attr:`.SwitchCaseOp.target`
    fields is preliminary and incomplete.  The ``text`` and ``mpl`` drawers will make a
    best-effort attempt to show data dependencies, but the LaTeX-based drawers will skip
    these completely.

Args:
    output: Select the output method to use for drawing the circuit.
        Valid choices are ``text``, ``mpl``, ``latex``, ``latex_source``.
        By default, the ``text`` drawer is used unless the user config file
        (usually ``~/.qiskit/settings.conf``) has an alternative backend set
        as the default. For example, ``circuit_drawer = latex``. If the output
        kwarg is set, that backend will always be used over the default in
        the user config file.
    scale: Scale of image to draw (shrink if ``< 1.0``). Only used by
        the ``mpl``, ``latex`` and ``latex_source`` outputs. Defaults to ``1.0``.
    filename: File path to save image to. Defaults to ``None`` (result not saved in a file).
    style: Style name, file name of style JSON file, or a dictionary specifying the style.

        * The supported style names are ``"iqp"`` (default), ``"iqp-dark"``, ``"clifford"``,
          ``"textbook"`` and ``"bw"``.
        * If given a JSON file, e.g. ``my_style.json`` or ``my_style`` (the ``.json``
          extension may be omitted), this function attempts to load the style dictionary
          from that location. Note, that the JSON file must completely specify the
          visualization specifications. The file is searched for in
          ``qiskit/visualization/circuit/styles``, the current working directory, and
          the location specified in ``~/.qiskit/settings.conf``.
        * If a dictionary, every entry overrides the default configuration. If the
          ``"name"`` key is given, the default configuration is given by that style.
          For example, ``{"name": "textbook", "subfontsize": 5}`` loads the ``"texbook"``
          style and sets the subfontsize (e.g. the gate angles) to ``5``.
        * If ``None`` the default style ``"iqp"`` is used or, if given, the default style
          specified in ``~/.qiskit/settings.conf``.

    interactive: When set to ``True``, show the circuit in a new window
        (for ``mpl`` this depends on the matplotlib backend being used
        supporting this). Note when used with either the `text` or the
        ``latex_source`` output type this has no effect and will be silently
        ignored. Defaults to ``False``.
    reverse_bits: When set to ``True``, reverse the bit order inside
        registers for the output visualization. Defaults to ``False`` unless the
        user config file (usually ``~/.qiskit/settings.conf``) has an
        alternative value set. For example, ``circuit_reverse_bits = True``.
    plot_barriers: Enable/disable drawing barriers in the output
        circuit. Defaults to ``True``.
    justify: Options are ``"left"``, ``"right"`` or ``"none"`` (str).
        If anything else is supplied, left justified will be used instead.
        It refers to where gates should be placed in the output circuit if
        there is an option. ``none`` results in each gate being placed in
        its own column. Defaults to ``left``.
    vertical_compression: ``high``, ``medium`` or ``low``. It
        merges the lines generated by the `text` output so the drawing
        will take less vertical room.  Default is ``medium``. Only used by
        the ``text`` output, will be silently ignored otherwise.
    idle_wires: Include (or not) idle wires (wires with no circuit elements)
        in output visualization. The string ``"auto"`` is also possible, in which
        case idle wires are show except that the circuit has a layout attached.
        Default is ``"auto"`` unless the
        user config file (usually ``~/.qiskit/settings.conf``) has an
        alternative value set. For example, ``circuit_idle_wires = False``.
    with_layout: Include layout information, with labels on the
        physical layout. Default is ``True``.
    fold: Sets pagination. It can be disabled using -1. In ``text``,
        sets the length of the lines. This is useful when the drawing does
        not fit in the console. If None (default), it will try to guess the
        console width using ``shutil.get_terminal_size()``. However, if
        running in jupyter, the default line length is set to 80 characters.
        In ``mpl``, it is the number of (visual) layers before folding.
        Default is 25.
    ax: Only used by the `mpl` backend. An optional ``matplotlib.axes.Axes``
        object to be used for the visualization output. If none is
        specified, a new matplotlib Figure will be created and used.
        Additionally, if specified there will be no returned Figure since
        it is redundant.
    initial_state: Adds :math:`|0\rangle` in the beginning of the qubit wires and
        :math:`0` to classical wires. Default is ``False``.
    cregbundle: If set to ``True``, bundle classical registers.
        Default is ``True``, except for when ``output`` is set to  ``"text"``.
    wire_order: A list of integers used to reorder the display
        of the bits. The list must have an entry for every bit with the bits
        in the range 0 to (``num_qubits`` + ``num_clbits``).
    expr_len: The number of characters to display if an :class:`~.expr.Expr`
        is used for the condition in a :class:`.ControlFlowOp`. If this number is exceeded,
        the string will be truncated at that number and '...' added to the end.
    measure_arrows: If True, draw an arrow from each measure box down the the classical bit
        or register where the measure value is placed. If False, do not draw arrow, but
        instead place the name of the bit or register in the measure box.
        Default is ``True`` unless the user config file (usually ``~/.qiskit/settings.conf``)
        has an alternative value set. For example, ``circuit_measure_arrows = False``.

Returns:
    :class:`.TextDrawing` or :class:`matplotlib.figure` or :class:`PIL.Image` or
    :class:`str`:

    * ``TextDrawing`` (if ``output='text'``)
        A drawing that can be printed as ascii art.
    * ``matplotlib.figure.Figure`` (if ``output='mpl'``)
        A matplotlib figure object for the circuit diagram.
    * ``PIL.Image`` (if ``output='latex``')
        An in-memory representation of the image of the circuit diagram.
    * ``str`` (if ``output='latex_source'``)
        The LaTeX source code for visualizing the circuit diagram.

Raises:
    VisualizationError: when an invalid output method is selected
    ImportError: when the output methods requires non-installed libraries.

Example:
    .. plot::
       :alt: Circuit diagram output by the previous code.
       :include-source:

       from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
       qc = QuantumCircuit(1, 1)
       qc.h(0)
       qc.measure(0, 0)
       qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
r   )circuit_drawerscalefilenamestyler   interactiveplot_barriersr.  justifyvertical_compression
idle_wireswith_layoutfoldaxinitial_state
cregbundle
wire_orderexpr_lenmeasure_arrows)qiskit.visualizationr  )r   r   r  r  r  r  r  r.  r  r  r  r  r  r  r  r  r  r  r  r  s                       r`   r   QuantumCircuit.draw  s    t 	8

 
 	

 
 $
 (
 &
 
 "6
 "
 $
 
 
 (
  "!
" "#
$ %
& *'
 	
r   c                :    [        U R                  SS5      (       + $ N
_directiveFrC  r  xs    r`   <lambda>QuantumCircuit.<lambda>  s    GKKu=
 9
r   c                >    [        [        XR                  5      5      $ )aT  Returns total number of instructions in circuit.

Args:
    filter_function (callable): a function to filter out some instructions.
        Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)).
        By default, filters out "directives", such as barrier or snapshot.

Returns:
    int: Total number of gate operations.
)summapry   )r   filter_functions     r`   sizeQuantumCircuit.size}  s      3

344r   c                :    [        U R                  SS5      (       + $ r  r  r  s    r`   r  r    s    gKKuO
 K
r   c                X  ^ U R                   U R                  U R                  5       4 VVs0 s H  o"  H  o3S_M     M     snnmS nU R                   GH  n[	        [
        R                  " UR                   UR                  5      5      n[        UR                  SS5      =nb  UR                  [        R                  " U5      R                  5        [        U[        R                  5      (       a	  U" X&5        OUR                  [        R                  " U5      R                  5        O[        UR                  [        5      (       a2  U" U[        R                   " UR                  R"                  5      5        OW[        UR                  [$        5      (       a8  U" X%R                  R&                  5        U" X%R                  R(                  5        [+        U4S jU 5       SS9nU" U5      (       a  US-  nU H  nUTU'   M
     GM     [+        TR-                  5       SS9$ s  snnf )a  Return circuit depth (i.e., length of critical path).

The depth of a quantum circuit is a measure of how many
"layers" of quantum gates, executed in parallel, it takes to
complete the computation defined by the circuit.  Because
quantum gates take time to implement, the depth of a circuit
roughly corresponds to the amount of time it takes the quantum
computer to execute the circuit.


.. warning::
    This operation is not well defined if the circuit contains control-flow operations.

Args:
    filter_function: A function to decide which instructions count to increase depth.
        Should take as a single positional input a :class:`CircuitInstruction`.
        Instructions for which the function returns ``False`` are ignored in the
        computation of the circuit depth.  By default, filters out "directives", such as
        :class:`.Barrier`.

Returns:
    int: Depth of circuit.

Examples:
    Simple calculation of total circuit depth::

        from qiskit.circuit import QuantumCircuit
        qc = QuantumCircuit(4)
        qc.h(0)
        qc.cx(0, 1)
        qc.h(2)
        qc.cx(2, 3)
        assert qc.depth() == 2

    Modifying the previous example to only calculate the depth of multi-qubit gates::

        assert qc.depth(lambda instr: len(instr.qubits) > 1) == 1
r   c                    [         R                  " U5       HV  nUR                  (       a  U R                  U5        M'  U R	                  [
        R                  " U5      R                  5        MX     g rZ   )r9   r  r  addr   r(   node_resourcesr   )objectsnoder   s      r`   update_from_expr.QuantumCircuit.depth.<locals>.update_from_expr  sE    ~~d+>>KK$NN>#@#@#E#L#LM	 ,r   r|  Nc              3  .   >#    U  H
  nTU   v   M     g 7frZ   rQ   )r^   obj
obj_depthss     r`   ra   'QuantumCircuit.depth.<locals>.<genexpr>  s     @Z_s   r  r   )r   r   r  ry   r   r  r  rC  r  r   r(   condition_resourcesr[   r9   rD  r5   r  r  rD   r  r  maxvalues)	r   r  r  r	  r  r   r}  	new_depthr
  s	           @r`   depthQuantumCircuit.depth  s   Z $(;;T^^=M"N
"NwZaSVFZaC"N

	N  ::K)//+*<*<k>P>PQRG$[%:%:L$OO	\~AA)LSSTi33$W8NN>#E#Ei#P#W#WXK11<@@ $))K4I4I4P4P*QRK11599 *?*?*F*FG *?*?*F*FG
 @@!LI{++Q	"+
3 ) &, :$$&22C
s   H&c                6    U R                   R                  5       $ )zVReturn number of qubits plus clbits in circuit.

Returns:
    int: Width of circuit.

)ry   widthr   s    r`   r  QuantumCircuit.width  s     zz!!r   c                .    U R                   R                  $ )zReturn number of qubits.)ry   r  r   s    r`   r  QuantumCircuit.num_qubits  s     zz$$$r   c                ,    [        U R                  5      $ )a;  Return the number of ancilla qubits.

Example:

    .. plot::
        :include-source:
        :nofigs:

        from qiskit import QuantumCircuit, QuantumRegister, AncillaRegister

        # Create a 2-qubit quantum circuit
        reg = QuantumRegister(2)
        qc = QuantumCircuit(reg)

        # Create an ancilla register with 1 qubit
        anc = AncillaRegister(1)
        qc.add_register(anc)  # Add the ancilla register to the circuit

        print("Number of ancilla qubits:", qc.num_ancillas)

    .. code-block:: text

        Number of ancilla qubits: 1
)r  r  r   s    r`   num_ancillasQuantumCircuit.num_ancillas  s    4 4==!!r   c                .    U R                   R                  $ )ar  Return number of classical bits.

Example:

    .. plot::
        :include-source:
        :nofigs:

        from qiskit import QuantumCircuit

        # Create a new circuit with two qubits and one classical bit
        qc = QuantumCircuit(2, 1)
        print("Number of classical bits:", qc.num_clbits)

    .. code-block:: text

        Number of classical bits: 1


)ry   r  r   s    r`   r  QuantumCircuit.num_clbits  s    , zz$$$r   c                L    U R                   R                  5       n[        U5      $ )zCount each operation kind in the circuit.

Returns:
    OrderedDict: a breakdown of how many operations of each kind, sorted by amount.
)ry   	count_opsr   )r   ops_dicts     r`   r  QuantumCircuit.count_ops#  s!     ::'')8$$r   c                6    U R                   R                  5       $ )zlReturn number of non-local gates (i.e. involving 2+ qubits).

Conditional nonlocal gates are also included.
)ry   num_nonlocal_gatesr   s    r`   r!  !QuantumCircuit.num_nonlocal_gates,  s    
 zz,,..r   c                |    U R                    Vs/ s H   o"R                  R                  U:X  d  M  UPM"     sn$ s  snf )zGet instructions matching name.

Args:
    name (str): The name of instruction to.

Returns:
    list(tuple): list of (instruction, qargs, cargs).
)ry   r  rR   )r   rR   matchs      r`   get_instructionsQuantumCircuit.get_instructions3  s/     $(::N:%1E1E1M:NNNs   99c                   U(       a  U R                   OU R                   U R                  -   n[        U5       VVs0 s H  u  p4XC_M	     nnn[        [	        U5      5       Vs/ s H  oD/PM     nn[	        U5      nU R
                   GHC  nU(       a  UR                   n	[	        U	5      n
O$UR                   UR                  -   n	[	        U	5      n
U
S:  a  [        UR                  SS5      (       d  / nSnU	 H<  nX]   n[        U5       H&  nXU   ;   d  M  X;  d  M  UR                  U5          M:     M>     [        [        U5      5      n[	        U5      nUS:  af  / nU H  nUR                  Xc   5        M     / n[        U5       H  nX;;  d  M
  UR                  Xc   5        M     UR                  U5        UnX|S-
  -  nUS:X  d  GMC    U$    U$ s  snnf s  snf )zHow many non-entangled subcircuits can the circuit be factored to.

Args:
    unitary_only (bool): Compute only unitary part of graph.

Returns:
    int: Number of connected components in circuit.
r  r  Fr   r   )r   r   r  r;  r  ry   rC  r  r   r\   r   r  )r   unitary_onlyr'  rV  r  bit_indices
sub_graphsnum_sub_graphsr   args	num_qargsgraphs_touchednum_touchedr  reg_intr   connections_sub_graphss                     r`   num_connected_components'QuantumCircuit.num_connected_components>  s    +t{{t{{1JJSTX/0Z/hc/0Z (-S-='>?'>e'>
?Z  ::K"))I	"))K,>,>>I	A~gk.C.C\SX&Y&Y!# !D)/G">2"m3 6 . 5 5a 8 %	 3 ! "&c.&9!:!.1
 ?"$K-#**:?;  ."$K$^44'..z?  5  &&{3!,J"Ao5N"S &R e 1[ @s   G"Gc                     U R                  SS9$ )zYComputes the number of tensor factors in the unitary
(quantum) part of the circuit only.
T)r(  )r3  r   s    r`   num_unitary_factors"QuantumCircuit.num_unitary_factors}  s     ,,$,??r   c                "    U R                  5       $ )zComputes the number of tensor factors in the unitary
(quantum) part of the circuit only.

Notes:
    This is here for backwards compatibility, and will be
    removed in a future release of Qiskit. You should call
    `num_unitary_factors` instead.
)r6  r   s    r`   num_tensor_factors!QuantumCircuit.num_tensor_factors  s     ''))r   c                d    U R                  USS9nU R                  R                  5       Ul        U$ )zCopy the circuit.

Args:
  name (str): name to be given to the copied circuit. If None, then the name stays the same.

Returns:
  QuantumCircuit: a deepcopy of the current circuit, with the specified name
rl  rm  )r  ry   r   )r   rR   cpys      r`   r   QuantumCircuit.copy  s0     ""46":JJOO%	
r   alikerm  c                   Ub$  [        U[        5      (       d  [        SU S35      e[        R                  " U 5      n[        X5        U R                  R                  US9Ul        U(       a  Xl        U$ )a  Return a copy of self with the same structure but empty.

That structure includes:

* name and other metadata
* global phase
* all the qubits and clbits, including the registers
* the realtime variables defined in the circuit, handled according to the ``vars`` keyword
  argument.

.. warning::

    If the circuit contains any local variable declarations (those added by the
    ``declarations`` argument to the circuit constructor, or using :meth:`add_var`), they
    may be **uninitialized** in the output circuit.  You will need to manually add store
    instructions for them (see :class:`.Store` and :meth:`.QuantumCircuit.store`) to
    initialize them.

Args:
    name: Name for the copied circuit. If None, then the name stays the same.
    vars_mode: The mode to handle realtime variables in.

        alike
            The variables in the output circuit will have the same declaration semantics as
            in the original circuit.  For example, ``input`` variables in the source will be
            ``input`` variables in the output circuit.
            Note that this causes the local variables to be uninitialised, because the stores are
            not copied.  This can leave the circuit in a potentially dangerous state for users if
            they don't re-add initializer stores.

        captures
            All variables will be converted to captured variables.  This is useful when you
            are building a new layer for an existing circuit that you will want to
            :meth:`compose` onto the base, since :meth:`compose` can inline captures onto
            the base circuit (but not other variables).

        drop
            The output circuit will have no variables defined.

Returns:
    QuantumCircuit: An empty copy of self.
zinvalid name for a circuit: 'z''. The name must be a string or 'None'.rm  )	r[   rs   rl   r   r   _copy_metadatary   r  rR   )r   rR   rn  r<  s       r`   r  QuantumCircuit.copy_empty_like  sn    ` 
4 5 5/v5\]  jjt!JJ...C	H
r   c                Z    U R                   R                  5         U R                  U l        g)a*  Clear all instructions in self.

Clearing the circuits will keep the metadata.

.. seealso::
    :meth:`copy_empty_like`
        A method to produce a new circuit with no instructions and all the same tracking of
        quantum and classical typed data, but without mutating the original circuit.
N)ry   r   rS   r   s    r`   r   QuantumCircuit.clear  s"     	

 --r   c                    X R                    Vs/ s H  o3R                  PM     sn;   a  [        R                  " X5      nU$ [        X5      nU$ s  snf )zCCreates a creg, checking if ClassicalRegister with same name exists)r   rR   r$   _new_with_prefix)r   lengthrR   cregnew_cregs        r`   _create_cregQuantumCircuit._create_creg  sJ    **5*$II*55(99&GH  )6H	 6   Ac                    X R                    Vs/ s H  o3R                  PM     sn;   a  [        R                  " X5      nU$ [        X5      nU$ s  snf )zACreates a qreg, checking if QuantumRegister with same name exists)r   rR   r   rE  )r   rF  rR   qregnew_qregs        r`   _create_qregQuantumCircuit._create_qreg  sJ    **5*$II*55&77EH  'v4H	 6rK  c                >    SSK Jn  U R                  U" 5       U// SS9$ )zReset the quantum bit(s) to their default state.

Args:
    qubit: qubit(s) to reset.

Returns:
    qiskit.circuit.InstructionSet: handle to the added instruction.
r   )ResetFr   )resetrR  r   )r   r   rR  s      r`   rS  QuantumCircuit.reset  s"     	!{{57UGRe{<<r   c                   [         R                  " U5      n[        U[        5      (       a!  [        U[        5      (       d  UR
                  OSn[         R                  " X#5      nU R                  [        X5      SSSS9$ )a)  Store the result of the given real-time classical expression ``rvalue`` in the memory
location defined by ``lvalue``.

Typically ``lvalue`` will be a :class:`~.expr.Var` node and ``rvalue`` will be some
:class:`~.expr.Expr` to write into it, but anything that :func:`.expr.lift` can raise to an
:class:`~.expr.Expr` is permissible in both places, and it will be called on them.

Args:
    lvalue: a valid specifier for a memory location in the circuit.  This will typically be
        a :class:`~.expr.Var` node, but you can also write to :class:`.Clbit` or
        :class:`.ClassicalRegister` memory locations if your hardware supports it.  The
        memory location must already be present in the circuit.
    rvalue: a real-time classical expression whose result should be written into the given
        memory location.

.. seealso::
    :class:`~.circuit.Store`
        The backing :class:`~.circuit.Instruction` class that represents this operation.

    :meth:`add_var`
        Create a new variable in the circuit that can be written to with this method.
NrQ   Fr   )r9   r  r[   re   r  rm   r   rD   )r   r  r  rvalue_types       r`   r  QuantumCircuit.store  se    0 6"%fc22:fd;S;SFKKY] 	 6/{{50"bu{EEr   c                @    SSK Jn  U R                  U" 5       U/U/SS9$ )ue	  Measure a quantum bit (``qubit``) in the Z basis into a classical bit (``cbit``).

When a quantum state is measured, a qubit is projected in the computational (Pauli Z) basis
to either :math:`\lvert 0 \rangle` or :math:`\lvert 1 \rangle`. The classical bit ``cbit``
indicates the result
of that projection as a ``0`` or a ``1`` respectively. This operation is non-reversible.

Args:
    qubit: qubit(s) to measure.
    cbit: classical bit(s) to place the measurement result(s) in.

Returns:
    qiskit.circuit.InstructionSet: handle to the added instructions.

Raises:
    CircuitError: if arguments have bad format.

Examples:
    In this example, a qubit is measured and the result of that measurement is stored in the
    classical bit (usually expressed in diagrams as a double line):

    .. plot::
       :include-source:
       :nofigs:
       :context: reset

       from qiskit import QuantumCircuit
       circuit = QuantumCircuit(1, 1)
       circuit.h(0)
       circuit.measure(0, 0)
       circuit.draw()


    .. code-block:: text

              ┌───┐┌─┐
           q: ┤ H ├┤M├
              └───┘└╥┘
         c: 1/══════╩═
                    0

    It is possible to call ``measure`` with lists of ``qubits`` and ``cbits`` as a shortcut
    for one-to-one measurement. These two forms produce identical results:

    .. plot::
       :include-source:
       :nofigs:
       :context:

       circuit = QuantumCircuit(2, 2)
       circuit.measure([0,1], [0,1])

    .. plot::
       :include-source:
       :nofigs:
       :context:

       circuit = QuantumCircuit(2, 2)
       circuit.measure(0, 0)
       circuit.measure(1, 1)

    Instead of lists, you can use :class:`~qiskit.circuit.QuantumRegister` and
    :class:`~qiskit.circuit.ClassicalRegister` under the same logic.

    .. plot::
       :include-source:
       :nofigs:
       :context: reset

        from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
        qreg = QuantumRegister(2, "qreg")
        creg = ClassicalRegister(2, "creg")
        circuit = QuantumCircuit(qreg, creg)
        circuit.measure(qreg, creg)

    This is equivalent to:

    .. plot::
       :include-source:
       :nofigs:
       :context:

        circuit = QuantumCircuit(qreg, creg)
        circuit.measure(qreg[0], creg[0])
        circuit.measure(qreg[1], creg[1])

r   )MeasureFr   )measurerY  r   )r   r   cbitrY  s       r`   rZ  QuantumCircuit.measure&  s%    p 	%{{79ugvE{BBr   c                l   SSK Jn  U(       a  U nOU R                  5       nU" U5      nUR                   Vs/ s H  oUUR	                  5       ;  d  M  UPM     nnUR                  [        U5      S5      nUR                  U5        UR                  5         UR                  Xg5        U(       d  U$ gs  snf )an  Adds measurement to all non-idle qubits. Creates a new ClassicalRegister with
a size equal to the number of non-idle qubits being measured.

Returns a new circuit with measurements if `inplace=False`.

Args:
    inplace (bool): All measurements inplace or return new circuit.

Returns:
    QuantumCircuit: Returns circuit with measurements when ``inplace = False``.
r   r   r  N)
r  r   r   r   r  rI  r  r{   r<  rZ  )r   r  r   r+  r  r   qubits_to_measurerH  s           r`   measure_activeQuantumCircuit.measure_active  s     	DD99;DT"04]uCNNL\?\U]$$S):%;VD(#&1K ^s   B1B1c                   U(       a  U nOU R                  5       nU(       aZ  UR                  UR                  S5      nUR                  U5        UR	                  5         UR                  UR                  U5        OhUR                  UR                  :  a  [        S5      eUR	                  5         UR                  UR                  UR                  SUR                   5        U(       d  U$ g)a  Adds measurement to all qubits.

By default, adds new classical bits in a :obj:`.ClassicalRegister` to store these
measurements.  If ``add_bits=False``, the results of the measurements will instead be stored
in the already existing classical bits, with qubit ``n`` being measured into classical bit
``n``.

Returns a new circuit with measurements if ``inplace=False``.

Args:
    inplace (bool): All measurements inplace or return new circuit.
    add_bits (bool): Whether to add new bits to store the results.

Returns:
    QuantumCircuit: Returns circuit with measurements when ``inplace=False``.

Raises:
    CircuitError: if ``add_bits=False`` but there are not enough classical bits.
r  zPThe number of classical bits must be equal or greater than the number of qubits.r   N)
r   rI  r  r{   r<  rZ  r   r  r   r   )r   r  r   r+  rH  s        r`   measure_allQuantumCircuit.measure_all  s    , D99;D((&AHh'LLNLLh/0",  LLNLLdkk!doo&FGKr   c                   SSK Jn  SSKJn  U(       a  U nOU R	                  5       nU" U5      nU" 5       nUR                  U5      n[        UR                  R                  5       5      n[        UR                  5      n	UR                   V
s/ s H  oU;   d  M
  U
PM     nn
UR                  R                   Vs/ s H  oU	;   d  M
  UPM     nnUR                  n[        UR                  R                  [        UR                  5      UR                  S9Ul
        U H  nUR!                  U5        M     UR#                  U5        U H  n
UR!                  U
5        M     UR%                  5        HD  nUR&                  R	                  5       nUR)                  UUR*                  UR,                  5        MF     U(       d  U$ gs  sn
f s  snf )a  Removes final measurements and barriers on all qubits if they are present.
Deletes the classical registers that were used to store the values from these measurements
that become idle as a result of this operation, and deletes classical bits that are
referenced only by removed registers, or that aren't referenced at all but have
become idle as a result of this operation.

Measurements and barriers are considered final if they are
followed by no other operations (aside from other measurements or barriers.)

.. note::
    This method has rather complex behavior, particularly around the removal of newly idle
    classical bits and registers.  It is much more efficient to avoid adding unnecessary
    classical data in the first place, rather than trying to remove it later.

.. seealso::
    :class:`.RemoveFinalMeasurements`
        A transpiler pass that removes final measurements and barriers.  This does not
        remove the classical data.  If this is your goal, you can call that with::

            from qiskit.circuit import QuantumCircuit
            from qiskit.transpiler.passes import RemoveFinalMeasurements

            qc = QuantumCircuit(2, 2)
            qc.h(0)
            qc.cx(0, 1)
            qc.barrier()
            qc.measure([0, 1], [0, 1])

            pass_ = RemoveFinalMeasurements()
            just_bell = pass_(qc)

Args:
    inplace (bool): All measurements removed inplace or return new circuit.

Returns:
    QuantumCircuit: Returns the resulting circuit when ``inplace=False``, else None.
r   )RemoveFinalMeasurementsr   )r   reserverS   N)qiskit.transpiler.passesre  r   r   r   r  r   r   r  r   ry   r   r   r   r  rS   r{   r   topological_op_nodesr  r   r   r   )r   r  re  r   r+  r  remove_final_measnew_dag
kept_cregskept_clbitsrG  cregs_to_addr   clbits_to_add	old_qregsrM  r  r?  s                     r`   remove_final_measurements(QuantumCircuit.remove_final_measurements  su   N 	E4D99;DT"35#'',--/0
'..) *.Jz7IJ,0JJ,=,=V,=5+AU,=V JJ	 !::$$c$**oDL]L]


 Dd#  	m$ Dd# ! 002D77<<>DKKdjj$**5 3
 K? KVs   	GG:	GGc                p    SSK Jn  UR                  U UR                  UR                  UR
                  SS9$ )aG  Read an OpenQASM 2.0 program from a file and convert to an instance of
:class:`.QuantumCircuit`.

Args:
  path (str): Path to the file for an OpenQASM 2 program

Return:
  QuantumCircuit: The QuantumCircuit object for the input OpenQASM 2.

See also:
    :func:`.qasm2.load`: the complete interface to the OpenQASM 2 importer.
r   qasm2Finclude_pathcustom_instructionscustom_classicalstrict)qiskitrt  loadLEGACY_INCLUDE_PATHLEGACY_CUSTOM_INSTRUCTIONSLEGACY_CUSTOM_CLASSICAL)pathrt  s     r`   from_qasm_fileQuantumCircuit.from_qasm_file%  s>     	!zz22 % @ @"::  
 	
r   c                p    SSK Jn  UR                  U UR                  UR                  UR
                  SS9$ )a>  Convert a string containing an OpenQASM 2.0 program to a :class:`.QuantumCircuit`.

Args:
  qasm_str (str): A string containing an OpenQASM 2.0 program.
Return:
  QuantumCircuit: The QuantumCircuit object for the input OpenQASM 2

See also:
    :func:`.qasm2.loads`: the complete interface to the OpenQASM 2 importer.
r   rs  Fru  )rz  rt  loadsr|  r}  r~  )qasm_strrt  s     r`   from_qasm_strQuantumCircuit.from_qasm_str>  s>     	!{{22 % @ @"::  
 	
r   c                    U R                   (       a  U R                   S   R                  $ U R                  R                  $ )aF  The global phase of the current circuit scope in radians.

Example:

    .. plot::
        :include-source:
        :nofigs:
        :context: reset

        from qiskit import QuantumCircuit

        circuit = QuantumCircuit(2)
        circuit.h(0)
        circuit.cx(0, 1)
        print(circuit.global_phase)

    .. code-block:: text

        0.0

    .. plot::
        :include-source:
        :nofigs:
        :context:

        from numpy import pi

        circuit.global_phase = pi/4
        print(circuit.global_phase)

    .. code-block:: text

        0.7853981633974483
r&  rx   rS   ry   r   s    r`   rS   QuantumCircuit.global_phaseU  s5    J $$,,R0===zz&&&r   c                n    U R                   (       a  XR                   S   l        gXR                  l        g)zcSet the phase of the current circuit scope.

Args:
    angle (float, ParameterExpression): radians
r&  Nr  )r   angles     r`   rS   r  ~  s(     $$9>%%b)6&+JJ#r   c                @    [        U R                  R                  5      $ )u	  The parameters defined in the circuit.

This attribute returns the :class:`.Parameter` objects in the circuit sorted
alphabetically. Note that parameters instantiated with a :class:`.ParameterVector`
are still sorted numerically.

Examples:

    The snippet below shows that insertion order of parameters does not matter.

    .. plot::
       :include-source:
       :nofigs:

        >>> from qiskit.circuit import QuantumCircuit, Parameter
        >>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
        >>> circuit = QuantumCircuit(1)
        >>> circuit.rx(b, 0)
        >>> circuit.rz(elephant, 0)
        >>> circuit.ry(a, 0)
        >>> circuit.parameters  # sorted alphabetically!
        ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])

    Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers.
    The literal "10" comes before "2" in strict alphabetical sorting.

    .. plot::
       :include-source:
       :nofigs:

        >>> from qiskit.circuit import QuantumCircuit, Parameter
        >>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
        >>> circuit = QuantumCircuit(1)
        >>> circuit.u(*angles, 0)
        >>> circuit.draw()
           ┌─────────────────────────────┐
        q: ┤ U(angle_1,angle_2,angle_10) ├
           └─────────────────────────────┘
        >>> circuit.parameters
        ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])

    To respect numerical sorting, a :class:`.ParameterVector` can be used.

    .. plot::
       :include-source:
       :nofigs:

        >>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
        >>> x = ParameterVector("x", 12)
        >>> circuit = QuantumCircuit(1)
        >>> for x_i in x:
        ...     circuit.rx(x_i, 0)
        >>> circuit.parameters
        ParameterView([
            ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
            ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
            ..., ParameterVectorElement(x[11])
        ])


Returns:
    The sorted :class:`.Parameter` objects in the circuit.
)r=   ry   rG  r   s    r`   rG  QuantumCircuit.parameters  s    D TZZ2233r   c                6    U R                   R                  5       $ )z/The number of parameter objects in the circuit.)ry   rF  r   s    r`   rF  QuantumCircuit.num_parameters  s     zz((**r   c                6    U R                   R                  5       $ )a6  Efficiently get all parameters in the circuit, without any sorting overhead.

.. warning::

    The returned object may directly view onto the ``ParameterTable`` internals, and so
    should not be mutated.  This is an internal performance detail.  Code outside of this
    package should not use this method.
)ry   unsorted_parametersr   s    r`   _unsorted_parameters#QuantumCircuit._unsorted_parameters  s     zz--//r   )
flat_inputry  c                   g rZ   rQ   r   rG  r  r  ry  s        r`   assign_parameters QuantumCircuit.assign_parameters  s     r   c                   g rZ   rQ   r  s        r`   r  r    s     r   c                  U(       a  U nO[[        U[        5      (       d  U R                  R                  nU R	                  5       nUR                  5         UR                  5         [        U[        R                  R                  5      (       a  U(       a  UOU R                  X5      nU(       aV  U Vs/ s H  oR                  U5      (       a  M  UPM     sn=n	(       a%  [        SSR                  S U	 5       5       S35      eUR                  R                  U5        OUR                  R                  U5        U(       a  S$ U$ s  snf )aO  Assign parameters to new parameters or values.

If ``parameters`` is passed as a dictionary, the keys should be :class:`.Parameter`
instances in the current circuit. The values of the dictionary can either be numeric values
or new parameter objects.

If ``parameters`` is passed as a list or array, the elements are assigned to the
current parameters in the order of :attr:`parameters` which is sorted
alphabetically (while respecting the ordering in :class:`.ParameterVector` objects).

The values can be assigned to the current circuit object or to a copy of it.

.. note::
    When ``parameters`` is given as a mapping, it is permissible to have keys that are
    strings of the parameter names; these will be looked up using :meth:`get_parameter`.
    You can also have keys that are :class:`.ParameterVector` instances, and in this case,
    the dictionary value should be a sequence of values of the same length as the vector.

    If you use either of these cases, you must leave the setting ``flat_input=False``;
    changing this to ``True`` enables the fast path, where all keys must be
    :class:`.Parameter` instances.

Args:
    parameters: Either a dictionary or iterable specifying the new parameter values.
    inplace: If False, a copy of the circuit with the bound parameters is returned.
        If True the circuit instance itself is modified.
    flat_input: If ``True`` and ``parameters`` is a mapping type, it is assumed to be
        exactly a mapping of ``{parameter: value}``.  By default (``False``), the mapping
        may also contain :class:`.ParameterVector` keys that point to a corresponding
        sequence of values, and these will be unrolled during the mapping, or string keys,
        which will be converted to :class:`.Parameter` instances using
        :meth:`get_parameter`.
    strict: If ``False``, any parameters given in the mapping that are not used in the
        circuit will be ignored.  If ``True`` (the default), an error will be raised
        indicating a logic error.

Raises:
    CircuitError: If parameters is a dict and contains parameters not present in the
        circuit.
    ValueError: If parameters is a list/array and the length mismatches the number of free
        parameters in the circuit.

Returns:
    A copy of the circuit with bound parameters if ``inplace`` is False, otherwise None.

Examples:

    Create a parameterized circuit and assign the parameters in-place.

    .. plot::
       :alt: Circuit diagram output by the previous code.
       :include-source:

       from qiskit.circuit import QuantumCircuit, Parameter

       circuit = QuantumCircuit(2)
       params = [Parameter('A'), Parameter('B'), Parameter('C')]
       circuit.ry(params[0], 0)
       circuit.crx(params[1], 0, 1)
       circuit.draw('mpl')
       circuit.assign_parameters({params[0]: params[2]}, inplace=True)
       circuit.draw('mpl')

    Bind the values out-of-place by list and get a copy of the original circuit.

    .. plot::
       :alt: Circuit diagram output by the previous code.
       :include-source:

       from qiskit.circuit import QuantumCircuit, ParameterVector

       circuit = QuantumCircuit(2)
       params = ParameterVector('P', 2)
       circuit.ry(params[0], 0)
       circuit.crx(params[1], 0, 1)

       bound_circuit = circuit.assign_parameters([1, 2])
       bound_circuit.draw('mpl')

       circuit.draw('mpl')

zCannot bind parameters (z, c              3  8   #    U  H  n[        U5      v   M     g 7frZ   )rs   )r^   r  s     r`   ra   3QuantumCircuit.assign_parameters.<locals>.<genexpr>b  s     8PAQrg   z) not present in the circuit.N)r[   r   ry   rG  r   rt   rr   collectionsabcr   _unroll_param_dictre  r   joinassign_parameters_mappingassign_parameters_iterable)
r   rG  r  r  ry  r  r  raw_mappingrb  extrass
             r`   r  r    s   t Fj$// JJ))YY[F'')!j+//"9"9::(2*8O8OPZ8cK/:/:)BTBTU^B_I{   #.tyy8P8P/P.Q R$ $ 
 LL22;?LL33J?t*F*s   4EEc                6    U R                   R                  5       $ )zeChecks whether the circuit has an instance of :class:`.ControlFlowOp`
present amongst its operations.)ry   has_control_flow_opr   s    r`   r  "QuantumCircuit.has_control_flow_opl  s     zz--//r   c                   0 nUR                  5        H  u  pE[        U[        5      (       ae  [        U5      [        U5      :w  a1  [	        SUR
                   S[        U5       S[        U5       S35      eUR                  [        XE5      5        M  [        U[        5      (       aP  U(       a  XSU R                  U5      '   U(       d-  U R                  U5      (       a  XSU R                  U5      '   M  M  M  XSU'   M     U$ )NzParameter vector 'z' has length z, but was assigned to z values.)r   r[   r>   r  r   rR   r   r  rs   rZ  re  )r   parameter_bindsry  r   rb  r   s         r`   r  !QuantumCircuit._unroll_param_dictq  s      / 5 5 7I)_55y>SZ/&,Y^^,<M#i.IY Z003E
|8E  

3y01Is++9>**956$"4"4Y"?"?9>**956 #@v "'I !8 
r   r-  c          	        SSK Jn  U(       a_  [        U VVs0 s H  o@R                  U5        H  oUS_M     M     snn5      nU R	                  [        U" [        U5      US9US5      SS9$ U R                  R                  5       nU R                  5       R	                  [        U" [        U5      US9US5      5      $ s  snnf )a2  Apply :class:`~.library.Barrier`. If ``qargs`` is empty, applies to all qubits
in the circuit.

Args:
    qargs (QubitSpecifier): Specification for one or more qubit arguments.
    label (str): The string label of the barrier.

Returns:
    qiskit.circuit.InstructionSet: handle to the added instructions.
r   )BarrierNr-  rQ   Fr   )
r<  r  ro   r  r   rB   r  r   r   r  )r   rR  r   r  r8  r  r   s          r`   r<  QuantumCircuit.barrier  s     	%%*YUT4R4RSW4XqD4XUYF ;;"73v;e#DfbQX]    [[%%'F&&(//"73v;e#DfbQ  Zs   $B?
c                T    Uc  U R                   nU R                  [        XS9U// SS9$ )aB  Apply :class:`~.circuit.Delay`. If qarg is ``None``, applies to all qubits.
When applying to multiple qubits, delays with the same duration will be created.

Args:
    duration (Object):
        duration of the delay. If this is an :class:`~.expr.Expr`, it must be
        a constant expression of type :class:`~.types.Duration`.
    qarg (Object): qubit argument to apply this delay.
    unit (str | None): unit of the duration, unless ``duration`` is an :class:`~.expr.Expr`
        in which case it must not be specified. Supported units: ``'s'``, ``'ms'``, ``'us'``,
        ``'ns'``, ``'ps'``, and ``'dt'``. Default is ``'dt'``, i.e. integer time unit
        depending on the target backend.

Returns:
    qiskit.circuit.InstructionSet: handle to the added instructions.

Raises:
    CircuitError: if arguments have bad format.
)r   Fr   )r   r   rC   )r   r   r8  r   s       r`   delayQuantumCircuit.delay  s0    2 <;;D{{55vr{NNr   c                F    U R                  [        R                  U/S5      $ )zApply :class:`~qiskit.circuit.library.HGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   Hr   r   s     r`   hQuantumCircuit.h       )),..5'2FFr   c                    Ub  US;   a!  U R                  [        R                  X/SUS9$ SSKJn  U R                  U" X4S9X// SS9$ )	a  Apply :class:`~qiskit.circuit.library.CHGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit: The qubit(s) used as the control.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
1r   rQ   r-  r   )CHGaterR  rS  Fr   )r;  r   CHlibrary.standard_gates.hr  r   )r   control_qubittarget_qubitrR  rS  r  s         r`   chQuantumCircuit.ch  h    . x!7---!>% .   	5{{6)	  
 	
r   c                F    U R                  [        R                  U/S5      $ )zApply :class:`~qiskit.circuit.library.IGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   Ir  s     r`   idQuantumCircuit.id  r  r   c                P    SSK Jn  U R                  U" [        U5      U5      USS9$ )a  Apply :class:`~qiskit.circuit.library.MSGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The angle of the rotation.
    qubits: The qubits to apply the gate to.

Returns:
    A handle to the instructions created.
r   )MSGateFr   )library.generalized_gates.gmsr  r   r  )r   thetar   r  s       r`   msQuantumCircuit.ms  s'     	:{{6#f+u5vE{JJr   c                H    U R                  [        R                  U/U45      $ )a  Apply :class:`~qiskit.circuit.library.PhaseGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: THe angle of the rotation.
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
)r;  r   Phase)r   r  r   s      r`   pQuantumCircuit.p  s#     )),*<*<ugxPPr   c                    Ub  US;   a"  U R                  [        R                  X#/U4US9$ SSKJn  U R                  U" XUS9X#// SS9$ )a  Apply :class:`~qiskit.circuit.library.CPhaseGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The angle of the rotation.
    control_qubit: The qubit(s) used as the control.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r  r-  r   )
CPhaseGater  Fr   )r;  r   CPhaselibrary.standard_gates.pr  r   )r   r  r  r  rR  rS  r  s          r`   cpQuantumCircuit.cp  so    2 x!7--##m%BUHTY .   	9{{ujA)	  
 	
r   c                `    SSK Jn  [        U5      nU R                  U" XUS9USS U/-   / SS9$ )a  Apply :class:`~qiskit.circuit.library.MCPhaseGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    lam: The angle of the rotation.
    control_qubits: The qubits used as the controls.
    target_qubit: The qubit(s) targeted by the gate.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r   )MCPhaseGaterS  NFr   )r  r  r  r   )r   lamcontrol_qubitsr  rS  r  rQ  s          r`   mcpQuantumCircuit.mcpC  sF    , 	:n-{{D1.	  
 	
r   c           
        SSK Jn  SSKJnJnJn  U R                  U5      n	U R                  U5      n
[        U
5      S:w  a  [        S5      eX-   nU
S   n
U R                  U5        [        U	5      nUS:X  a  U" U U[        * S-  [        S-  U	S   U
US9  gUS:  a*  USSUS-
  -  -  -  nU" U U[        * S-  [        S-  U	U
US9  gU" U" U5      [        U	5      US	9nU R                  XU
/-   S
S9  g)z
Apply Multiple-Controlled X rotation gate

Args:
    theta: The angle of the rotation.
    q_controls: The qubits used as the controls.
    q_target: The qubit targeted by the gate.
    use_basis_gates: use p, u, cx basis gates.
r   )RXGater   	_apply_cu_apply_mcu_graycode_mcsu2_real_diagonalz-The mcrx gate needs a single qubit as target.r  use_basis_gates   num_controlsr  Tr  N)library.standard_gates.rxr  !qiskit.synthesis.multi_controlledr  r  r  r  r  r   r3  r   r  )r   r  
q_controlsq_targetr  r  r  r  r  r  r  
all_qubitsn_c
theta_stepcgates                  r`   mcrxQuantumCircuit.mcrxc  s&   " 	6	
 	
 77
C55h?|!MNN#2
#A$.!!8aQq! / 1W!qS1W~"67JaQ / )u 0 /E
 LL, ?LNr   modec           
        SSK Jn  SSKJnJn	Jn
  U R                  U5      nU R                  U5      n[        U5      S:w  a  [        S5      eUc  / OU R                  U5      nX-   U-   nUS   nU R                  U5        Uc,  [        S[        U5      S-
  5      n[        U5      U:  a  SnOS	nUS:X  Ga"  SS
KJn  U R                  US-  U5        [        U5      S:X  a  U R                  US   U5        OS[        U5      S:X  a  U R                  US   US   U5        O*X/-   U-   nU" [        U5      5      nU R                  UUSS9  U R                  U* S-  U5        [        U5      S:X  a  U R                  US   U5        g[        U5      S:X  a  U R                  US   US   U5        gX/-   U-   nU" [        U5      5      nU R                  UUSS9  gUS	:X  an  [        U5      nUS:X  a  U" U USSUS   UUS9  gUS:  a  USSUS-
  -  -  -  nU	" U USSUUUS9  gU
" U" U5      [        U5      US9nU R                  UX/-   SS9  g[        SU S35      e)a=  
Apply Multiple-Controlled Y rotation gate

Args:
    theta: The angle of the rotation.
    q_controls: The qubits used as the controls.
    q_target: The qubit targeted by the gate.
    q_ancillae: The list of ancillary qubits.
    mode: The implementation mode to use.
    use_basis_gates: use p, u, cx basis gates
r   )RYGater   r  z-The mcry gate needs a single qubit as target.Nr  basic	noancilla)synth_mcx_n_clean_m15Tr  r  r  r  z-Unrecognized mode for building MCRY circuit: r  )library.standard_gates.ryr  r  r  r  r  r  r  r   r3  r  r  rycxccxr  )r   r  r  r  
q_ancillaer  r  r  r  r  r  r  r  ancillary_qubitsr  additional_vchainr  r   mcxr  r  r  s                         r`   mcryQuantumCircuit.mcry  s   * 	6	
 	
 77
C55h?|!MNN!+!329W9WXb9c#25EE
#A$ < #As>':Q'> ?#$(99"7?OGGEAIx(>"a'q)84^$)*N1,=xH'.8;KK+C,?@S&$7GGUFQJ)>"a'q)84^$)*N1,=xH'.8;KK+C,?@S&$7[ n%Cax"1% $3 q"a1q>&:;
#" $3 -5M!$^!4$3
 UN^$CTR MdVSTUVVr   c                >   SSK JnJn  SSKJn  U R                  U5      nU R                  U5      n	[        U	5      S:w  a  [        S5      eX-   n
U	S   n	U R                  U
5        [        U5      nUS:X  a}  U(       aZ  U R                  SSUS-  U	5        U R                  US   U	5        U R                  SSU* S-  U	5        U R                  US   U	5        g
U R                  U" U5      X/-   5        g
U" U" U5      [        U5      US9nU R                  XU	/-   SS	9  g
)z
Apply Multiple-Controlled Z rotation gate

Args:
    lam: The angle of the rotation.
    q_controls: The qubits used as the controls.
    q_target: The qubit targeted by the gate.
    use_basis_gates: use p, u, cx basis gates.
r   )CRZGateRZGater   )r  z-The mcrz gate needs a single qubit as target.r  r  Tr  N)library.standard_gates.rzr  r  r  r  r  r  r   r3  ur  r   r  )r   r  r  r  r  r  r  r  r  r  r  r  r  s                r`   mcrzQuantumCircuit.mcrz  s   " 	?J77
C55h?|!MNN#2
#A$.!!8q!S1Wl3q)<8q!cTAX|4q)<8GCL.>*IJ(s 0 /E
 LL, ?LNr   c                H    U R                  [        R                  U/X/5      $ )aI  Apply :class:`~qiskit.circuit.library.RGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The angle of the rotation.
    phi: The angle of the axis of rotation in the x-y plane.
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
)r;  r   R)r   r  phir   s       r`   rQuantumCircuit.r2  s!     )),..5'E<PPr   c                B    SSK Jn  U R                  U" XU5      U// SS9$ )a  Apply :class:`~qiskit.circuit.library.RVGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Rotation around an arbitrary rotation axis :math:`v`, where :math:`|v|` is the angle of
rotation in radians.

Args:
    vx: x-component of the rotation axis.
    vy: y-component of the rotation axis.
    vz: z-component of the rotation axis.
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
r   )RVGateFr   )library.generalized_gates.rvr  r   )r   vxvyvzr   r  s         r`   rvQuantumCircuit.rvC  s'    . 	9{{6""-w{GGr   c                H    U R                  [        R                  XU/S5      $ )ai  Apply :class:`~qiskit.circuit.library.RCCXGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit1: The qubit(s) used as the first control.
    control_qubit2: The qubit(s) used as the second control.
    target_qubit: The qubit(s) targeted by the gate.

Returns:
    A handle to the instructions created.
rQ   )r;  r   RCCX)r   control_qubit1control_qubit2r  s       r`   rccxQuantumCircuit.rccx^  s)    $ ))Mr
 	
r   c                H    U R                  [        R                  XX4/S5      $ )a  Apply :class:`~qiskit.circuit.library.RC3XGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit1: The qubit(s) used as the first control.
    control_qubit2: The qubit(s) used as the second control.
    control_qubit3: The qubit(s) used as the third control.
    target_qubit: The qubit(s) targeted by the gate.

Returns:
    A handle to the instructions created.
rQ   )r;  r   RC3X)r   r  r  control_qubit3r  s        r`   rcccxQuantumCircuit.rcccxt  s+    ( ))^J
 	
r   c                F    U R                  [        R                  U/U/US9$ )aJ  Apply :class:`~qiskit.circuit.library.RXGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The rotation angle of the gate.
    qubit: The qubit(s) to apply the gate to.
    label: The string label of the gate in the circuit.

Returns:
    A handle to the instructions created.
r-  )r;  r   RXr   r  r   rR  s       r`   rxQuantumCircuit.rx  '     )),//E7UGSX)YYr   c                    Ub  US;   a"  U R                  [        R                  X#/U/US9$ SSKJn  U R                  U" XUS9X#// SS9$ )a	  Apply :class:`~qiskit.circuit.library.CRXGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The angle of the rotation.
    control_qubit: The qubit(s) used as the control.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r  r-  r   )CRXGater  Fr   )r;  r   CRXr  r)  r   )r   r  r  r  rR  rS  r)  s          r`   crxQuantumCircuit.crx  o    2 x!7--  ="?%PU .   	7{{E:>)	  
 	
r   c                H    U R                  [        R                  X#/U/5      $ )a>  Apply :class:`~qiskit.circuit.library.RXXGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The angle of the rotation.
    qubit1: The qubit(s) to apply the gate to.
    qubit2: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
)r;  r   RXXr   r  qubit1qubit2s       r`   rxxQuantumCircuit.rxx  $     )),*:*:V<LugVVr   c                F    U R                  [        R                  U/U/US9$ )aJ  Apply :class:`~qiskit.circuit.library.RYGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The rotation angle of the gate.
    qubit: The qubit(s) to apply the gate to.
    label: The string label of the gate in the circuit.

Returns:
    A handle to the instructions created.
r-  )r;  r   RYr$  s       r`   r  QuantumCircuit.ry  r'  r   c                    Ub  US;   a"  U R                  [        R                  X#/U/US9$ SSKJn  U R                  U" XUS9X#// SS9$ )a	  Apply :class:`~qiskit.circuit.library.CRYGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The angle of the rotation.
    control_qubit: The qubit(s) used as the control.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r  r-  r   )CRYGater  Fr   )r;  r   CRYr  r:  r   )r   r  r  r  rR  rS  r:  s          r`   cryQuantumCircuit.cry  r-  r   c                H    U R                  [        R                  X#/U/5      $ )aC  Apply :class:`~qiskit.circuit.library.RYYGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The rotation angle of the gate.
    qubit1: The qubit(s) to apply the gate to.
    qubit2: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
)r;  r   RYYr0  s       r`   ryyQuantumCircuit.ryy  r5  r   c                H    U R                  [        R                  U/U/5      $ )a  Apply :class:`~qiskit.circuit.library.RZGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    phi: The rotation angle of the gate.
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
)r;  r   RZ)r   r  r   s      r`   rzQuantumCircuit.rz   s!     )),//E7SEJJr   c                    Ub  US;   a"  U R                  [        R                  X#/U/US9$ SSKJn  U R                  U" XUS9X#// SS9$ )a	  Apply :class:`~qiskit.circuit.library.CRZGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The angle of the rotation.
    control_qubit: The qubit(s) used as the control.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r  r-  r   )r  r  Fr   )r;  r   CRZr  r  r   )r   r  r  r  rR  rS  r  s          r`   crzQuantumCircuit.crz.  r-  r   c                H    U R                  [        R                  X#/U/5      $ )aC  Apply :class:`~qiskit.circuit.library.RZXGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The rotation angle of the gate.
    qubit1: The qubit(s) to apply the gate to.
    qubit2: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
)r;  r   RZXr0  s       r`   rzxQuantumCircuit.rzxU  r5  r   c                H    U R                  [        R                  X#/U/5      $ )aC  Apply :class:`~qiskit.circuit.library.RZZGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The rotation angle of the gate.
    qubit1: The qubit(s) to apply the gate to.
    qubit2: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
)r;  r   RZZr0  s       r`   rzzQuantumCircuit.rzzf  r5  r   c                F    U R                  [        R                  X/S5      $ )zApply :class:`~qiskit.circuit.library.ECRGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit1, qubit2: The qubits to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   ECRr   r1  r2  s      r`   ecrQuantumCircuit.ecrw  s"     )),*:*:V<LbQQr   c                F    U R                  [        R                  U/S5      $ )zApply :class:`~qiskit.circuit.library.SGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   rJ   r  s     r`   sQuantumCircuit.s  r  r   c                F    U R                  [        R                  U/S5      $ )zApply :class:`~qiskit.circuit.library.SdgGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   Sdgr  s     r`   sdgQuantumCircuit.sdg  !     )),*:*:UGRHHr   c                    Ub  US;   a!  U R                  [        R                  X/SUS9$ SSKJn  U R                  U" X4S9X// SS9$ )	a  Apply :class:`~qiskit.circuit.library.CSGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit: The qubit(s) used as the control.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r  rQ   r-  r   )CSGater  Fr   )r;  r   CSlibrary.standard_gates.sr`  r   )r   r  r  rR  rS  r`  s         r`   csQuantumCircuit.cs  r  r   c                    Ub  US;   a!  U R                  [        R                  X/SUS9$ SSKJn  U R                  U" X4S9X// SS9$ )	a  Apply :class:`~qiskit.circuit.library.CSdgGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit: The qubit(s) used as the control.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r  rQ   r-  r   )CSdgGater  Fr   )r;  r   CSdgrb  rf  r   )r   r  r  rR  rS  rf  s         r`   csdgQuantumCircuit.csdg  sj    . x!7--!!M#@"E .   	7{{58)	  
 	
r   c                F    U R                  [        R                  X/S5      $ )zApply :class:`~qiskit.circuit.library.SwapGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit1, qubit2: The qubits to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   SwaprT  s      r`   swapQuantumCircuit.swap  s)     ))
 	
r   c                F    U R                  [        R                  X/S5      $ )zApply :class:`~qiskit.circuit.library.iSwapGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit1, qubit2: The qubits to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   ISwaprT  s      r`   iswapQuantumCircuit.iswap  s#     )),*<*<v>NPRSSr   c                    Ub  US;   a"  U R                  [        R                  XU/SUS9$ SSKJn  U R                  U" XES9XU// SS9$ )	a$  Apply :class:`~qiskit.circuit.library.CSwapGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit: The qubit(s) used as the control.
    target_qubit1: The qubit(s) targeted by the gate.
    target_qubit2: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. ``'1'``).  Defaults to controlling
        on the ``'1'`` state.

Returns:
    A handle to the instructions created.
r  rQ   r-  r   )	CSwapGater  Fr   )r;  r   CSwaplibrary.standard_gates.swaprs  r   )r   r  target_qubit1target_qubit2rR  rS  rs  s          r`   cswapQuantumCircuit.cswap  sq    2 x!7--""}=	 .   	;{{E9=9	  
 	
r   c                F    U R                  [        R                  U/S5      $ )zApply :class:`~qiskit.circuit.library.SXGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   SXr  s     r`   sxQuantumCircuit.sx0  s     )),//E7BGGr   c                F    U R                  [        R                  U/S5      $ )zApply :class:`~qiskit.circuit.library.SXdgGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   SXdgr  s     r`   sxdgQuantumCircuit.sxdg=  s!     )),*;*;eWbIIr   c                    Ub  US;   a!  U R                  [        R                  X/SUS9$ SSKJn  U R                  U" X4S9X// SS9$ )	a  Apply :class:`~qiskit.circuit.library.CSXGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit: The qubit(s) used as the control.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r  rQ   r-  r   )CSXGater  Fr   )r;  r   CSXlibrary.standard_gates.sxr  r   )r   r  r  rR  rS  r  s         r`   csxQuantumCircuit.csxJ  sj    . x!7--  ="?5 .   	7{{%7)	  
 	
r   c                F    U R                  [        R                  U/S5      $ )zApply :class:`~qiskit.circuit.library.TGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   rK   r  s     r`   tQuantumCircuit.to  r  r   c                F    U R                  [        R                  U/S5      $ )zApply :class:`~qiskit.circuit.library.TdgGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   Tdgr  s     r`   tdgQuantumCircuit.tdg|  r^  r   c                J    U R                  [        R                  U/XU/5      $ )a  Apply :class:`~qiskit.circuit.library.UGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The :math:`\theta` rotation angle of the gate.
    phi: The :math:`\phi` rotation angle of the gate.
    lam: The :math:`\lambda` rotation angle of the gate.
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
)r;  r   U)r   r  r  r  r   s        r`   r  QuantumCircuit.u  s%    ( )),..5'EPSCTUUr   c	                    Ub  US;   a#  U R                  [        R                  XV/XX4/US9$ SSKJn	  U R                  U	" XX4XxS9XV// SS9$ )a  Apply :class:`~qiskit.circuit.library.CUGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    theta: The :math:`\theta` rotation angle of the gate.
    phi: The :math:`\phi` rotation angle of the gate.
    lam: The :math:`\lambda` rotation angle of the gate.
    gamma: The global phase applied of the U gate, if applied.
    control_qubit: The qubit(s) used as the control.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r  r-  r   )CUGater  Fr   )r;  r   CUlibrary.standard_gates.ur  r   )
r   r  r  r  gammar  r  rR  rS  r  s
             r`   cuQuantumCircuit.cu  st    > x!7---S(	 .   	5{{5sN)	  
 	
r   c                D    U R                  [        R                  U/SUS9$ )a  Apply :class:`~qiskit.circuit.library.XGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit: The qubit(s) to apply the gate to.
    label: The string label of the gate in the circuit.

Returns:
    A handle to the instructions created.
rQ   r-  )r;  r   X)r   r   rR  s      r`   r  QuantumCircuit.x  s$     )),..5'2U)SSr   c                    Ub  US;   a!  U R                  [        R                  X/SUS9$ SSKJn  U R                  U" X4S9X// SS9$ )	a  Apply :class:`~qiskit.circuit.library.CXGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit: The qubit(s) used as the control.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r  rQ   r-  r   )CXGater  Fr   )r;  r   CXlibrary.standard_gates.xr  r   )r   r  r  rR  rS  r  s         r`   r  QuantumCircuit.cx  k    . x!7---	 .   	5{{6)	  
 	
r   c                F    U R                  [        R                  X/S5      $ )a  Apply :class:`~qiskit.circuit.library.DCXGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit1: The qubit(s) to apply the gate to.
    qubit2: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   DCXrT  s      r`   dcxQuantumCircuit.dcx  s"     )),*:*:V<LbQQr   c                    Ub  US;   a#  U R                  [        R                  XU/S5      $ SSKJn  U R                  U" US9XU// SS9$ )a  Apply :class:`~qiskit.circuit.library.CCXGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit1: The qubit(s) used as the first control.
    control_qubit2: The qubit(s) used as the second control.
    target_qubit: The qubit(s) targeted by the gate.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
11   rQ   r   )CCXGater  Fr   )r;  r   CCXr  r  r   )r   r  r  r  rS  r  s         r`   r  QuantumCircuit.ccx  si    . y!8--  >  	6{{z*\:	  
 	
r   z2.1zInstead, add a generic MCXGate to the circuit and specify the synthesis method via the ``hls_config`` in the transpilation. Alternatively, specific decompositions are available at https://qisk.it/mcx.)rR   r   additional_msgc                    SSK JnJnJn  [	        U5      n	1 Skn
U(       a  U R                  U5      nUc  U" XS9nOYXJ;   aC  US:X  a  U" XS9nOGUS;   a  U" XS9nO:US;   a	  U" U	S	US9nO+US
;   a	  U" U	SUS9nO[        S5      e[        SU SU
 35      eUb  [        US5      (       d  / nO[        R                  " 5          [        R                  " S[        SS9  UR                  nSSS5        WS:  aX  Uc  [        SU S35      e[        US5      (       d  U/n[	        U5      U:  a  [	        U5      n[        SU SU S35      eUSU nO/ nU R                  XSS U/-   USS -   / 5      $ ! , (       d  f       N= f)a  Apply :class:`~qiskit.circuit.library.MCXGate`.

The multi-cX gate can be implemented using different techniques, which use different numbers
of ancilla qubits and have varying circuit depth. These modes are:

- ``'noancilla'``: Requires 0 ancilla qubits.
- ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0.
- ``'v-chain'``: Requires 2 less ancillas than the number of control qubits.
- ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer).

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubits: The qubits used as the controls.
    target_qubit: The qubit(s) targeted by the gate.
    ancilla_qubits: The qubits used as the ancillae, if the mode requires them.
    mode: The choice of mode, explained further above.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.

Raises:
    ValueError: if the given mode is not known, or if too few ancilla qubits are passed.
    AttributeError: if no ancilla qubits are passed, but some are needed.
r   )MCXGateMCXRecursive	MCXVChain>   r  advancedr  	recursionv-chainv-chain-dirtybasic-dirty-ancillaNr  r  )r  r  )r  r  F)r  r  T)dirty_ancillasrS  zunreachable.zUnsupported mode (z) selected, choose one of num_ancilla_qubitsignorerz  )categorymoduler   zNo ancillas provided, but z are needed!r  z	At least z ancillas required, but z given.)r  r  r  r  r  r  rk   rA  r  catch_warningsfilterwarningsDeprecationWarningr  r   r   )r   r  r  ancilla_qubitsr  rS  r  r  r  rQ  available_implementationsr  rJ  requiredactuallys                  r`   r   QuantumCircuit.mcx:  s   Z 	ONn-%
! ..~>A<?BD.{"F22#OK-- %JOAA R\] 00 $TF*DE^D_`  <wt-ABBN((*'';MV^_22 + !|!)(+EhZ|)\]] ~y99&4%5N~&1">2H$#H:-EhZwW  "0	!:!#{{4!2l^!CnUVFW!WY[\\- +*s   'E//
E=c                F    U R                  [        R                  U/S5      $ )zApply :class:`~qiskit.circuit.library.YGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   Yr  s     r`   yQuantumCircuit.y  r  r   c                    Ub  US;   a!  U R                  [        R                  X/SUS9$ SSKJn  U R                  U" X4S9X// SS9$ )	a  Apply :class:`~qiskit.circuit.library.CYGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit: The qubit(s) used as the controls.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r  rQ   r-  r   )CYGater  Fr   )r;  r   CYlibrary.standard_gates.yr  r   )r   r  r  rR  rS  r  s         r`   cyQuantumCircuit.cy  r  r   c                F    U R                  [        R                  U/S5      $ )zApply :class:`~qiskit.circuit.library.ZGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    qubit: The qubit(s) to apply the gate to.

Returns:
    A handle to the instructions created.
rQ   )r;  r   Zr  s     r`   zQuantumCircuit.z  r  r   c                    Ub  US;   a!  U R                  [        R                  X/SUS9$ SSKJn  U R                  U" X4S9X// SS9$ )	a  Apply :class:`~qiskit.circuit.library.CZGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit: The qubit(s) used as the controls.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '1').  Defaults to controlling
        on the '1' state.

Returns:
    A handle to the instructions created.
r  rQ   r-  r   )CZGater  Fr   )r;  r   CZlibrary.standard_gates.zr  r   )r   r  r  rR  rS  r  s         r`   czQuantumCircuit.cz  r  r   c                    Ub  US;   a"  U R                  [        R                  XU/SUS9$ SSKJn  U R                  U" XES9XU// SS9$ )	a)  Apply :class:`~qiskit.circuit.library.CCZGate`.

For the full matrix form of this gate, see the underlying gate documentation.

Args:
    control_qubit1: The qubit(s) used as the first control.
    control_qubit2: The qubit(s) used as the second control.
    target_qubit: The qubit(s) targeted by the gate.
    label: The string label of the gate in the circuit.
    ctrl_state:
        The control state in decimal, or as a bitstring (e.g. '10').  Defaults to controlling
        on the '11' state.

Returns:
    A handle to the instructions created.
r  rQ   r-  r   )CCZGater  Fr   )r;  r   CCZr  r  r   )r   r  r  r  rR  rS  r  s          r`   cczQuantumCircuit.ccz  sq    2 y!8--  >	 .   	6{{%7\:	  
 	
r   c                >    SSK Jn  U R                  U" U5      U/ SS9$ )zApply :class:`~qiskit.circuit.library.PauliGate`.

Args:
    pauli_string: A string representing the Pauli operator to apply, e.g. 'XX'.
    qubits: The qubits to apply this gate to.

Returns:
    A handle to the instructions created.
r   )	PauliGateFr   ).qiskit.circuit.library.generalized_gates.paulir  r   )r   pauli_stringr   r  s       r`   pauliQuantumCircuit.pauli8  s$     	M{{9\2FBU{KKr   c           	        SSK Jn  Uc  U R                  nO2[        U[        [
        R                  [        [        45      (       a  U/n[        U[        5      (       a  [        U5      OSnU R                  U" XX4S9USS9$ )u  Prepare qubits in a specific state.

This class implements a state preparing unitary. Unlike
:meth:`.initialize` it does not reset the qubits first.

Args:
    state: The state to initialize to, can be either of the following.

        * Statevector or vector of complex amplitudes to initialize to.
        * Labels of basis states of the Pauli eigenstates Z, X, Y. See
          :meth:`.Statevector.from_label`. Notice the order of the labels is reversed with
          respect to the qubit index to be applied to. Example label '01' initializes the
          qubit zero to :math:`|1\rangle` and the qubit one to :math:`|0\rangle`.
        * An integer that is used as a bitmap indicating which qubits to initialize to
          :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit
          2 to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`.

    qubits: Qubits to initialize. If ``None`` the initialization is applied to all qubits in
        the circuit.
    label: An optional label for the gate
    normalize: Whether to normalize an input array to a unit vector.

Returns:
    A handle to the instruction that was just initialized

Examples:
    Prepare a qubit in the state :math:`(|0\rangle - |1\rangle) / \sqrt{2}`.

    .. plot::
       :include-source:
       :nofigs:

        import numpy as np
        from qiskit import QuantumCircuit

        circuit = QuantumCircuit(1)
        circuit.prepare_state([1/np.sqrt(2), -1/np.sqrt(2)], 0)
        circuit.draw()

    output:

    .. code-block:: text

             ┌─────────────────────────────────────┐
        q_0: ┤ State Preparation(0.70711,-0.70711) ├
             └─────────────────────────────────────┘


    Prepare from a string two qubits in the state :math:`|10\rangle`.
    The order of the labels is reversed with respect to qubit index.
    More information about labels for basis states are in
    :meth:`.Statevector.from_label`.

    .. plot::
       :include-source:
       :nofigs:

        import numpy as np
        from qiskit import QuantumCircuit

        circuit = QuantumCircuit(2)
        circuit.prepare_state('01', circuit.qubits)
        circuit.draw()

    output:

    .. code-block:: text

             ┌─────────────────────────┐
        q_0: ┤0                        ├
             │  State Preparation(0,1) │
        q_1: ┤1                        ├
             └─────────────────────────┘


    Initialize two qubits from an array of complex amplitudes

    .. plot::
        :include-source:
        :nofigs:

        import numpy as np
        from qiskit import QuantumCircuit

        circuit = QuantumCircuit(2)
        circuit.prepare_state([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits)
        circuit.draw()

    output:

    .. code-block:: text

             ┌───────────────────────────────────────────┐
        q_0: ┤0                                          ├
             │  State Preparation(0,0.70711,-0.70711j,0) │
        q_1: ┤1                                          ├
             └───────────────────────────────────────────┘
r   )StatePreparationN)rR  	normalizeFr   )'qiskit.circuit.library.data_preparationr  r   r[   re   rD  rE  slicer    r  r   )r   stater   rR  r  r  r  s          r`   prepare_stateQuantumCircuit.prepare_stateJ  su    T 	M>[[Fbjj% ?@@XF$.uc$:$:S[
{{UeQ  
 	
r   c                   SSK Jn  Uc  U R                  nO2[        U[        [
        R                  [        [        45      (       a  U/n[        U[        5      (       a  [        U5      OSnU R                  U" XU5      USS9$ )u  Initialize qubits in a specific state.

Qubit initialization is done by first resetting the qubits to :math:`|0\rangle`
followed by calling :class:`~qiskit.circuit.library.StatePreparation`
class to prepare the qubits in a specified state.
Both these steps are included in the
:class:`~qiskit.circuit.library.Initialize` instruction.

Args:
    params: The state to initialize to, can be either of the following.

        * Statevector or vector of complex amplitudes to initialize to.
        * Labels of basis states of the Pauli eigenstates Z, X, Y. See
          :meth:`.Statevector.from_label`. Notice the order of the labels is reversed with
          respect to the qubit index to be applied to. Example label ``'01'`` initializes the
          qubit zero to :math:`|1\rangle` and the qubit one to :math:`|0\rangle`.
        * An integer that is used as a bitmap indicating which qubits to initialize to
          :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit
          2 to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`.

    qubits: Qubits to initialize. If ``None`` the initialization is applied to all qubits in
        the circuit.
    normalize: Whether to normalize an input array to a unit vector.

Returns:
    A handle to the instructions created.

Examples:
    Prepare a qubit in the state :math:`(|0\rangle - |1\rangle) / \sqrt{2}`.

    .. plot::
       :include-source:
       :nofigs:

        import numpy as np
        from qiskit import QuantumCircuit

        circuit = QuantumCircuit(1)
        circuit.initialize([1/np.sqrt(2), -1/np.sqrt(2)], 0)
        circuit.draw()

    output:

    .. code-block:: text

             ┌──────────────────────────────┐
        q_0: ┤ Initialize(0.70711,-0.70711) ├
             └──────────────────────────────┘


    Initialize from a string two qubits in the state :math:`|10\rangle`.
    The order of the labels is reversed with respect to qubit index.
    More information about labels for basis states are in
    :meth:`.Statevector.from_label`.

    .. plot::
       :include-source:
       :nofigs:

        import numpy as np
        from qiskit import QuantumCircuit

        circuit = QuantumCircuit(2)
        circuit.initialize('01', circuit.qubits)
        circuit.draw()

    output:

    .. code-block:: text

             ┌──────────────────┐
        q_0: ┤0                 ├
             │  Initialize(0,1) │
        q_1: ┤1                 ├
             └──────────────────┘

    Initialize two qubits from an array of complex amplitudes.

    .. plot::
       :include-source:
       :nofigs:

        import numpy as np
        from qiskit import QuantumCircuit

        circuit = QuantumCircuit(2)
        circuit.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits)
        circuit.draw()

    output:

    .. code-block:: text

             ┌────────────────────────────────────┐
        q_0: ┤0                                   ├
             │  Initialize(0,0.70711,-0.70711j,0) │
        q_1: ┤1                                   ├
             └────────────────────────────────────┘
r   )
InitializeNFr   )$library.data_preparation.initializerr  r   r[   re   rD  rE  r  r    r  r   )r   r6  r   r  r  r  s         r`   
initializeQuantumCircuit.initialize  sl    T 	E>[[Fbjj% ?@@XF$.vs$;$;S[
{{:f)DfSX{YYr   c                    SSK Jn  U" XS9nUR                  S:X  a-  [        U[        [
        45      (       d  [        U5      S:  a  U/nU R                  XR/ SS9$ )aw  Apply unitary gate specified by ``obj`` to ``qubits``.

Args:
    obj: Unitary operator.
    qubits: The circuit qubits to apply the transformation to.
    label: Unitary name for backend [Default: None].

Returns:
    QuantumCircuit: The quantum circuit.

Example:

    Apply a gate specified by a unitary matrix to a quantum circuit

    .. plot::
       :include-source:
       :nofigs:

        from qiskit import QuantumCircuit
        matrix = [[0, 0, 0, 1],
                [0, 0, 1, 0],
                [1, 0, 0, 0],
                [0, 1, 0, 0]]
        circuit = QuantumCircuit(2)
        circuit.unitary(matrix, [0, 1])
r   )UnitaryGater-  Fr   )!library.generalized_gates.unitaryr  r  r[   re   r    r  r   )r   r	  r   rR  r  rJ  s         r`   unitaryQuantumCircuit.unitary8  sX    B 	C3, ??a&3,//3v;? {{4%{88r   c                    U R                  5       nU H,  nU R                  U5       H  nUR                  U5        M     M.     g)a  Mark the given qubit(s) as used within the current scope, without adding an operation.

This has no effect (other than raising an exception on invalid input) when called in the
top scope of a :class:`QuantumCircuit`.  Within a control-flow builder, this causes the
qubit to be "used" by the control-flow block, if it wouldn't already be used, without adding
any additional operations on it.

For example::

    from qiskit.circuit import QuantumCircuit

    qc = QuantumCircuit(3)
    with qc.box():
        # This control-flow block will only use qubits 0 and 1.
        qc.cx(0, 1)
    with qc.box():
        # This control-flow block will contain only the same operation as the previous
        # block, but it will also mark qubit 2 as "used" by the box.
        qc.cx(0, 1)
        qc.noop(2)

Args:
    *qargs: variadic list of valid qubit specifiers.  Anything that can be passed as a qubit
        or collection of qubits is valid for each argument here.

Raises:
    CircuitError: if any requested qubit is not valid for the circuit.
N)r  r  	use_qubit)r   r   scoper8  r   s        r`   noopQuantumCircuit.noope  s?    : ##%D77= & > r   c                Z    U R                   (       a  U R                   S   $ U R                  $ )Nr&  )rx   rv   r   s    r`   r  QuantumCircuit._current_scope  s(    $$,,R00   r   c                n    U R                   R                  [        UUU R                  5       UUUS95        g)a  Add a scope for collecting instructions into this circuit.

This should only be done by the control-flow context managers, which will handle cleaning up
after themselves at the end as well.

Args:
    qubits: Any qubits that this scope should automatically use.
    clbits: Any clbits that this scope should automatically use.
    allow_jumps: Whether this scope allows jumps to be used within it.
    forbidden_message: If given, all attempts to add instructions to this scope will raise a
        :exc:`.CircuitError` with this message.
)parent	registersallow_jumpsforbidden_messageN)rx   r   r*   r  )r   r   r   r  r  r   s         r`   _push_scopeQuantumCircuit._push_scope  s;    ( 	!!((#**,#'"3		
r   c                6    U R                   R                  5       $ )zFinish a scope used in the control-flow builder interface, and return it to the caller.

This should only be done by the control-flow context managers, since they naturally
synchronize the creation and deletion of stack elements.)rx   popr   s    r`   
_pop_scopeQuantumCircuit._pop_scope  s    
 ((,,..r   c                    U R                   (       a  U R                   S   R                  5       $ U R                  (       d  [        S5      eU R                  S   $ )a  Return the instruction 3-tuple of the most recent instruction in the current scope, even
if that scope is currently under construction.

This function is only intended for use by the control-flow ``if``-statement builders, which
may need to modify a previous instruction.r&  &This circuit contains no instructions.)rx   peekry   r   r   s    r`   #_peek_previous_instruction_in_scope2QuantumCircuit._peek_previous_instruction_in_scope  sH     $$,,R05577zzGHHzz"~r   c                    U R                   (       a  U R                   S   R                  5       $ U R                  (       d  [        S5      eU R                  R                  5       nU$ )a=  Return the instruction 3-tuple of the most recent instruction in the current scope, even
if that scope is currently under construction, and remove it from that scope.

This function is only intended for use by the control-flow ``if``-statement builders, which
may need to replace a previous instruction with another.
r&  r  )rx   r  ry   r   )r   r   s     r`   "_pop_previous_instruction_in_scope1QuantumCircuit._pop_previous_instruction_in_scope  sP     $$,,R04466zzGHHjjnn&r   )rR  r   r   r   c         
        [        U[        5      (       a9  UnUb  Uc  [        S5      eU[        L a  / nU R	                  [        XXdUS9UUSS9$ USL a
  USL a  SOUnOUSLa  [        S5      eUnUc  Ub  [        S5      e[        XXdUS9$ )	a  Create a ``box`` of operations on this circuit that are treated atomically in the greater
context.

A "box" is a control-flow construct that is entered unconditionally.  The contents of the
box behave somewhat as if the start and end of the box were barriers (see :meth:`barrier`),
except it is permissible to commute operations "all the way" through the box.  The box is
also an explicit scope for the purposes of variables, stretches and compiler passes.

There are two forms for calling this function:

* Pass a :class:`QuantumCircuit` positionally, and the ``qubits`` and ``clbits`` it acts
  on.  In this form, a :class:`.BoxOp` is immediately created and appended using the circuit
  as the body.

* Use in a ``with`` statement with no ``body``, ``qubits`` or ``clbits``.  This is the
  "builder-interface form", where you then use other :class:`QuantumCircuit` methods within
  the Python ``with`` scope to add instructions to the ``box``.  This is the preferred form,
  and much less error prone.

Examples:

    Using the builder interface to add two boxes in sequence.  The two boxes in this circuit
    can execute concurrently, and the second explicitly inserts a data-flow dependency on
    qubit 8 for the duration of the box, even though the qubit is idle.

    .. code-block:: python

        from qiskit.circuit import QuantumCircuit, Annotation

        class MyAnnotation(Annotation):
            namespace = "my.namespace"

        qc = QuantumCircuit(9)
        with qc.box():
            qc.cz(0, 1)
            qc.cz(2, 3)
        with qc.box([MyAnnotation()]):
            qc.cz(4, 5)
            qc.cz(6, 7)
            qc.noop(8)

    Using the explicit construction of box.  This creates the same circuit as above, and
    should give an indication why the previous form is preferred for interactive use.

    .. code-block:: python

        from qiskit.circuit import QuantumCircuit, BoxOp

        body_0 = QuantumCircuit(4)
        body_0.cz(0, 1)
        body_0.cz(2, 3)

        # Note that the qubit indices inside a body related only to the body.  The
        # association with qubits in the containing circuit is made by the ``qubits``
        # argument to `QuantumCircuit.box`.
        body_1 = QuantumCircuit(5)
        body_1.cz(0, 1)
        body_1.cz(2, 3)

        qc = QuantumCircuit(9)
        qc.box(body_0, [0, 1, 2, 3], [])
        qc.box(body_1, [4, 5, 6, 7, 8], [])

Args:
    body_or_annotations: the first positional argument is unnamed.  If a
        :class:`QuantumCircuit` is passed positionally, it is immediately used as the body
        of the box, and ``qubits`` and ``clbits`` must also be specified.  If not given, or
        if given an iterable of :class:`.Annotation` objects, the context-manager form of
        this method is triggered.
    qubits: the qubits to apply the :class:`.BoxOp` to, in the explicit form.
    clbits: the qubits to apply the :class:`.BoxOp` to, in the explicit form.
    label: an optional string label for the instruction.
    duration: an optional explicit duration for the :class:`.BoxOp`.  Scheduling passes are
        constrained to schedule the contained scope to match a given duration, including
        delay insertion if required.
    unit: the unit of the ``duration``.
    annotations: any :class:`.Annotation` objects the box should have.  When this method is
        used in context-manager form, this argument can instead be passed as the only
        positional argument.
z>When using 'box' with a body, you must pass qubits and clbits.)r   r   rR  r   Fr   .rQ   zCQuantumCircuit.box() got multiple values for argument 'annotations'zHWhen using 'box' as a context manager, you cannot pass qubits or clbits.)r[   rN   r   r`  r   r-   rl   r.   )	r   body_or_annotationsr   r   rR  r   r   r   bodys	            r`   r>  QuantumCircuit.box  s    x )>::&D~"#cddh& ;;dDS^_	    #% +s 2"K#abb-K!3Z  $Wbccr   c                   g rZ   rQ   r   r}  r  r   r   rR  s         r`   
while_loopQuantumCircuit.while_loopD  s     r   c                   g rZ   rQ   r  s         r`   r  r  O       r   c               >   U R                  5       n[        U[        R                  5      (       a  [	        Xa5      nOUR                  US   5      US   4nUc  Uc  Ub  [        S5      e[        XUS9$ Ub  Uc  [        S5      eU R                  [        XU5      X4SS9$ )a  Create a ``while`` loop on this circuit.

There are two forms for calling this function.  If called with all its arguments (with the
possible exception of ``label``), it will create a
:obj:`~qiskit.circuit.controlflow.WhileLoopOp` with the given ``body``.  If ``body`` (and
``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which
will automatically build a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` when the scope
finishes.  In this form, you do not need to keep track of the qubits or clbits you are
using, because the scope will handle it for you.

Example usage::

    from qiskit.circuit import QuantumCircuit, Clbit, Qubit
    bits = [Qubit(), Qubit(), Clbit()]
    qc = QuantumCircuit(bits)

    with qc.while_loop((bits[2], 0)):
        qc.h(0)
        qc.cx(0, 1)
        qc.measure(0, 0)

Args:
    condition (Tuple[Union[ClassicalRegister, Clbit], int]): An equality condition to be
        checked prior to executing ``body``. The left-hand side of the condition must be a
        :obj:`~ClassicalRegister` or a :obj:`~Clbit`, and the right-hand side must be an
        integer or boolean.
    body (Optional[QuantumCircuit]): The loop body to be repeatedly executed.  Omit this to
        use the context-manager mode.
    qubits (Optional[Sequence[Qubit]]): The circuit qubits over which the loop body should
        be run.  Omit this to use the context-manager mode.
    clbits (Optional[Sequence[Clbit]]): The circuit clbits over which the loop body should
        be run.  Omit this to use the context-manager mode.
    label (Optional[str]): The string label of the instruction in the circuit.

Returns:
    InstructionSet or WhileLoopContext: If used in context-manager mode, then this should be
    used as a ``with`` resource, which will infer the block content and operands on exit.
    If the full form is used, then this returns a handle to the instructions created.

Raises:
    CircuitError: if an incorrect calling convention is used.
r   r   zOWhen using 'while_loop' as a context manager, you cannot pass qubits or clbits.r-  zEWhen using 'while_loop' with a body, you must pass qubits and clbits.Fr   )
r  r[   r9   rD  rE  r1  r   r8   r   r7   )r   r}  r  r   r   rR  r7  s          r`   r  r  Z  s    V ++-i++&}@I&AA)A,OQZ[\Q]^I<!V%7"9  $D5AA^v~W  {{;y>UZ{[[r   c                   g rZ   rQ   r   indexsetloop_parameterr  r   r   rR  s          r`   for_loopQuantumCircuit.for_loop       r   c                   g rZ   rQ   r  s          r`   r  r    r   r   c                   Uc  Uc  Ub  [        S5      e[        XX&S9$ Ub  Uc  [        S5      eU R                  [        XX65      XESS9$ )a	  Create a ``for`` loop on this circuit.

There are two forms for calling this function.  If called with all its arguments (with the
possible exception of ``label``), it will create a
:class:`~qiskit.circuit.ForLoopOp` with the given ``body``.  If ``body`` (and
``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which,
when entered, provides a loop variable (unless one is given, in which case it will be
reused) and will automatically build a :class:`~qiskit.circuit.ForLoopOp` when the
scope finishes.  In this form, you do not need to keep track of the qubits or clbits you are
using, because the scope will handle it for you.

For example::

    from qiskit import QuantumCircuit
    qc = QuantumCircuit(2, 1)

    with qc.for_loop(range(5)) as i:
        qc.h(0)
        qc.cx(0, 1)
        qc.measure(0, 0)
        with qc.if_test((0, True)):
            qc.break_loop()

Args:
    indexset (Iterable[int]): A collection of integers to loop over.  Always necessary.
    loop_parameter (Optional[Parameter]): The parameter used within ``body`` to which
        the values from ``indexset`` will be assigned.  In the context-manager form, if this
        argument is not supplied, then a loop parameter will be allocated for you and
        returned as the value of the ``with`` statement.  This will only be bound into the
        circuit if it is used within the body.

        If this argument is ``None`` in the manual form of this method, ``body`` will be
        repeated once for each of the items in ``indexset`` but their values will be
        ignored.
    body (Optional[QuantumCircuit]): The loop body to be repeatedly executed.  Omit this to
        use the context-manager mode.
    qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the loop body
        should be run.  Omit this to use the context-manager mode.
    clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the loop body
        should be run.  Omit this to use the context-manager mode.
    label (Optional[str]): The string label of the instruction in the circuit.

Returns:
    InstructionSet or ForLoopContext: depending on the call signature, either a context
    manager for creating the for loop (it will automatically be added to the circuit at the
    end of the block), or an :obj:`~InstructionSet` handle to the appended loop operation.

Raises:
    CircuitError: if an incorrect calling convention is used.
zMWhen using 'for_loop' as a context manager, you cannot pass qubits or clbits.r-  zCWhen using 'for_loop' with a body, you must pass qubits and clbits.Fr   )r   r2   r   r1   r  s          r`   r  r    st    j <!V%7"c  "$.NN^v~U  {{h<fSX  
 	
r   c                    g rZ   rQ   )r   r}  s     r`   if_testQuantumCircuit.if_test  s    VYr   c                   g rZ   rQ   )r   r}  	true_bodyr   r   rR  s         r`   r$  r%    r  r   c                  U R                  5       n[        U[        R                  5      (       a  [	        Xa5      nOUR                  US   5      US   4nUcP  Uc  Ub  [        S5      e[        U R                  =(       a    U R                  S   R                  5      n[        XXuS9$ Ub  Uc  [        S5      eU R                  [        XSU5      X4SS	9$ )
a	  Create an ``if`` statement on this circuit.

There are two forms for calling this function.  If called with all its arguments (with the
possible exception of ``label``), it will create a
:obj:`~qiskit.circuit.IfElseOp` with the given ``true_body``, and there will be
no branch for the ``false`` condition (see also the :meth:`.if_else` method).  However, if
``true_body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context
manager, which can be used to build ``if`` statements.  The return value of the ``with``
statement is a chainable context manager, which can be used to create subsequent ``else``
blocks.  In this form, you do not need to keep track of the qubits or clbits you are using,
because the scope will handle it for you.

For example::

    from qiskit.circuit import QuantumCircuit, Qubit, Clbit
    bits = [Qubit(), Qubit(), Qubit(), Clbit(), Clbit()]
    qc = QuantumCircuit(bits)

    qc.h(0)
    qc.cx(0, 1)
    qc.measure(0, 0)
    qc.h(0)
    qc.cx(0, 1)
    qc.measure(0, 1)

    with qc.if_test((bits[3], 0)) as else_:
        qc.x(2)
    with else_:
        qc.h(2)
        qc.z(2)

Args:
    condition (Tuple[Union[ClassicalRegister, Clbit], int]): A condition to be evaluated in
        real time during circuit execution, which, if true, will trigger the evaluation of
        ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be
        tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be
        compared to either a ``bool`` or an ``int``.
    true_body (Optional[QuantumCircuit]): The circuit body to be run if ``condition`` is
        true.
    qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the if/else
        should be run.
    clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the if/else
        should be run.
    label (Optional[str]): The string label of the instruction in the circuit.

Returns:
    InstructionSet or IfContext: depending on the call signature, either a context
    manager for creating the ``if`` block (it will automatically be added to the circuit at
    the end of the block), or an :obj:`~InstructionSet` handle to the appended conditional
    operation.

Raises:
    CircuitError: If the provided condition references Clbits outside the
        enclosing circuit.
    CircuitError: if an incorrect calling convention is used.

Returns:
    A handle to the instruction created.
r   r   NzLWhen using 'if_test' as a context manager, you cannot pass qubits or clbits.r&  in_looprR  zBWhen using 'if_test' with a body, you must pass qubits and clbits.Fr   )r  r[   r9   rD  rE  r1  r   r  rx   r  r4   r   r3   )r   r}  r'  r   r   rR  r7  r*  s           r`   r$  r%    s    H ++-i++&}@I&AA)A,OQZ[\Q]^I!V%7"b 
 444b9R9RSU9V9b9bcGTgKK^v~cdd{{8I$F]b{ccr   c                    U R                  5       n[        U[        R                  5      (       a  [	        Xq5      nOUR                  US   5      US   4nU R                  [        XX65      XESS9$ )a  Apply :class:`~qiskit.circuit.IfElseOp`.

.. note::

    This method does not have an associated context-manager form, because it is already
    handled by the :meth:`.if_test` method.  You can use the ``else`` part of that with
    something such as::

        from qiskit.circuit import QuantumCircuit, Qubit, Clbit
        bits = [Qubit(), Qubit(), Clbit()]
        qc = QuantumCircuit(bits)
        qc.h(0)
        qc.cx(0, 1)
        qc.measure(0, 0)
        with qc.if_test((bits[2], 0)) as else_:
            qc.h(0)
        with else_:
            qc.x(0)

Args:
    condition: A condition to be evaluated in real time at circuit execution, which,
        if true, will trigger the evaluation of ``true_body``. Can be
        specified as either a tuple of a ``ClassicalRegister`` to be
        tested for equality with a given ``int``, or as a tuple of a
        ``Clbit`` to be compared to either a ``bool`` or an ``int``.
    true_body: The circuit body to be run if ``condition`` is true.
    false_body: The circuit to be run if ``condition`` is false.
    qubits: The circuit qubits over which the if/else should be run.
    clbits: The circuit clbits over which the if/else should be run.
    label: The string label of the instruction in the circuit.

Raises:
    CircuitError: If the provided condition references Clbits outside the
        enclosing circuit.

Returns:
    A handle to the instruction created.
r   r   Fr   )r  r[   r9   rD  rE  r1  r   r3   )r   r}  r'  
false_bodyr   r   rR  r7  s           r`   if_elseQuantumCircuit.if_else[  ss    ^ ++-i++&}@I&AA)A,OQZ[\Q]^I{{Y:=vTY  
 	
r   c                   g rZ   rQ   r   r  casesr   r   rR  s         r`   switchQuantumCircuit.switch  s     r   c                   g rZ   rQ   r0  s         r`   r2  r3    r  r   c                  U R                  5       n[        U[        R                  5      (       a  [	        Xa5      nOUR                  U5      nUcP  Uc  Ub  [        S5      e[        U R                  =(       a    U R                  S   R                  5      n[        XXuS9$ Ub  Uc  [        S5      eU R                  [        XUS9X4SS9$ )aE	  Create a ``switch``/``case`` structure on this circuit.

There are two forms for calling this function.  If called with all its arguments (with the
possible exception of ``label``), it will create a :class:`.SwitchCaseOp` with the given
case structure.  If ``cases`` (and ``qubits`` and ``clbits``) are *not* passed, then this
acts as a context manager, which will automatically build a :class:`.SwitchCaseOp` when the
scope finishes.  In this form, you do not need to keep track of the qubits or clbits you are
using, because the scope will handle it for you.

Example usage::

    from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister
    qreg = QuantumRegister(3)
    creg = ClassicalRegister(3)
    qc = QuantumCircuit(qreg, creg)
    qc.h([0, 1, 2])
    qc.measure([0, 1, 2], [0, 1, 2])

    with qc.switch(creg) as case:
        with case(0):
            qc.x(0)
        with case(1, 2):
            qc.z(1)
        with case(case.DEFAULT):
            qc.cx(0, 1)

Args:
    target (Union[ClassicalRegister, Clbit]): The classical value to switch one.  This must
        be integer-like.
    cases (Iterable[Tuple[typing.Any, QuantumCircuit]]): A sequence of case specifiers.
        Each tuple defines one case body (the second item).  The first item of the tuple can
        be either a single integer value, the special value :data:`.CASE_DEFAULT`, or a
        tuple of several integer values.  Each of the integer values will be tried in turn;
        control will then pass to the body corresponding to the first match.
        :data:`.CASE_DEFAULT` matches all possible values.  Omit in context-manager form.
    qubits (Sequence[Qubit]): The circuit qubits over which all case bodies execute. Omit in
        context-manager form.
    clbits (Sequence[Clbit]): The circuit clbits over which all case bodies execute. Omit in
        context-manager form.
    label (Optional[str]): The string label of the instruction in the circuit.

Returns:
    InstructionSet or SwitchCaseContext: If used in context-manager mode, then this should
    be used as a ``with`` resource, which will return an object that can be repeatedly
    entered to produce cases for the switch statement.  If the full form is used, then this
    returns a handle to the instructions created.

Raises:
    CircuitError: if an incorrect calling convention is used.
zKWhen using 'switch' as a context manager, you cannot pass qubits or clbits.r&  r)  z@When using 'switch' with cases, you must pass qubits and clbits.r-  Fr   )r  r[   r9   rD  rE  r1  r   r  rx   r  r6   r   r5   )r   r  r1  r   r   rR  r7  r*  s           r`   r2  r3    s    h ++-fdii((#M:F"==fEF=!V%7"a  444b9R9RSU9V9b9bcG wLL>V^abb{{<UCVZ_{``r   c                *   U R                   (       a?  [        5       nUR                  5       nU R                  XR                  UR
                  SS9$ U R                  [        U R                  U R                  5      U R                  U R
                  SS9$ )ap  Apply :class:`~qiskit.circuit.BreakLoopOp`.

.. warning::

    If you are using the context-manager "builder" forms of :meth:`.if_test`,
    :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are
    within a loop context, because otherwise the "resource width" of the operation cannot be
    determined.  This would quickly lead to invalid circuits, and so if you are trying to
    construct a reusable loop body (without the context managers), you must also use the
    non-context-manager form of :meth:`.if_test` and :meth:`.if_else`.  Take care that the
    :obj:`.BreakLoopOp` instruction must span all the resources of its containing loop, not
    just the immediate scope.

Returns:
    A handle to the instruction created.

Raises:
    CircuitError: if this method was called within a builder context, but not contained
        within a loop.
Fr   )	rx   r,   placeholder_resourcesr   r   r   r+   r  r  r   r  	resourcess      r`   
break_loopQuantumCircuit.break_loop  s|    * $$,.I!779I;;y*:*:I<L<LSX;YY{{94;;Z_  
 	
r   c                *   U R                   (       a?  [        5       nUR                  5       nU R                  XR                  UR
                  SS9$ U R                  [        U R                  U R                  5      U R                  U R
                  SS9$ )a  Apply :class:`~qiskit.circuit.ContinueLoopOp`.

.. warning::

    If you are using the context-manager "builder" forms of :meth:`.if_test`,
    :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are
    within a loop context, because otherwise the "resource width" of the operation cannot be
    determined.  This would quickly lead to invalid circuits, and so if you are trying to
    construct a reusable loop body (without the context managers), you must also use the
    non-context-manager form of :meth:`.if_test` and :meth:`.if_else`.  Take care that the
    :class:`~qiskit.circuit.ContinueLoopOp` instruction must span all the resources of its
    containing loop, not just the immediate scope.

Returns:
    A handle to the instruction created.

Raises:
    CircuitError: if this method was called within a builder context, but not contained
        within a loop.
Fr   )	rx   r0   r7  r   r   r   r/   r  r  r8  s      r`   continue_loopQuantumCircuit.continue_loop  s|    * $$/1I!779I;;y*:*:I<L<LSX;YY{{4??DOO<dkk4;;]b  
 	
r   c                @    U R                   " U6 U R                  " U6 -
  $ )aB  Return the duration between the start and stop time of the first and last instructions,
excluding delays, over the supplied qubits. Its time unit is ``self.unit``.

Args:
    *qubits: Qubits within ``self`` to include.

Returns:
    Return the duration between the first start and last stop time of non-delay instructions
)qubit_stop_timequbit_start_timer  s     r`   qubit_durationQuantumCircuit.qubit_duration*  s%     ##V,t/D/Df/MMMr   c                2   U R                   c>  U R                   H-  n[        UR                  [        5      (       a  M$  [        S5      e   gU Vs/ s H)  n[        U[        5      (       a  U R                  U   OUPM+     nnU Vs0 s H  o3S_M     nnU Vs0 s H  o3S_M     nnU R                   H  nU Hd  nX2R                  ;   d  M  [        UR                  [        5      (       a-  XS   (       d"  XC==   UR                  R                  -  ss'   M^  M`  SXS'   Mf     [        U5      [        UR                  5        Vs/ s H  of(       d  M  UPM     sn5      :X  d  M  [        S UR                  5        5       5      s  $    gs  snf s  snf s  snf s  snf )a  Return the start time of the first instruction, excluding delays,
over the supplied qubits. Its time unit is ``self.unit``.

Return 0 if there are no instructions over qubits

Args:
    *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating
    indices of ``self.qubits``.

Returns:
    Return the start time of the first instruction, excluding delays, over the qubits

Raises:
    CircuitError: if ``self`` is a not-yet scheduled circuit.
z<qubit_start_time undefined. Circuit must be scheduled first.r   FTc              3  $   #    U  H  ov   M     g 7frZ   rQ   )r^   starts     r`   ra   2QuantumCircuit.qubit_start_time.<locals>.<genexpr>\  s     >oU5o   )r   ry   r[   r  rC   r   re   r   r   r  r  min)r   r   r   r  startsdonesdones          r`   rA  QuantumCircuit.qubit_start_time6  sW     >>!#zz!+"7"7??&V   *
 GMNv!Jq#$6$6$++a.A=vN &'1Q$'#)*6aE6*::K***!+"7"7??$x"I)>)>)G)GGI  ( $(  6{cELLN"KNDd4N"KLL>fmmo>>> &  O'* #Ls   0FF
F 
FFc                   U R                   c>  U R                   H-  n[        UR                  [        5      (       a  M$  [        S5      e   gU Vs/ s H)  n[        U[        5      (       a  U R                  U   OUPM+     nnU Vs0 s H  o3U R                   _M     nnU Vs0 s H  o3S_M     nn[        U R                  5       H  nU Hd  nX2R                  ;   d  M  [        UR                  [        5      (       a-  XS   (       d"  XC==   UR                  R                  -  ss'   M^  M`  SXS'   Mf     [        U5      [        UR                  5        Vs/ s H  of(       d  M  UPM     sn5      :X  d  M  [        S UR                  5        5       5      s  $    [        U5      S:  a  [        UR                  5       5      $ gs  snf s  snf s  snf s  snf )a  Return the stop time of the last instruction, excluding delays, over the supplied qubits.
Its time unit is ``self.unit``.

Return 0 if there are no instructions over qubits

Args:
    *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating
    indices of ``self.qubits``.

Returns:
    Return the stop time of the last instruction, excluding delays, over the qubits

Raises:
    CircuitError: if ``self`` is a not-yet scheduled circuit.
z;qubit_stop_time undefined. Circuit must be scheduled first.r   FTc              3  $   #    U  H  ov   M     g 7frZ   rQ   )r^   stops     r`   ra   1QuantumCircuit.qubit_stop_time.<locals>.<genexpr>  s     ;ND4NrH  )r   ry   r[   r  rC   r   re   r   r  r   r  r  r  )r   r   r   r  stopsrK  rL  s          r`   r@  QuantumCircuit.qubit_stop_time`  s}     >>!#zz!+"7"7??&U   *
 GMNv!Jq#$6$6$++a.A=vN,23FqDNN"F3#)*6aE6*#DJJ/K***!+"7"7??$x!H(=(=(F(FFH  ( $(  6{cELLN"KNDd4N"KLL;ELLN;;; 0 u:>u||~&&% O3* #Ls   0G G"G

G!Gc                    SSK Jn  [        U" U 5      U5      nUS:X  a  U$ US:X  a  SSKJn  U" XAR
                  5      $ SSSS	S	S
SSSSSS.nX&;  a  [        SU S35      eXFU   -  $ )u  Estimate the duration of a scheduled circuit

This method computes the estimate of the circuit duration by finding
the longest duration path in the circuit based on the durations
provided by a given target. This method only works for simple circuits
that have no control flow or other classical feed-forward operations.

Args:
    target (Target): The :class:`.Target` instance that contains durations for
        the instructions if the target is missing duration data for any of the
        instructions in the circuit an :class:`.QiskitError` will be raised. This
        should be the same target object used as the target for transpilation.
    unit: The unit to return the duration in. This defaults to "s" for seconds
        but this can be a supported SI prefix for seconds returns. For example
        setting this to "n" will return in unit of nanoseconds. Supported values
        of this type are "f", "p", "n", "u", "µ", "m", "k", "M", "G", "T", and
        "P". Additionally, a value of "dt" is also accepted to output an integer
        in units of "dt". For this to function "dt" must be specified in the
        ``target``.

Returns:
    The estimated duration for the execution of a single shot of the circuit in
    the specified unit.

Raises:
    QiskitError: If the circuit is not scheduled or contains other
        details that prevent computing an estimated duration from
        (such as parameterized delay).
r   r   rX  rh   )duration_in_dtgV瞯<g-q=g&.>gư>gMbP?g     @@g    .Ag    eAg   mBg  4&kC)fr  nr     µmr   MGrK   PzSpecified unit: z1 is not a valid/supported SI prefix, 's', or 'dt')r   r   r   qiskit.circuit.durationrU  rh   r   )r   r  r   r   durrU  prefix_dicts          r`   estimate_duration QuantumCircuit.estimate_duration  s    < 	5()=vF3;J4<>!#yy11 
 ""4&(YZ  &&&r   )rz   rp   rv   rx   ry   r   r|   r   rw   r   rS   rT   rR   )r   Register | int | Sequence[Bit]rR   
str | NonerS   r<   rT   dict | NonerU   zIterable[expr.Var]rV   z!Iterable[expr.Var | expr.Stretch]rW   zCMapping[expr.Var, expr.Expr] | Iterable[Tuple[expr.Var, expr.Expr]])r   zint | float | None)FN)r   r   r   r  rR   rc  r  typing.Self)r   zIterable[CircuitInstruction | tuple[qiskit.circuit.Instruction] | tuple[qiskit.circuit.Instruction, Iterable[Qubit]] | tuple[qiskit.circuit.Instruction, Iterable[Qubit], Iterable[Clbit]]]r   Iterable[Qubit]r   Iterable[Clbit]rR   rc  rS   r<   rT   rd  r  'QuantumCircuit')r  zOptional[TranspileLayout])r  rA   )r   r   )r  z	list[int])r  r   )rT   r   )r  rs   )r  r  rZ   )r  re   )r  None)r  r%   r  r  )r  
int | Noner   r  r  r  )r  rh  )F)r3  r  r  rh  )r=  re   r7  r  r  rh  )FF)rH  floatrI  r  r3  r  r  rh  )r   NNF)
rQ  re   rR  rc  rS  str | int | Noner3  r  r  rh  )NNFFF)r   z$Union['QuantumCircuit', Instruction]r   0QubitSpecifier | Sequence[QubitSpecifier] | Noner   z0ClbitSpecifier | Sequence[ClbitSpecifier] | Noner  r  r  r  r  r  r   r  rX  zLMapping[str | expr.Var | expr.Stretch, str | expr.Var | expr.Stretch] | NonerY  r  r  Optional['QuantumCircuit'])r   rh  r  r  r  rn  )r  zdict[Clbit, BitLocations])r  zdict[Qubit, BitLocations])r  list[Qubit])r  list[Clbit])r  list[QuantumRegister])r   rq  )r  list[ClassicalRegister])r   rr  )r  zlist[AncillaQubit])r  ztyping.Iterable[expr.Var])r  ztyping.Iterable[expr.Stretch])r  z5typing.Iterable[typing.Union[expr.Var, expr.Stretch]])r  rh  r  rh  )r  rh  r  rh  )r  re   r  rB   )r  r  r  list[CircuitInstruction])r   rJ   r   zCallable[..., T]r  zUnion[S, T])r$  QubitSpecifierr  ro  )r(  ClbitSpecifierr  rp  )rQ   rQ   N)
r  r   r   Sequence[QubitSpecifier]r6  zSequence[ParameterValueType]rR  rc  r  r?   r  )
r   zOperation | CircuitInstructionr   Sequence[QubitSpecifier] | Noner   Sequence[ClbitSpecifier] | Noner   r  r  r?   )r   rB   r/  r  r  rB   )r   r@   r   Sequence[Qubit]r   zSequence[Clbit]r  r@   )rQ   rQ   r/  r  )rR   rs   rY  rK   r  zUnion[Parameter, T]).)rR   rs   rY  	type(...)r  r   )rR   rs   rY  
typing.Anyr  r   )rd  zstr | Parameterr  r  )rR   rs   rY  rK   r  zUnion[expr.Var, T])rR   rs   rY  r{  r  expr.Var)rR   rs   rY  r|  )rn  str | expr.Varr  r  )rR   rs   rY  rK   r  zUnion[expr.Stretch, T])rR   rs   rY  r{  r  expr.Stretch)rw  str | expr.Stretchr  r  )rR   rs   rY  rK   r  z!Union[expr.Var | expr.Stretch, T])rR   rs   rY  r{  r  r  )r  zstr | expr.Var | expr.Stretchr  r  )rn  r~  r   ztypes.Type | Noner  r}  )rw  r  r  r  )r   r|  rn  r~  r  r}  )r   r}  )r  r  )rn  rs   r   z
types.Typer  r}  )rn  r}  r   ri  r  r}  )r   rb  r  ri  )r'  zIterable[Bit]r  ri  )r  r   r  r   )r   ry  r  ri  )r  *dict[Parameter, ParameterValueType] | NonerR  rc  r  r   )r  r  rR  rc  r  r   r   )r  zBstr | Type[Instruction] | Sequence[str | Type[Instruction]] | Noner=  re   r  re  )NNNNFTNNmediumNTNNFNN   N)$r   rc  r  zfloat | Noner  rc  r  zdict | str | Noner  r  r  r  r.  bool | Noner  rc  r  rc  r  zbool | str | Noner  r  r  rj  r  z
Any | Noner  r  r  r  r  zlist[int] | Noner  re   r  r  )r  zCallable[..., int]r  re   )r  z$Callable[[CircuitInstruction], bool]r  re   )r  z'OrderedDict[Instruction, int]')rR   rs   r  rs  )r(  r  r  re   )rR   rc  r  re  )rR   rc  rn  z$Literal['alike', 'captures', 'drop']r  re  )rF  re   rR   rs   r  r$   )rF  re   rR   rs   r  r   )r   rt  r  r?   )r  r|  r  r|  r  r?   )r   rt  r[  ru  r  r?   )T)r  r  r  rn  )TT)r  r  r   r  r  rn  )r  rs   r  rh  )r  rs   r  rh  )r  r<   )r  r<   )r  r=   )r  zset[Parameter])
rG  KUnion[Mapping[Parameter, ParameterValueType], Iterable[ParameterValueType]]r  zLiteral[False]r  r  ry  r  r  rh  )
rG  r  r  zLiteral[True]r  r  ry  r  r  ri  )
rG  r  r  r  r  r  ry  r  r  rn  )r  &Mapping[Parameter, ParameterValueType]ry  r  r  r  )r   rt  r  r?   )r   z$Union[ParameterValueType, expr.Expr]r8  zQubitSpecifier | Noner   rc  r  r?   )
r  rt  r  rt  rR  rc  rS  rl  r  r?   )r  r<   r   rv  r  r?   )r  r<   r   rt  r  r?   )r  r<   r  rt  r  rt  rR  rc  rS  rl  r  r?   )
r  r<   r  rv  r  rt  rS  rl  r  r?   )r  r<   r  rv  r  rt  r  r  )NNF)r  r<   r  rv  r  rt  r  rm  r  rc  r  r  )r  r<   r  rv  r  rt  r  r  )r  r<   r  r<   r   rt  r  r?   )
r  r<   r  r<   r  r<   r   rt  r  r?   )r  rt  r  rt  r  rt  r  r?   )
r  rt  r  rt  r  rt  r  rt  r  r?   )r  r<   r   rt  rR  rc  r  r?   )r  r<   r1  rt  r2  rt  r  r?   )r  r<   r   rt  r  r?   )r1  rt  r2  rt  r  r?   )r  rt  rv  rt  rw  rt  rR  rc  rS  rl  r  r?   )
r  r<   r  r<   r  r<   r   rt  r  r?   )r  r<   r  r<   r  r<   r  r<   r  rt  r  rt  rR  rc  rS  rl  r  r?   )r   rt  rR  rc  r  r?   )
r  rt  r  rt  r  rt  rS  rl  r  r?   )NNN)r  rv  r  rt  r  rm  r  rc  rS  rl  r  r?   )r  rt  r  rt  r  rt  rR  rc  rS  rl  r  r?   )r  rs   r   rv  r  r?   )
r  +Statevector | Sequence[complex] | str | intr   rw  rR  rc  r  r  r  r?   )NF)r6  r  r   rw  r  r  )r	  z np.ndarray | Gate | BaseOperatorr   rv  rR  rc  )r   rt  )r  r)   )rQ   rQ   rQ   TN)
r   rf  r   rg  r  zIterable[Register]r  r  r   Optional[str])r  r*   )r  rB   ).NN)r   rw  r   rx  r  z,QuantumCircuit | typing.Iterable[Annotation]rR  rc  r   ri  r   z9Literal['dt', 's', 'ms', 'us', 'ns', 'ps', 'expr'] | Noner   ztyping.Iterable[Annotation])r}  1tuple[ClassicalRegister | Clbit, int] | expr.Exprr  ri  r   ri  r   ri  rR  rc  r  r8   )r}  r  r  rh  r   rv  r   Sequence[ClbitSpecifier]rR  rc  r  r?   )r  Iterable[int]r  zParameter | Noner  ri  r   ri  r   ri  rR  rc  r  r2   )r  r  r  zUnion[Parameter, None]r  rh  r   rv  r   r  rR  rc  r  r?   )NNNN)r}  %tuple[ClassicalRegister | Clbit, int]r  r4   )r}  r  r'  rh  r   rv  r   r  rR  rc  r  r?   )r}  zFtuple[ClassicalRegister, int] | tuple[Clbit, int] | tuple[Clbit, bool]r'  rh  r,  rh  r   rv  r   r  rR  rc  r  r?   )r  (Union[ClbitSpecifier, ClassicalRegister]r1  ri  r   ri  r   ri  rR  r  r  r6   )r  r  r1  z+Iterable[Tuple[typing.Any, QuantumCircuit]]r   rv  r   r  rR  r  r  r?   )r  r?   )r   zUnion[Qubit, int]r  rk  )rX  )r   rs   r  zint | float)rn   
__module____qualname____firstlineno____doc__r   r   r   propertyr   r   setterr   classmethodr   staticmethodr   r   r   r   rT   r   r   r   rt   r   rq   rr   r  r   r!  r.  r4  rA  rH  rP  r  r  r  r  r   r   r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r	  r  r  r  typingr   r  r!  r  r  r;  r   r   rZ  re  rh  ro  rr  rx  r{  r  r  r  r  r   r  r~   r}   r{   r   r)  r3  r:  r9  r  r   r  r  r  r  r  r  r  r!  r%  r3  r6  r9  r   r  r   rI  rO  rS  r  rZ  r_  rb  rp  r  r  rS   rG  rF  r  r  r  r  r<  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r%  r+  r3  r  r<  r@  rD  rH  rL  rP  rU  rX  r\  rc  rh  rl  rp  rx  r|  r  r  r  r  r  r  r  r  r  r  r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r>  r  r  r$  r-  r2  r:  r=  rB  rA  r@  r`  __static_attributes__rQ   r   r`   rN   rN      s0   Xt IF
  +, $%'68\^u-u u )	u
 u #u 4u Zun '4ESWX Y 
 __  '4ESWX Y  
[[  PT/3CM	   #%"$+, $2
2  2  2 2 )2 2 
2 2h 3 3j ( (4 
[[C C: V$ V$p  @ __" "-	
2    
  K"LUY L L\&PBH2 2h <A  : KP55*.5CG5	5r  ! '+'' ' %	'
 ' 
'X DHCG\)   %\)3\) A\) A	\)
 \) \) \) \) Y\) \) 
$\)|
Y Yv ) ) ) ) ! !
 ! !>    
 \\! !    
 \\! !  
 U U I I 2 2 ) ) , , 1 1 , , 1 1

.3+
d.3!
 
 __? ?__G G   JJ  +-/1  ( -	
  
8 2615	i i3i /i /	i i 
iX __!-!BF!	! !
 __  	
 
 DCQV DC DCL __N N __R R- -^
2 __G G __K K+ +ZC, __O O __S S& &PO& __] ] __.1,,"+,	&, ,
 BN:)2C	<" D\|5B __- -__5 5&JP __P P__V V GK)2C	:?:BB=~( EI HAH H 
	H: EI AAA A 
	A< !: O!:
 !: 
!:J ""##'!"$("+3(,  #"&'+&*+p
p
 p
 	p

 !p
 p
 p
 "p
 p
 )p
 &p
 p
 p
  !p
" #p
$  %p
& %'p
( )p
* $+p
h/
5+5
 
5(A
M3=M3
 
M3^" % % " "6 % %4%/	O= =~@	* $  < ;B	<< 8	<
 
<|.=F>ZCx @ 6:++.2+	#+ZU Un 
 
0 
 
, &' &'P 	, 	, A4 A4F + +0  #&
 _  
   
   "%
 _ 
   
  v+
 !v+_v+ v+
 v+ v+ 
$v+p0 W[EOS	/* 59  < '+	O6O $O 	O
 
O:G" !'+#
%#
 %#
 	#

 %#
 
#
JGK"Q& !'+%
!%
 &%
 %	%

 %
 %%
 
%
X (,

 1
 %	

 %
 

J !&<O!<O -<O !	<O
 <OF HL %bW!bW -bW !	bW
 EbW bW bWR !&+O+O -+O !	+O
 +OZQ'Q.@QIWQ	Q"HH H 	H
 H 
H6
&
 '
 %	

 

,
&
 '
 '	

 %
 

6 UYZ'Z0>ZGQZ	Z, !'+%
!%
 &%
 %	%

 %
 %%
 
%
NW'W1?WIWW	W$ UYZ'Z0>ZGQZ	Z, !'+%
!%
 &%
 %	%

 %
 %%
 
%
NW'W1?WIWW	W"K& !'+%
!%
 &%
 %	%

 %
 %%
 
%
NW'W1?WIWW	W"W'W1?WIWW	W"RGI" !'+#
%#
 %#
 	#

 %#
 
#
R !'+#
%#
 %#
 	#

 %#
 
#
J
"T$ !'+(
%(
 &(
 &	(

 (
 %(
 
(
THJ" !'+#
%#
 %#
 	#

 %#
 
#
JGIV!V  V  	V
 V 
V< !'+.
!.
  .
  	.

 ".
 &.
 %.
 .
 %.
 
.
`T T$ !'+&
%&
 %&
 	&

 %&
 
&
PR& (,%
&%
 '%
 %	%

 %%
 
%
N 4	 LP'+b]0b] %b] I	b]
 b] %b] 
b]b]HG" !'+&
%&
 %&
 	&

 %&
 
&
PG" !'+#
%#
 %#
 	#

 %#
 
#
T !'+(
&(
 '(
 %	(

 (
 %(
 
(
TLL )L 
	L* 37 w
:w
 0w
 	w

 w
 
w
x 37	sZ;sZ 0sZ 	sZr !	+9-+9 )+9 	+9Z"'H! #%"$(* +/

  
 &	

 
 )
>/
  MP2626td !JN36td 0	td
 0tdItd td td Htd 1tdl __D  	
   
  __D  )	
 )  
 =\RV =\~ __		 )	 		
 	 	 	 
	 	 __		 /	 		
 )	 )	 	 
	 	 MQB
[_B
H __Y Y__ !8 $ )	
 )  
  Vd Vd~ !7
Y7
 $7
 %	7

 )7
 )7
 7
 
7
r __8  	
   
  __8 ; )	
 )  
 CaD CaJ
:
<
N(T+Z9' 9'r   rN   c                  ~    \ rS rSrSrSS jr\S 5       rSS.SS jjrSS jr	S	 r
S
 rS rS rS rS rS rS rSrg)ru   i  rP   c                    Xl         g rZ   r  )r   rP   s     r`   r   $_OuterCircuitScopeInterface.__init__  s    r   c                .    U R                   R                  $ rZ   )rP   ry   r   s    r`   r   (_OuterCircuitScopeInterface.instructions  s    ||!!!r   Fr.  c               4    U R                   R                  XS9$ )Nr.  )rP   r   rO  s      r`   r   "_OuterCircuitScopeInterface.append  s    ||##K#OOr   c                    U R                   R                  R                  U5        S U R                   l        SU R                   l        g )Nrh   )rP   ry   r  r   r   )r   r   s     r`   r  "_OuterCircuitScopeInterface.extend  s2    !!$' $ r   c                   [        U[        5      (       a*  XR                  R                  ;  a  [	        SU S35      eU$ [        U[
        5      (       a*  XR                  R                  ;  a  [	        SU S35      eU$ [        U[        5      (       a$   U R                  R                  R                  U   $ [	        SU S35      e! [         a    [	        SU S35      S ef = f)NzClbit z  is not present in this circuit.z	Register zClassical bit index z is out-of-range.z'Unknown classical resource specifier: 'z'.)r[   r#   rP   r  r   r$   r   re   ry   r   
IndexError)r   	specifiers     r`   r1  6_OuterCircuitScopeInterface.resolve_classical_resource  s     i'' ; ;;"VI;6V#WXXi!233
  2 22"Yyk9Y#Z[[i%%b||))00;; DYKrRSS  b"%9)DU#VW]aabs   "C C"c                    U R                   R                  US 5      nU R                   R                  R                  U5        g rZ   )rP   r  ry   add_declared_varr  s     r`   r  1_OuterCircuitScopeInterface.add_uninitialized_var  s0    ll++C6++C0r   c                    U R                   R                  U5      nU R                   R                  R                  U5        g rZ   )rP   r  ry   add_declared_stretchr  s     r`   r  '_OuterCircuitScopeInterface.add_stretch  s.    ,,33G<//8r   c                L    U R                   R                  R                  U5      $ rZ   )rP   ry   rh  r   rR   s     r`   rh  #_OuterCircuitScopeInterface.get_var  s    ||!!))$//r   c                L    U R                   R                  R                  U5      $ rZ   )rP   ry   rr  r  s     r`   rr  '_OuterCircuitScopeInterface.get_stretch  s    ||!!--d33r   c                `    U R                  UR                  5      U:w  a  [        SU S35      eg Nr\  z ' is not present in this circuit)rh  rR   r   r  s     r`   r  #_OuterCircuitScopeInterface.use_var  s1    <<!S(3%'GHII )r   c                `    U R                  UR                  5      U:w  a  [        SU S35      eg r  )rr  rR   r   r  s     r`   r  '_OuterCircuitScopeInterface.use_stretch  s3    GLL)W47)+KLMM 5r   c                    g rZ   rQ   r  s     r`   r  %_OuterCircuitScopeInterface.use_qubit  s    r   N)rP   rN   rz  )r   r   )rn   r  r  r  	__slots__r   r  r   r   r  r1  r  r  rh  rr  r  r  r  r  rQ   r   r`   ru   ru     s^     I " " =B P!
T.1904JNr   ru   c                4   [        [        R                  " U5      5       Ht  n[        U[        R                  5      (       a  U R                  U5        M5  UR                  (       a  U R                  U5        MY  U R                  UR                  5        Mv     U$ rZ   )
r   r9   iter_identifiersr[   r_  r  r  r  r1  r   )r7  r  idents      r`   rE  rE    sm     T**401eT\\**%%e,%%e,88C 2 Kr   c                    [        U5      Ul        U R                  R                  5       Ul        [        R
                  " U R                  5      Ul        g rZ   )ru   rv   rz   r   r   r   r   )originalr<  s     r`   r@  r@  "  s;    237C&&++-CMNN8#5#56CMr   )r7  r)   r  	expr.Exprr  r  )~r  
__future__r   r  collections.abcr  r   r   r  r   r  r   r   r   r   r   r	   r
   r   r   r   r   r   r   mathr   numpyrD  qiskit._accelerate.circuitr   r   r   #qiskit._accelerate.circuit_durationr   qiskit.exceptionsr   qiskit.circuit.instructionr   qiskit.circuit.gater   qiskit.circuit.parameterr   qiskit.circuit.exceptionsr   qiskit.utilsr   r   r   r   r   r    r!   r"   r#   r$   r%   r&   controlflowr'   r(   controlflow.builderr)   r*   controlflow.break_loopr+   r,   controlflow.boxr-   r.   controlflow.continue_loopr/   r0   controlflow.for_loopr1   r2   controlflow.if_elser3   r4   controlflow.switch_caser5   r6   controlflow.while_loopr7   r8   	classicalr9   r:   parameterexpressionr;   r<   parametertabler=   parametervectorr>   instructionsetr?   r  r@   quantumcircuitdatarA   rB   r  rC   r  rD   TYPE_CHECKINGrz  qiskit.circuitrE   qiskit.transpiler.layoutrG   +qiskit.quantum_info.operators.base_operatorrH   &qiskit.quantum_info.states.statevectorrI   rJ   rK   re   r  rt  ru  rL   rN   ru   rE  r@  rQ   r   r`   <module>r     sj    "       #      2 3 3 J ) 2 $ . 2 6	 	 	 & 6 O E . N ; 4 @ A " H ) , *   F   
)8HB CLCL 		U5#:	! 		U5#:	! )UE
*Eu' Eu'PjE"7 EP"7r   