Skip to main contentIBM Quantum Documentation
This page is from an old version of Qiskit SDK. Go to the latest version

qiskit.circuit.library.TwoLocal

class TwoLocal(num_qubits=None, rotation_blocks=None, entanglement_blocks=None, entanglement='full', reps=3, skip_unentangled_qubits=False, skip_final_rotation_layer=False, parameter_prefix='θ', insert_barriers=False, initial_state=None)

GitHub

The two-local circuit.

The two-local circuit is a parameterized circuit consisting of alternating rotation layers and entanglement layers. The rotation layers are single qubit gates applied on all qubits. The entanglement layer uses two-qubit gates to entangle the qubits according to a strategy set using entanglement. Both the rotation and entanglement gates can be specified as string (e.g. 'ry' or 'cx'), as gate-type (e.g. RYGate or CXGate) or as QuantumCircuit (e.g. a 1-qubit circuit or 2-qubit circuit).

A set of default entanglement strategies is provided:

  • 'full' entanglement is each qubit is entangled with all the others.
  • 'linear' entanglement is qubit ii entangled with qubit i+1i + 1, for all i{0,1,...,n2}i \in \{0, 1, ... , n - 2\}, where nn is the total number of qubits.
  • 'circular' entanglement is linear entanglement but with an additional entanglement of the first and last qubit before the linear part.
  • 'sca' (shifted-circular-alternating) entanglement is a generalized and modified version of the proposed circuit 14 in Sim et al.. It consists of circular entanglement where the ‘long’ entanglement connecting the first with the last qubit is shifted by one each block. Furthermore the role of control and target qubits are swapped every block (therefore alternating).

The entanglement can further be specified using an entangler map, which is a list of index pairs, such as

>>> entangler_map = [(0, 1), (1, 2), (2, 0)]

If different entanglements per block should be used, provide a list of entangler maps. See the examples below on how this can be used.

>>> entanglement = [entangler_map_layer_1, entangler_map_layer_2, ... ]

Barriers can be inserted in between the different layers for better visualization using the insert_barriers attribute.

For each parameterized gate a new parameter is generated using a ParameterVector. The name of these parameters can be chosen using the parameter_prefix.

Examples

>>> two = TwoLocal(3, 'ry', 'cx', 'linear', reps=2, insert_barriers=True)
>>> print(two)  # decompose the layers into standard gates
     ┌──────────┐ ░            ░ ┌──────────┐ ░            ░ ┌──────────┐
q_0:Ry(θ[0]) ├─░───■────────░─┤ Ry(θ[3]) ├─░───■────────░─┤ Ry(θ[6])
     ├──────────┤ ░ ┌─┴─┐      ░ ├──────────┤ ░ ┌─┴─┐      ░ ├──────────┤
q_1:Ry(θ[1]) ├─░─┤ X ├──■───░─┤ Ry(θ[4]) ├─░─┤ X ├──■───░─┤ Ry(θ[7])
     ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤
q_2:Ry(θ[2]) ├─░──────┤ X ├─░─┤ Ry(θ[5]) ├─░──────┤ X ├─░─┤ Ry(θ[8])
     └──────────┘ ░      └───┘ ░ └──────────┘ ░      └───┘ ░ └──────────┘
>>> two = TwoLocal(3, ['ry','rz'], 'cz', 'full', reps=1, insert_barriers=True)
>>> qc = QuantumCircuit(3)
>>> qc += two
>>> print(qc.decompose().draw())
     ┌──────────┐┌──────────┐ ░           ░ ┌──────────┐ ┌──────────┐
q_0:Ry(θ[0]) ├┤ Rz(θ[3]) ├─░──■──■─────░─┤ Ry(θ[6]) ├─┤ Rz(θ[9])
     ├──────────┤├──────────┤ ░  │  │     ░ ├──────────┤┌┴──────────┤
q_1:Ry(θ[1]) ├┤ Rz(θ[4]) ├─░──■──┼──■──░─┤ Ry(θ[7]) ├┤ Rz(θ[10])
     ├──────────┤├──────────┤ ░     │  │  ░ ├──────────┤├───────────┤
q_2:Ry(θ[2]) ├┤ Rz(θ[5]) ├─░─────■──■──░─┤ Ry(θ[8]) ├┤ Rz(θ[11])
     └──────────┘└──────────┘ ░           ░ └──────────┘└───────────┘
>>> entangler_map = [[0, 1], [1, 2], [2, 0]]  # circular entanglement for 3 qubits
>>> two = TwoLocal(3, 'x', 'crx', entangler_map, reps=1)
>>> print(two)  # note: no barriers inserted this time!
        ┌───┐                             ┌──────────┐┌───┐
q_0: |0>┤ X ├─────■───────────────────────┤ Rx(θ[2]) ├┤ X ├
        ├───┤┌────┴─────┐            ┌───┐└─────┬────┘└───┘
q_1: |0>┤ X ├┤ Rx(θ[0]) ├─────■──────┤ X ├──────┼──────────
        ├───┤└──────────┘┌────┴─────┐└───┘      │     ┌───┐
q_2: |0>┤ X ├────────────┤ Rx(θ[1]) ├───────────■─────┤ X ├
        └───┘            └──────────┘                 └───┘
>>> entangler_map = [[0, 3], [0, 2]]  # entangle the first and last two-way
>>> two = TwoLocal(4, [], 'cry', entangler_map, reps=1)
>>> circuit = two + two
>>> print(circuit.decompose().draw())  # note, that the parameters are the same!
q_0: ─────■───────────■───────────■───────────■──────
          │           │           │           │
q_1: ─────┼───────────┼───────────┼───────────┼──────
          │      ┌────┴─────┐     │      ┌────┴─────┐
q_2: ─────┼──────┤ Ry(θ[1]) ├─────┼──────┤ Ry(θ[1])
     ┌────┴─────┐└──────────┘┌────┴─────┐└──────────┘
q_3:Ry(θ[0]) ├────────────┤ Ry(θ[0]) ├────────────
     └──────────┘            └─────────
>>> layer_1 = [(0, 1), (0, 2)]
>>> layer_2 = [(1, 2)]
>>> two = TwoLocal(3, 'x', 'cx', [layer_1, layer_2], reps=2, insert_barriers=True)
>>> print(two)
     ┌───┐ ░            ░ ┌───┐ ░       ░ ┌───┐
q_0: ┤ X ├─░───■────■───░─┤ X ├─░───────░─┤ X ├
     ├───┤ ░ ┌─┴─┐  │   ░ ├───┤ ░       ░ ├───┤
q_1: ┤ X ├─░─┤ X ├──┼───░─┤ X ├─░───■───░─┤ X ├
     ├───┤ ░ └───┘┌─┴─┐ ░ ├───┤ ░ ┌─┴─┐ ░ ├───┤
q_2: ┤ X ├─░──────┤ X ├─░─┤ X ├─░─┤ X ├─░─┤ X ├
     └───┘ ░      └───┘ ░ └───┘ ░ └───┘ ░ └───┘

Construct a new two-local circuit.

Parameters

  • num_qubits (Optional[int]) – The number of qubits of the two-local circuit.
  • rotation_blocks (Union[str, List[str], type, List[type], QuantumCircuit, List[QuantumCircuit], None]) – The gates used in the rotation layer. Can be specified via the name of a gate (e.g. ‘ry’) or the gate type itself (e.g. RYGate). If only one gate is provided, the gate same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order. See the Examples section for more detail.
  • entanglement_blocks (Union[str, List[str], type, List[type], QuantumCircuit, List[QuantumCircuit], None]) – The gates used in the entanglement layer. Can be specified in the same format as rotation_blocks.
  • entanglement (Union[str, List[List[int]], Callable[[int], List[int]]]) – Specifies the entanglement structure. Can be a string (‘full’, ‘linear’ , ‘circular’ or ‘sca’), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to ‘full’ entanglement. See the Examples section for more detail.
  • reps (int) – Specifies how often a block consisting of a rotation layer and entanglement layer is repeated.
  • skip_unentangled_qubits (bool) – If True, the single qubit gates are only applied to qubits that are entangled with another qubit. If False, the single qubit gates are applied to each qubit in the Ansatz. Defaults to False.
  • skip_final_rotation_layer (bool) – If False, a rotation layer is added at the end of the ansatz. If True, no rotation layer is added.
  • parameter_prefix (str) – The parameterized gates require a parameter to be defined, for which we use instances of qiskit.circuit.Parameter. The name of each parameter will be this specified prefix plus its index.
  • insert_barriers (bool) – If True, barriers are inserted in between each layer. If False, no barriers are inserted. Defaults to False.
  • initial_state (Optional[Any]) – An InitialState object to prepend to the circuit.

__init__

__init__(num_qubits=None, rotation_blocks=None, entanglement_blocks=None, entanglement='full', reps=3, skip_unentangled_qubits=False, skip_final_rotation_layer=False, parameter_prefix='θ', insert_barriers=False, initial_state=None)

Construct a new two-local circuit.

Parameters

  • num_qubits (Optional[int]) – The number of qubits of the two-local circuit.
  • rotation_blocks (Union[str, List[str], type, List[type], QuantumCircuit, List[QuantumCircuit], None]) – The gates used in the rotation layer. Can be specified via the name of a gate (e.g. ‘ry’) or the gate type itself (e.g. RYGate). If only one gate is provided, the gate same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order. See the Examples section for more detail.
  • entanglement_blocks (Union[str, List[str], type, List[type], QuantumCircuit, List[QuantumCircuit], None]) – The gates used in the entanglement layer. Can be specified in the same format as rotation_blocks.
  • entanglement (Union[str, List[List[int]], Callable[[int], List[int]]]) – Specifies the entanglement structure. Can be a string (‘full’, ‘linear’ , ‘circular’ or ‘sca’), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to ‘full’ entanglement. See the Examples section for more detail.
  • reps (int) – Specifies how often a block consisting of a rotation layer and entanglement layer is repeated.
  • skip_unentangled_qubits (bool) – If True, the single qubit gates are only applied to qubits that are entangled with another qubit. If False, the single qubit gates are applied to each qubit in the Ansatz. Defaults to False.
  • skip_final_rotation_layer (bool) – If False, a rotation layer is added at the end of the ansatz. If True, no rotation layer is added.
  • parameter_prefix (str) – The parameterized gates require a parameter to be defined, for which we use instances of qiskit.circuit.Parameter. The name of each parameter will be this specified prefix plus its index.
  • insert_barriers (bool) – If True, barriers are inserted in between each layer. If False, no barriers are inserted. Defaults to False.
  • initial_state (Optional[Any]) – An InitialState object to prepend to the circuit.

Methods

__init__([num_qubits, rotation_blocks, …])Construct a new two-local circuit.
add_calibration(gate, qubits, schedule[, params])Register a low-level, custom pulse definition for the given gate.
add_layer(other[, entanglement, front])Append another layer to the NLocal.
add_register(*regs)Add registers.
append(instruction[, qargs, cargs])Append one or more instructions to the end of the circuit, modifying the circuit in place.
assign_parameters(param_dict[, inplace])Assign parameters to the n-local circuit.
barrier(*qargs)Apply Barrier.
bind_parameters(value_dict)Assign numeric parameters to values yielding a new circuit.
cast(value, _type)Best effort to cast value to type.
cbit_argument_conversion(clbit_representation)Converts several classical bit representations (such as indexes, range, etc.) into a list of classical bits.
ccx(control_qubit1, control_qubit2, target_qubit)Apply CCXGate.
ch(control_qubit, target_qubit[, label, …])Apply CHGate.
cls_instances()Return the current number of instances of this class, useful for auto naming.
cls_prefix()Return the prefix to use for auto naming.
cnot(control_qubit, target_qubit[, label, …])Apply CXGate.
combine(rhs)Append rhs to self if self contains compatible registers.
compose(other[, qubits, clbits, front, inplace])Compose circuit with other circuit or instruction, optionally permuting wires.
control([num_ctrl_qubits, label, ctrl_state])Control this circuit on num_ctrl_qubits qubits.
copy([name])Copy the circuit.
count_ops()Count each operation kind in the circuit.
cp(theta, control_qubit, target_qubit[, …])Apply CPhaseGate.
crx(theta, control_qubit, target_qubit[, …])Apply CRXGate.
cry(theta, control_qubit, target_qubit[, …])Apply CRYGate.
crz(theta, control_qubit, target_qubit[, …])Apply CRZGate.
cswap(control_qubit, target_qubit1, …[, …])Apply CSwapGate.
csx(control_qubit, target_qubit[, label, …])Apply CSXGate.
cu(theta, phi, lam, gamma, control_qubit, …)Apply CUGate.
cu1(theta, control_qubit, target_qubit[, …])Apply CU1Gate.
cu3(theta, phi, lam, control_qubit, target_qubit)Apply CU3Gate.
cx(control_qubit, target_qubit[, label, …])Apply CXGate.
cy(control_qubit, target_qubit[, label, …])Apply CYGate.
cz(control_qubit, target_qubit[, label, …])Apply CZGate.
dcx(qubit1, qubit2)Apply DCXGate.
decompose()Call a decomposition pass on this circuit, to decompose one level (shallow decompose).
delay(duration[, qarg, unit])Apply Delay.
depth()Return circuit depth (i.e., length of critical path).
diag_gate(diag, qubit)Deprecated version of QuantumCircuit.diagonal.
diagonal(diag, qubit)Attach a diagonal gate to a circuit.
draw([output, scale, filename, style, …])Draw the quantum circuit.
extend(rhs)Append QuantumCircuit to the right hand side if it contains compatible registers.
fredkin(control_qubit, target_qubit1, …)Apply CSwapGate.
from_qasm_file(path)Take in a QASM file and generate a QuantumCircuit object.
from_qasm_str(qasm_str)Take in a QASM string and generate a QuantumCircuit object.
get_entangler_map(rep_num, block_num, …)Overloading to handle the special case of 1 qubit where the entanglement are ignored.
get_unentangled_qubits()Get the indices of unentangled qubits in a set.
h(qubit)Apply HGate.
hamiltonian(operator, time, qubits[, label])Apply hamiltonian evolution to to qubits.
has_register(register)Test if this circuit has the register r.
i(qubit)Apply IGate.
id(qubit)Apply IGate.
initialize(params, qubits)Apply initialize to circuit.
inverse()Invert (take adjoint of) this circuit.
iso(isometry, q_input, q_ancillas_for_output)Attach an arbitrary isometry from m to n qubits to a circuit.
isometry(isometry, q_input, …[, …])Attach an arbitrary isometry from m to n qubits to a circuit.
iswap(qubit1, qubit2)Apply iSwapGate.
mcmt(gate, control_qubits, target_qubits[, …])Apply a multi-control, multi-target using a generic gate.
mcp(lam, control_qubits, target_qubit)Apply MCPhaseGate.
mcrx(theta, q_controls, q_target[, …])Apply Multiple-Controlled X rotation gate
mcry(theta, q_controls, q_target, q_ancillae)Apply Multiple-Controlled Y rotation gate
mcrz(lam, q_controls, q_target[, …])Apply Multiple-Controlled Z rotation gate
mct(control_qubits, target_qubit[, …])Apply MCXGate.
mcu1(lam, control_qubits, target_qubit)Apply MCU1Gate.
mcx(control_qubits, target_qubit[, …])Apply MCXGate.
measure(qubit, cbit)Measure quantum bit into classical bit (tuples).
measure_active([inplace])Adds measurement to all non-idle qubits.
measure_all([inplace])Adds measurement to all qubits.
mirror()DEPRECATED: use circuit.reverse_ops().
ms(theta, qubits)Apply MSGate.
num_connected_components([unitary_only])How many non-entangled subcircuits can the circuit be factored to.
num_nonlocal_gates()Return number of non-local gates (i.e.
num_tensor_factors()Computes the number of tensor factors in the unitary (quantum) part of the circuit only.
num_unitary_factors()Computes the number of tensor factors in the unitary (quantum) part of the circuit only.
p(theta, qubit)Apply PhaseGate.
power(power[, matrix_power])Raise this circuit to the power of power.
print_settings()Returns information about the setting.
qasm([formatted, filename])Return OpenQASM string.
qbit_argument_conversion(qubit_representation)Converts several qubit representations (such as indexes, range, etc.) into a list of qubits.
qubit_duration(*qubits)Return the duration between the start and stop time of the first and last instructions, excluding delays, over the supplied qubits.
qubit_start_time(*qubits)Return the start time of the first instruction, excluding delays, over the supplied qubits.
qubit_stop_time(*qubits)Return the stop time of the last instruction, excluding delays, over the supplied qubits.
r(theta, phi, qubit)Apply RGate.
rcccx(control_qubit1, control_qubit2, …)Apply RC3XGate.
rccx(control_qubit1, control_qubit2, …)Apply RCCXGate.
remove_final_measurements([inplace])Removes final measurement on all qubits if they are present.
repeat(reps)Repeat this circuit reps times.
reset(qubit)Reset q.
reverse_bits()Return a circuit with the opposite order of wires.
reverse_ops()Reverse the circuit by reversing the order of instructions.
rx(theta, qubit[, label])Apply RXGate.
rxx(theta, qubit1, qubit2)Apply RXXGate.
ry(theta, qubit[, label])Apply RYGate.
ryy(theta, qubit1, qubit2)Apply RYYGate.
rz(phi, qubit)Apply RZGate.
rzx(theta, qubit1, qubit2)Apply RZXGate.
rzz(theta, qubit1, qubit2)Apply RZZGate.
s(qubit)Apply SGate.
sdg(qubit)Apply SdgGate.
size()Returns total number of gate operations in circuit.
snapshot(label[, snapshot_type, qubits, params])Take a statevector snapshot of the internal simulator representation.
snapshot_density_matrix(label[, qubits])Take a density matrix snapshot of simulator state.
snapshot_expectation_value(label, op, qubits)Take a snapshot of expectation value <O> of an Operator.
snapshot_probabilities(label, qubits[, variance])Take a probability snapshot of the simulator state.
snapshot_stabilizer(label)Take a stabilizer snapshot of the simulator state.
snapshot_statevector(label)Take a statevector snapshot of the simulator state.
squ(unitary_matrix, qubit[, mode, …])Decompose an arbitrary 2*2 unitary into three rotation gates.
swap(qubit1, qubit2)Apply SwapGate.
sx(qubit)Apply SXGate.
sxdg(qubit)Apply SXdgGate.
t(qubit)Apply TGate.
tdg(qubit)Apply TdgGate.
to_gate([parameter_map, label])Create a Gate out of this circuit.
to_instruction([parameter_map])Create an Instruction out of this circuit.
toffoli(control_qubit1, control_qubit2, …)Apply CCXGate.
u(theta, phi, lam, qubit)Apply UGate.
u1(theta, qubit)Apply U1Gate.
u2(phi, lam, qubit)Apply U2Gate.
u3(theta, phi, lam, qubit)Apply U3Gate.
uc(gate_list, q_controls, q_target[, …])Attach a uniformly controlled gates (also called multiplexed gates) to a circuit.
ucrx(angle_list, q_controls, q_target)Attach a uniformly controlled (also called multiplexed) Rx rotation gate to a circuit.
ucry(angle_list, q_controls, q_target)Attach a uniformly controlled (also called multiplexed) Ry rotation gate to a circuit.
ucrz(angle_list, q_controls, q_target)Attach a uniformly controlled (also called multiplexed gates) Rz rotation gate to a circuit.
unitary(obj, qubits[, label])Apply unitary gate to q.
width()Return number of qubits plus clbits in circuit.
x(qubit[, label])Apply XGate.
y(qubit)Apply YGate.
z(qubit)Apply ZGate.

Attributes

ancillasReturns a list of ancilla bits in the order that the registers were added.
calibrationsReturn calibration dictionary.
clbitsReturns a list of classical bits in the order that the registers were added.
dataReturn the circuit data (instructions and context).
entanglementGet the entanglement strategy.
entanglement_blocksThe blocks in the entanglement layers.
extension_lib
global_phaseReturn the global phase of the circuit in radians.
header
initial_stateReturn the initial state that is added in front of the n-local circuit.
insert_barriersIf barriers are inserted in between the layers or not.
instances
num_ancillasReturn the number of ancilla qubits.
num_clbitsReturn number of classical bits.
num_layersReturn the number of layers in the n-local circuit.
num_parametersConvenience function to get the number of parameter objects in the circuit.
num_parameters_settableThe number of total parameters that can be set to distinct values.
num_qubitsReturns the number of qubits in this circuit.
ordered_parametersThe parameters used in the underlying circuit.
parameter_boundsThe parameter bounds for the unbound parameters in the circuit.
parametersGet the Parameter objects in the circuit.
preferred_init_pointsThe initial points for the parameters.
prefix
qregsA list of the quantum registers associated with the circuit.
qubitsReturns a list of quantum bits in the order that the registers were added.
repsThe number of times rotation and entanglement block are repeated.
rotation_blocksThe blocks in the rotation layers.

add_calibration

add_calibration(gate, qubits, schedule, params=None)

Register a low-level, custom pulse definition for the given gate.

Parameters

  • gate (Union[Gate, str]) – Gate information.
  • qubits (Union[int, Tuple[int]]) – List of qubits to be measured.
  • schedule (Schedule) – Schedule information.
  • params (Optional[List[Union[float, Parameter]]]) – A list of parameters.

Raises

Exception – if the gate is of type string and params is None.

add_layer

add_layer(other, entanglement=None, front=False)

Append another layer to the NLocal.

Parameters

  • other (Union[NLocal, Instruction, QuantumCircuit]) – The layer to compose, can be another NLocal, an Instruction or Gate, or a QuantumCircuit.
  • entanglement (Union[List[int], str, List[List[int]], None]) – The entanglement or qubit indices.
  • front (bool) – If True, other is appended to the front, else to the back.

Return type

NLocal

Returns

self, such that chained composes are possible.

Raises

TypeError – If other is not compatible, i.e. is no Instruction and does not have a to_instruction method.

add_register

add_register(*regs)

Add registers.

ancillas

Returns a list of ancilla bits in the order that the registers were added.

append

append(instruction, qargs=None, cargs=None)

Append one or more instructions to the end of the circuit, modifying the circuit in place. Expands qargs and cargs.

Parameters

  • instruction (qiskit.circuit.Instruction) – Instruction instance to append
  • qargs (list(argument)) – qubits to attach instruction to
  • cargs (list(argument)) – clbits to attach instruction to

Returns

a handle to the instruction that was just added

Return type

qiskit.circuit.Instruction

Raises

  • CircuitError – if object passed is a subclass of Instruction
  • CircuitError – if object passed is neither subclass nor an instance of Instruction

assign_parameters

assign_parameters(param_dict, inplace=False)

Assign parameters to the n-local circuit.

This method also supports passing a list instead of a dictionary. If a list is passed, the list must have the same length as the number of unbound parameters in the circuit. The parameters are assigned in the order of the parameters in ordered_parameters().

Return type

Optional[QuantumCircuit]

Returns

A copy of the NLocal circuit with the specified parameters.

Raises

AttributeError – If the parameters are given as list and do not match the number of parameters.

barrier

barrier(*qargs)

Apply Barrier. If qargs is None, applies to all.

bind_parameters

bind_parameters(value_dict)

Assign numeric parameters to values yielding a new circuit.

To assign new Parameter objects or bind the values in-place, without yielding a new circuit, use the assign_parameters() method.

Parameters

value_dict (dict) – {parameter: value, …}

Raises

  • CircuitError – If value_dict contains parameters not present in the circuit
  • TypeError – If value_dict contains a ParameterExpression in the values.

Returns

copy of self with assignment substitution.

Return type

QuantumCircuit

calibrations

Return calibration dictionary.

The custom pulse definition of a given gate is of the form

{‘gate_name’: {(qubits, params): schedule}}

cast

static cast(value, _type)

Best effort to cast value to type. Otherwise, returns the value.

cbit_argument_conversion

cbit_argument_conversion(clbit_representation)

Converts several classical bit representations (such as indexes, range, etc.) into a list of classical bits.

Parameters

clbit_representation (Object) – representation to expand

Returns

Where each tuple is a classical bit.

Return type

List(tuple)

ccx

ccx(control_qubit1, control_qubit2, target_qubit)

Apply CCXGate.

ch

ch(control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CHGate.

clbits

Returns a list of classical bits in the order that the registers were added.

cls_instances

classmethod cls_instances()

Return the current number of instances of this class, useful for auto naming.

cls_prefix

classmethod cls_prefix()

Return the prefix to use for auto naming.

cnot

cnot(control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CXGate.

combine

combine(rhs)

Append rhs to self if self contains compatible registers.

Two circuits are compatible if they contain the same registers or if they contain different registers with unique names. The returned circuit will contain all unique registers between both circuits.

Return self + rhs as a new object.

Parameters

rhs (QuantumCircuit) – The quantum circuit to append to the right hand side.

Returns

Returns a new QuantumCircuit object

Return type

QuantumCircuit

Raises

QiskitError – if the rhs circuit is not compatible

compose

compose(other, qubits=None, clbits=None, front=False, inplace=False)

Compose circuit with other circuit or instruction, optionally permuting wires.

other can be narrower or of equal width to self.

Parameters

  • other (qiskit.circuit.Instruction orQuantumCircuit or BaseOperator) – (sub)circuit to compose onto self.
  • 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 (not implemented yet).
  • inplace (bool) – If True, modify the object. Otherwise return composed circuit.

Returns

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

Return type

QuantumCircuit

Raises

  • CircuitError – if composing on the front.
  • QiskitError – if other is wider or there are duplicate edge mappings.

Examples

>>> lhs.compose(rhs, qubits=[3, 2], inplace=True)
            ┌───┐                   ┌─────┐                ┌───┐
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 ═══════════════════════

control

control(num_ctrl_qubits=1, label=None, ctrl_state=None)

Control this circuit on num_ctrl_qubits qubits.

Parameters

  • 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.

Returns

The controlled version of this circuit.

Return type

QuantumCircuit

Raises

CircuitError – If the circuit contains a non-unitary operation and cannot be controlled.

copy

copy(name=None)

Copy the circuit.

Parameters

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

Returns

a deepcopy of the current circuit, with the specified name

Return type

QuantumCircuit

count_ops

count_ops()

Count each operation kind in the circuit.

Returns

a breakdown of how many operations of each kind, sorted by amount.

Return type

OrderedDict

cp

cp(theta, control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CPhaseGate.

crx

crx(theta, control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CRXGate.

cry

cry(theta, control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CRYGate.

crz

crz(theta, control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CRZGate.

cswap

cswap(control_qubit, target_qubit1, target_qubit2, label=None, ctrl_state=None)

Apply CSwapGate.

csx

csx(control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CSXGate.

cu

cu(theta, phi, lam, gamma, control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CUGate.

cu1

cu1(theta, control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CU1Gate.

cu3

cu3(theta, phi, lam, control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CU3Gate.

cx

cx(control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CXGate.

cy

cy(control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CYGate.

cz

cz(control_qubit, target_qubit, label=None, ctrl_state=None)

Apply CZGate.

data

Return the circuit data (instructions and context).

Returns

a list-like object containing the tuples for the circuit’s data.

Each tuple is in the format (instruction, qargs, cargs), where instruction is an Instruction (or subclass) object, qargs is a list of Qubit objects, and cargs is a list of Clbit objects.

Return type

QuantumCircuitData

dcx

dcx(qubit1, qubit2)

Apply DCXGate.

decompose

decompose()

Call a decomposition pass on this circuit, to decompose one level (shallow decompose).

Returns

a circuit one level decomposed

Return type

QuantumCircuit

delay

delay(duration, qarg=None, unit='dt')

Apply Delay. If qarg is None, applies to all qubits. When applying to multiple qubits, delays with the same duration will be created.

Parameters

  • duration (int or float) – duration of the delay.
  • qarg (Object) – qubit argument to apply this delay.
  • unit (str) – unit of the duration. Supported units: ‘s’, ‘ms’, ‘us’, ‘ns’, ‘ps’, ‘dt’. Default is dt, i.e. integer time unit depending on the target backend.

Returns

the attached delay instruction.

Return type

qiskit.Instruction

Raises

CircuitError – if arguments have bad format.

depth

depth()

Return circuit depth (i.e., length of critical path). This does not include compiler or simulator directives such as ‘barrier’ or ‘snapshot’.

Returns

Depth of circuit.

Return type

int

Notes

The circuit depth and the DAG depth need not be the same.

diag_gate

diag_gate(diag, qubit)

Deprecated version of QuantumCircuit.diagonal.

diagonal

diagonal(diag, qubit)

Attach a diagonal gate to a circuit.

The decomposition is based on Theorem 7 given in “Synthesis of Quantum Logic Circuits” by Shende et al. (https://arxiv.org/pdf/quant-ph/0406176.pdf).

Parameters

  • diag (list) – list of the 2^k diagonal entries (for a diagonal gate on k qubits). Must contain at least two entries
  • qubit (QuantumRegister|list) – list of k qubits the diagonal is acting on (the order of the qubits specifies the computational basis in which the diagonal gate is provided: the first element in diag acts on the state where all the qubits in q are in the state 0, the second entry acts on the state where all the qubits q[1],…,q[k-1] are in the state zero and q[0] is in the state 1, and so on)

Returns

the diagonal gate which was attached to the circuit.

Return type

QuantumCircuit

Raises

QiskitError – if the list of the diagonal entries or the qubit list is in bad format; if the number of diagonal entries is not 2^k, where k denotes the number of qubits

draw

draw(output=None, scale=None, filename=None, style=None, interactive=False, plot_barriers=True, reverse_bits=False, justify=None, vertical_compression='medium', idle_wires=True, with_layout=True, fold=None, ax=None, initial_state=False, cregbundle=True)

Draw the quantum circuit.

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

latex: high-quality images compiled via LaTeX.

latex_source: raw uncompiled LaTeX output.

matplotlib: images with color rendered purely in Python.

Parameters

  • output (str) – Select the output method to use for drawing the circuit. Valid choices are text, latex, latex_source, or mpl. By default the ‘text’ drawer is used unless a user config file has an alternative backend set as the default. If the output kwarg is set, that backend will always be used over the default in a user config file.
  • scale (float) – scale of image to draw (shrink if < 1)
  • filename (str) – file path to save image to
  • style (dict or str) – dictionary of style or file name of style file. This option is only used by the mpl output type. If a str is passed in that is the path to a json file which contains a dictionary of style, then that will be opened, parsed, and used as the input dict. See: Style Dict Doc for more information on the contents.
  • interactive (bool) – when set 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.
  • reverse_bits (bool) – When set to True, reverse the bit order inside registers for the output visualization.
  • plot_barriers (bool) – Enable/disable drawing barriers in the output circuit. Defaults to True.
  • justify (string) – Options are left, right or none. If anything else is supplied it defaults to left justified. 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.
  • vertical_compression (string) – 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 (bool) – Include idle wires (wires with no circuit elements) in output visualization. Default is True.
  • with_layout (bool) – Include layout information, with labels on the physical layout. Default is True.
  • fold (int) – 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 is the number of (visual) layers before folding. Default is 25.
  • ax (matplotlib.axes.Axes) – An optional 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. This is only used when the output kwarg is set to use the mpl backend. It will be silently ignored with all other outputs.
  • initial_state (bool) – Optional. Adds |0> in the beginning of the wire. Only used by the text, latex and latex_source outputs. Default: False.
  • cregbundle (bool) – Optional. If set True bundle classical registers. Not used by the matplotlib output. Default: True.

Returns

PIL.Image or matplotlib.figure or str or TextDrawing:

  • PIL.Image (output=’latex’)

    an in-memory representation of the image of the circuit diagram.

  • matplotlib.figure.Figure (output=’mpl’)

    a matplotlib figure object for the circuit diagram.

  • str (output=’latex_source’)

    The LaTeX source code for visualizing the circuit diagram.

  • TextDrawing (output=’text’)

    A drawing that can be printed as ASCII art.

Raises

  • VisualizationError – when an invalid output method is selected
  • ImportError – when the output methods require non-installed libraries

Style Dict Details

The style dict kwarg contains numerous options that define the style of the output circuit visualization. The style dict is only used by the mpl output. The options available in the style dict are defined below:

Parameters

  • name (str) – The name of the style. The name can be set to ‘iqx’, ‘bw’, or ‘default’. This overrides the setting in the ‘~/.qiskit/settings.conf’ file.

  • textcolor (str) – The color code to use for text. Defaults to ‘#000000’

  • subtextcolor (str) – The color code to use for subtext. Defaults to ‘#000000’

  • linecolor (str) – The color code to use for lines. Defaults to ‘#000000’

  • creglinecolor (str) – The color code to use for classical register lines. Defaults to ‘#778899’

  • gatetextcolor (str) – The color code to use for gate text. Defaults to ‘#000000’

  • gatefacecolor (str) – The color code to use for gates. Defaults to ‘#ffffff’

  • barrierfacecolor (str) – The color code to use for barriers. Defaults to ‘#bdbdbd’

  • backgroundcolor (str) – The color code to use for the background. Defaults to ‘#ffffff’

  • fontsize (int) – The font size to use for text. Defaults to 13.

  • subfontsize (int) – The font size to use for subtext. Defaults to 8.

  • displaytext (dict) –

    A dictionary of the text to use for each element type in the output visualization. The default values are:

    {
        'id': 'id',
        'u0': 'U_0',
        'u1': 'U_1',
        'u2': 'U_2',
        'u3': 'U_3',
        'x': 'X',
        'y': 'Y',
        'z': 'Z',
        'h': 'H',
        's': 'S',
        'sdg': 'S^\dagger',
        't': 'T',
        'tdg': 'T^\dagger',
        'rx': 'R_x',
        'ry': 'R_y',
        'rz': 'R_z',
        'reset': '\left|0\right\rangle'
    }

    You must specify all the necessary values if using this. There is no provision for passing an incomplete dict in.

  • displaycolor (dict) –

    The color codes to use for each circuit element in the form (gate_color, text_color). The default values are:

    {
        'u1': ('#FA74A6', '#000000'),
        'u2': ('#FA74A6', '#000000'),
        'u3': ('#FA74A6', '#000000'),
        'id': ('#05BAB6', '#000000'),
        'x': ('#05BAB6', '#000000'),
        'y': ('#05BAB6', '#000000'),
        'z': ('#05BAB6', '#000000'),
        'h': ('#6FA4FF', '#000000'),
        'cx': ('#6FA4FF', '#000000'),
        'cy': ('#6FA4FF', '#000000'),
        'cz': ('#6FA4FF', '#000000'),
        'swap': ('#6FA4FF', '#000000'),
        's': ('#6FA4FF', '#000000'),
        'sdg': ('#6FA4FF', '#000000'),
        'dcx': ('#6FA4FF', '#000000'),
        'iswap': ('#6FA4FF', '#000000'),
        't': ('#BB8BFF', '#000000'),
        'tdg': ('#BB8BFF', '#000000'),
        'r': ('#BB8BFF', '#000000'),
        'rx': ('#BB8BFF', '#000000'),
        'ry': ('#BB8BFF', '#000000'),
        'rz': ('#BB8BFF', '#000000'),
        'rxx': ('#BB8BFF', '#000000'),
        'ryy': ('#BB8BFF', '#000000'),
        'rzx': ('#BB8BFF', '#000000'),
        'reset': ('#000000', #FFFFFF'),
        'target': ('#FFFFFF, '#FFFFFF'),
        'measure': ('#000000', '#FFFFFF'),
        'ccx': ('#BB8BFF', '#000000'),
        'cdcx': ('#BB8BFF', '#000000'),
        'ccdcx': ('#BB8BFF', '#000000'),
        'cswap': ('#BB8BFF', '#000000'),
        'ccswap': ('#BB8BFF', '#000000'),
        'mcx': ('#BB8BFF', '#000000'),
        'mcx_gray': ('#BB8BFF', '#000000),
        'u': ('#BB8BFF', '#000000'),
        'p': ('#BB8BFF', '#000000'),
        'sx': ('#BB8BFF', '#000000'),
        'sxdg': ('#BB8BFF', '#000000')
    }

    Colors can also be entered without the text color, such as ‘u1’: ‘#FA74A6’, in which case the text color will always be ‘gatetextcolor’. The ‘displaycolor’ dict can contain any number of elements from one to the entire dict above.

  • latexdrawerstyle (bool) – When set to True, enable LaTeX mode, which will draw gates like the latex output modes.

  • usepiformat (bool) – When set to True, use radians for output.

  • fold (int) – The number of circuit elements to fold the circuit at. Defaults to 20.

  • cregbundle (bool) – If set True, bundle classical registers

  • showindex (bool) – If set True, draw an index.

  • compress (bool) – If set True, draw a compressed circuit.

  • figwidth (int) – The maximum width (in inches) for the output figure.

  • dpi (int) – The DPI to use for the output image. Defaults to 150.

  • margin (list) – A list of margin values to adjust spacing around output image. Takes a list of 4 ints: [x left, x right, y bottom, y top].

  • creglinestyle (str) – The style of line to use for classical registers. Choices are ‘solid’, ‘doublet’, or any valid matplotlib linestyle kwarg value. Defaults to doublet

entanglement

Get the entanglement strategy.

Return type

Union[str, List[str], List[List[str]], List[int], List[List[int]], List[List[List[int]]], List[List[List[List[int]]]], Callable[[int], str], Callable[[int], List[List[int]]]]

Returns

The entanglement strategy, see get_entangler_map() for more detail on how the format is interpreted.

entanglement_blocks

The blocks in the entanglement layers.

Return type

List[Instruction]

Returns

The blocks in the entanglement layers.

extend

extend(rhs)

Append QuantumCircuit to the right hand side if it contains compatible registers.

Two circuits are compatible if they contain the same registers or if they contain different registers with unique names. The returned circuit will contain all unique registers between both circuits.

Modify and return self.

Parameters

rhs (QuantumCircuit) – The quantum circuit to append to the right hand side.

Returns

Returns this QuantumCircuit object (which has been modified)

Return type

QuantumCircuit

Raises

QiskitError – if the rhs circuit is not compatible

fredkin

fredkin(control_qubit, target_qubit1, target_qubit2)

Apply CSwapGate.

from_qasm_file

static from_qasm_file(path)

Take in a QASM file and generate a QuantumCircuit object.

Parameters

path (str) – Path to the file for a QASM program

Returns

The QuantumCircuit object for the input QASM

Return type

QuantumCircuit

from_qasm_str

static from_qasm_str(qasm_str)

Take in a QASM string and generate a QuantumCircuit object.

Parameters

qasm_str (str) – A QASM program string

Returns

The QuantumCircuit object for the input QASM

Return type

QuantumCircuit

get_entangler_map

get_entangler_map(rep_num, block_num, num_block_qubits)

Overloading to handle the special case of 1 qubit where the entanglement are ignored.

Return type

List[List[int]]

get_unentangled_qubits

get_unentangled_qubits()

Get the indices of unentangled qubits in a set.

Return type

Set[int]

Returns

The unentangled qubits.

global_phase

Return the global phase of the circuit in radians.

h

h(qubit)

Apply HGate.

hamiltonian

hamiltonian(operator, time, qubits, label=None)

Apply hamiltonian evolution to to qubits.

has_register

has_register(register)

Test if this circuit has the register r.

Parameters

register (Register) – a quantum or classical register.

Returns

True if the register is contained in this circuit.

Return type

bool

i

i(qubit)

Apply IGate.

id

id(qubit)

Apply IGate.

initial_state

Return the initial state that is added in front of the n-local circuit.

Return type

Any

Returns

The initial state.

initialize

initialize(params, qubits)

Apply initialize to circuit.

insert_barriers

If barriers are inserted in between the layers or not.

Return type

bool

Returns

True, if barriers are inserted in between the layers, False if not.

inverse

inverse()

Invert (take adjoint of) this circuit.

This is done by recursively inverting all gates.

Returns

the inverted circuit

Return type

QuantumCircuit

Raises

CircuitError – if the circuit cannot be inverted.

Examples

input:

┌───┐

q_0: ┤ H ├─────■──────

└───┘┌────┴─────┐

q_1: ─────┤ RX(1.57) ├

└──────────┘

output:

┌───┐

q_0: ──────■──────┤ H ├

┌─────┴─────┐└───┘

q_1: ┤ RX(-1.57) ├─────

└───────────┘

iso

iso(isometry, q_input, q_ancillas_for_output, q_ancillas_zero=None, q_ancillas_dirty=None)

Attach an arbitrary isometry from m to n qubits to a circuit. In particular, this allows to attach arbitrary unitaries on n qubits (m=n) or to prepare any state on n qubits (m=0). The decomposition used here was introduced by Iten et al. in https://arxiv.org/abs/1501.06911.

Parameters

  • isometry (ndarray) – an isometry from m to n qubits, i.e., a (complex) ndarray of dimension 2^n×2^m with orthonormal columns (given in the computational basis specified by the order of the ancillas and the input qubits, where the ancillas are considered to be more significant than the input qubits.).
  • q_input (QuantumRegister|list[Qubit]) – list of m qubits where the input to the isometry is fed in (empty list for state preparation).
  • q_ancillas_for_output (QuantumRegister|list[Qubit]) – list of n-m ancilla qubits that are used for the output of the isometry and which are assumed to start in the zero state. The qubits are listed with increasing significance.
  • q_ancillas_zero (QuantumRegister|list[Qubit]) – list of ancilla qubits which are assumed to start in the zero state. Default is q_ancillas_zero = None.
  • q_ancillas_dirty (QuantumRegister|list[Qubit]) – list of ancilla qubits which can start in an arbitrary state. Default is q_ancillas_dirty = None.

Returns

the isometry is attached to the quantum circuit.

Return type

QuantumCircuit

Raises

QiskitError – if the array is not an isometry of the correct size corresponding to the provided number of qubits.

isometry

isometry(isometry, q_input, q_ancillas_for_output, q_ancillas_zero=None, q_ancillas_dirty=None)

Attach an arbitrary isometry from m to n qubits to a circuit. In particular, this allows to attach arbitrary unitaries on n qubits (m=n) or to prepare any state on n qubits (m=0). The decomposition used here was introduced by Iten et al. in https://arxiv.org/abs/1501.06911.

Parameters

  • isometry (ndarray) – an isometry from m to n qubits, i.e., a (complex) ndarray of dimension 2^n×2^m with orthonormal columns (given in the computational basis specified by the order of the ancillas and the input qubits, where the ancillas are considered to be more significant than the input qubits.).
  • q_input (QuantumRegister|list[Qubit]) – list of m qubits where the input to the isometry is fed in (empty list for state preparation).
  • q_ancillas_for_output (QuantumRegister|list[Qubit]) – list of n-m ancilla qubits that are used for the output of the isometry and which are assumed to start in the zero state. The qubits are listed with increasing significance.
  • q_ancillas_zero (QuantumRegister|list[Qubit]) – list of ancilla qubits which are assumed to start in the zero state. Default is q_ancillas_zero = None.
  • q_ancillas_dirty (QuantumRegister|list[Qubit]) – list of ancilla qubits which can start in an arbitrary state. Default is q_ancillas_dirty = None.

Returns

the isometry is attached to the quantum circuit.

Return type

QuantumCircuit

Raises

QiskitError – if the array is not an isometry of the correct size corresponding to the provided number of qubits.

iswap

iswap(qubit1, qubit2)

Apply iSwapGate.

mcmt

mcmt(gate, control_qubits, target_qubits, ancilla_qubits=None, mode='noancilla', *, single_control_gate_fun=None, q_controls=None, q_ancillae=None, q_targets=None)

Apply a multi-control, multi-target using a generic gate.

This can also be used to implement a generic multi-control gate, as the target could also be of length 1.

mcp

mcp(lam, control_qubits, target_qubit)

Apply MCPhaseGate.

mcrx

mcrx(theta, q_controls, q_target, use_basis_gates=False)

Apply Multiple-Controlled X rotation gate

Parameters

  • self (QuantumCircuit) – The QuantumCircuit object to apply the mcrx gate on.
  • theta (float) – angle theta
  • q_controls (list(Qubit)) – The list of control qubits
  • q_target (Qubit) – The target qubit
  • use_basis_gates (bool) – use p, u, cx

Raises

QiskitError – parameter errors

mcry

mcry(theta, q_controls, q_target, q_ancillae, mode=None, use_basis_gates=False)

Apply Multiple-Controlled Y rotation gate

Parameters

  • self (QuantumCircuit) – The QuantumCircuit object to apply the mcry gate on.
  • theta (float) – angle theta
  • q_controls (list(Qubit)) – The list of control qubits
  • q_target (Qubit) – The target qubit
  • q_ancillae (QuantumRegister or tuple(QuantumRegister, int)) – The list of ancillary qubits.
  • mode (string) – The implementation mode to use
  • use_basis_gates (bool) – use p, u, cx

Raises

QiskitError – parameter errors

mcrz

mcrz(lam, q_controls, q_target, use_basis_gates=False)

Apply Multiple-Controlled Z rotation gate

Parameters

  • self (QuantumCircuit) – The QuantumCircuit object to apply the mcrz gate on.
  • lam (float) – angle lambda
  • q_controls (list(Qubit)) – The list of control qubits
  • q_target (Qubit) – The target qubit
  • use_basis_gates (bool) – use p, u, cx

Raises

QiskitError – parameter errors

mct

mct(control_qubits, target_qubit, ancilla_qubits=None, mode='noancilla')

Apply MCXGate.

mcu1

mcu1(lam, control_qubits, target_qubit)

Apply MCU1Gate.

mcx

mcx(control_qubits, target_qubit, ancilla_qubits=None, mode='noancilla')

Apply 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: - ‘no-ancilla’: 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).

measure

measure(qubit, cbit)

Measure quantum bit into classical bit (tuples).

Parameters

  • qubit (QuantumRegister|list|tuple) – quantum register
  • cbit (ClassicalRegister|list|tuple) – classical register

Returns

the attached measure instruction.

Return type

qiskit.Instruction

Raises

CircuitError – if qubit is not in this circuit or bad format; if cbit is not in this circuit or not creg.

measure_active

measure_active(inplace=True)

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.

Parameters

inplace (bool) – All measurements inplace or return new circuit.

Returns

Returns circuit with measurements when inplace = False.

Return type

QuantumCircuit

measure_all

measure_all(inplace=True)

Adds measurement to all qubits. Creates a new ClassicalRegister with a size equal to the number of qubits being measured.

Returns a new circuit with measurements if inplace=False.

Parameters

inplace (bool) – All measurements inplace or return new circuit.

Returns

Returns circuit with measurements when inplace = False.

Return type

QuantumCircuit

mirror

mirror()

DEPRECATED: use circuit.reverse_ops().

Returns

the reversed circuit.

Return type

QuantumCircuit

ms

ms(theta, qubits)

Apply MSGate.

num_ancillas

Return the number of ancilla qubits.

num_clbits

Return number of classical bits.

num_connected_components

num_connected_components(unitary_only=False)

How many non-entangled subcircuits can the circuit be factored to.

Parameters

unitary_only (bool) – Compute only unitary part of graph.

Returns

Number of connected components in circuit.

Return type

int

num_layers

Return the number of layers in the n-local circuit.

Return type

int

Returns

The number of layers in the circuit.

num_nonlocal_gates

num_nonlocal_gates()

Return number of non-local gates (i.e. involving 2+ qubits).

Conditional nonlocal gates are also included.

num_parameters

Convenience function to get the number of parameter objects in the circuit.

num_parameters_settable

The number of total parameters that can be set to distinct values.

This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from num_parameters which counts the number of unique Parameter objects currently in the circuit.

Return type

int

Returns

The number of parameters originally available in the circuit.

Note

This quantity does not require the circuit to be built yet.

num_qubits

Returns the number of qubits in this circuit.

Return type

int

Returns

The number of qubits.

num_tensor_factors

num_tensor_factors()

Computes 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.

num_unitary_factors

num_unitary_factors()

Computes the number of tensor factors in the unitary (quantum) part of the circuit only.

ordered_parameters

The parameters used in the underlying circuit.

This includes float values and duplicates.

Examples

>>> # prepare circuit ...
>>> print(nlocal)
     ┌───────┐┌──────────┐┌──────────┐┌──────────┐
q_0:Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3])
     └───────┘└──────────┘└──────────┘└──────────┘
>>> nlocal.parameters
{Parameter(θ[1]), Parameter(θ[3])}
>>> nlocal.ordered_parameters
[1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])]

Return type

List[Parameter]

Returns

The parameters objects used in the circuit.

p

p(theta, qubit)

Apply PhaseGate.

parameter_bounds

The parameter bounds for the unbound parameters in the circuit.

Return type

Optional[List[Tuple[float, float]]]

Returns

A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If None is returned, problem is fully unbounded.

parameters

Get the Parameter objects in the circuit.

Return type

Set[Parameter]

Returns

A set containing the unbound circuit parameters.

power

power(power, matrix_power=False)

Raise this circuit to the power of power.

If power is a positive integer and matrix_power is False, this implementation defaults to calling repeat. Otherwise, if the circuit is unitary, the matrix is computed to calculate the matrix power.

Parameters

  • power (int) – The power to raise this circuit to.
  • matrix_power (bool) – If True, the circuit is converted to a matrix and then the matrix power is computed. If False, and power is a positive integer, the implementation defaults to repeat.

Raises

CircuitError – If the circuit needs to be converted to a gate but it is not unitary.

Returns

A circuit implementing this circuit raised to the power of power.

Return type

QuantumCircuit

preferred_init_points

The initial points for the parameters. Can be stored as initial guess in optimization.

Return type

Optional[List[float]]

Returns

The initial values for the parameters, or None, if none have been set.

print_settings()

Returns information about the setting.

Return type

str

Returns

The class name and the attributes/parameters of the instance as str.

qasm

qasm(formatted=False, filename=None)

Return OpenQASM string.

Parameters

  • formatted (bool) – Return formatted Qasm string.
  • filename (str) – Save Qasm to file with name ‘filename’.

Returns

If formatted=False.

Return type

str

Raises

ImportError – If pygments is not installed and formatted is True.

qbit_argument_conversion

qbit_argument_conversion(qubit_representation)

Converts several qubit representations (such as indexes, range, etc.) into a list of qubits.

Parameters

qubit_representation (Object) – representation to expand

Returns

Where each tuple is a qubit.

Return type

List(tuple)

qregs

A list of the quantum registers associated with the circuit.

qubit_duration

qubit_duration(*qubits)

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.

Parameters

*qubits – Qubits within self to include.

Return type

Union[int, float]

Returns

Return the duration between the first start and last stop time of non-delay instructions

qubit_start_time

qubit_start_time(*qubits)

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

Parameters

  • *qubits – Qubits within self to include. Integers are allowed for qubits, indicating
  • of self.qubits. (indices) –

Return type

Union[int, float]

Returns

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

Raises

CircuitError – if self is a not-yet scheduled circuit.

qubit_stop_time

qubit_stop_time(*qubits)

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

Parameters

  • *qubits – Qubits within self to include. Integers are allowed for qubits, indicating
  • of self.qubits. (indices) –

Return type

Union[int, float]

Returns

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

Raises

CircuitError – if self is a not-yet scheduled circuit.

qubits

Returns a list of quantum bits in the order that the registers were added.

r

r(theta, phi, qubit)

Apply RGate.

rcccx

rcccx(control_qubit1, control_qubit2, control_qubit3, target_qubit)

Apply RC3XGate.

rccx

rccx(control_qubit1, control_qubit2, target_qubit)

Apply RCCXGate.

remove_final_measurements

remove_final_measurements(inplace=True)

Removes final measurement on all qubits if they are present. Deletes the ClassicalRegister that was used to store the values from these measurements if it is idle.

Returns a new circuit without measurements if inplace=False.

Parameters

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

Returns

Returns circuit with measurements removed when inplace = False.

Return type

QuantumCircuit

repeat

repeat(reps)

Repeat this circuit reps times.

Parameters

reps (int) – How often this circuit should be repeated.

Returns

A circuit containing reps repetitions of this circuit.

Return type

QuantumCircuit

reps

The number of times rotation and entanglement block are repeated.

Return type

int

Returns

The number of repetitions.

reset

reset(qubit)

Reset q.

reverse_bits

reverse_bits()

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

the circuit with reversed bit order.

Return type

QuantumCircuit

Examples

input:

┌───┐

q_0: ┤ H ├─────■──────

└───┘┌────┴─────┐

q_1: ─────┤ RX(1.57) ├

└──────────┘

output:

┌──────────┐

q_0: ─────┤ RX(1.57) ├

┌───┐└────┬─────┘

q_1: ┤ H ├─────■──────

└───┘

reverse_ops

reverse_ops()

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

the reversed circuit.

Return type

QuantumCircuit

Examples

input:

┌───┐

q_0: ┤ H ├─────■──────

└───┘┌────┴─────┐

q_1: ─────┤ RX(1.57) ├

└──────────┘

output:

┌───┐

q_0: ─────■──────┤ H ├

┌────┴─────┐└───┘

q_1: ┤ RX(1.57) ├─────

└──────────┘

rotation_blocks

The blocks in the rotation layers.

Return type

List[Instruction]

Returns

The blocks in the rotation layers.

rx

rx(theta, qubit, label=None)

Apply RXGate.

rxx

rxx(theta, qubit1, qubit2)

Apply RXXGate.

ry

ry(theta, qubit, label=None)

Apply RYGate.

ryy

ryy(theta, qubit1, qubit2)

Apply RYYGate.

rz

rz(phi, qubit)

Apply RZGate.

rzx

rzx(theta, qubit1, qubit2)

Apply RZXGate.

rzz

rzz(theta, qubit1, qubit2)

Apply RZZGate.

s

s(qubit)

Apply SGate.

sdg

sdg(qubit)

Apply SdgGate.

size

size()

Returns total number of gate operations in circuit.

Returns

Total number of gate operations.

Return type

int

snapshot

snapshot(label, snapshot_type='statevector', qubits=None, params=None)

Take a statevector snapshot of the internal simulator representation. Works on all qubits, and prevents reordering (like barrier). :param label: a snapshot label to report the result :type label: str :param snapshot_type: the type of the snapshot. :type snapshot_type: str :param qubits: the qubits to apply snapshot to [Default: None]. :type qubits: list or None :param params: the parameters for snapshot_type [Default: None]. :type params: list or None

Returns

with attached command

Return type

QuantumCircuit

Raises

ExtensionError – malformed command

snapshot_density_matrix

snapshot_density_matrix(label, qubits=None)

Take a density matrix snapshot of simulator state.

Parameters

  • label (str) – a snapshot label to report the result
  • qubits (list or None) – the qubits to apply snapshot to. If None all qubits will be snapshot [Default: None].

Returns

with attached instruction.

Return type

QuantumCircuit

Raises

ExtensionError – if snapshot is invalid.

snapshot_expectation_value

snapshot_expectation_value(label, op, qubits, single_shot=False, variance=False)

Take a snapshot of expectation value <O> of an Operator.

Parameters

  • label (str) – a snapshot label to report the result
  • op (Operator) – operator to snapshot
  • qubits (list) – the qubits to snapshot.
  • single_shot (bool) – return list for each shot rather than average [Default: False]
  • variance (bool) – compute variance of values [Default: False]

Returns

with attached instruction.

Return type

QuantumCircuit

Raises

ExtensionError – if snapshot is invalid.

snapshot_probabilities

snapshot_probabilities(label, qubits, variance=False)

Take a probability snapshot of the simulator state.

Parameters

  • label (str) – a snapshot label to report the result
  • qubits (list) – the qubits to snapshot.
  • variance (bool) – compute variance of probabilities [Default: False]

Returns

with attached instruction.

Return type

QuantumCircuit

Raises

ExtensionError – if snapshot is invalid.

snapshot_stabilizer

snapshot_stabilizer(label)

Take a stabilizer snapshot of the simulator state.

Parameters

label (str) – a snapshot label to report the result.

Returns

with attached instruction.

Return type

QuantumCircuit

Raises

ExtensionError – if snapshot is invalid.

Additional Information:

This snapshot is always performed on all qubits in a circuit. The number of qubits parameter specifies the size of the instruction as a barrier and should be set to the number of qubits in the circuit.

snapshot_statevector

snapshot_statevector(label)

Take a statevector snapshot of the simulator state.

Parameters

label (str) – a snapshot label to report the result.

Returns

with attached instruction.

Return type

QuantumCircuit

Raises

ExtensionError – if snapshot is invalid.

Additional Information:

This snapshot is always performed on all qubits in a circuit. The number of qubits parameter specifies the size of the instruction as a barrier and should be set to the number of qubits in the circuit.

squ

squ(unitary_matrix, qubit, mode='ZYZ', up_to_diagonal=False, *, u=None)

Decompose an arbitrary 2*2 unitary into three rotation gates.

Note that the decomposition is up to a global phase shift. (This is a well known decomposition, which can be found for example in Nielsen and Chuang’s book “Quantum computation and quantum information”.)

Parameters

  • unitary_matrix (ndarray) – 2*2 unitary (given as a (complex) ndarray).
  • qubit (QuantumRegister | Qubit) – The qubit which the gate is acting on.
  • mode (string) – determines the used decomposition by providing the rotation axes. The allowed modes are: “ZYZ” (default)
  • up_to_diagonal (bool) – if set to True, the single-qubit unitary is decomposed up to a diagonal matrix, i.e. a unitary u’ is implemented such that there exists a 2*2 diagonal gate d with u = d.dot(u’)
  • u (ndarray) – Deprecated, use unitary_matrix instead.

Returns

The single-qubit unitary instruction attached to the circuit.

Return type

InstructionSet

Raises

QiskitError – if the format is wrong; if the array u is not unitary

swap

swap(qubit1, qubit2)

Apply SwapGate.

sx

sx(qubit)

Apply SXGate.

sxdg

sxdg(qubit)

Apply SXdgGate.

t

t(qubit)

Apply TGate.

tdg

tdg(qubit)

Apply TdgGate.

to_gate

to_gate(parameter_map=None, label=None)

Create a Gate out of this circuit.

Parameters

  • parameter_map (dict) – 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 (str) – Optional gate label.

Returns

a composite gate encapsulating this circuit (can be decomposed back)

Return type

Gate

to_instruction

to_instruction(parameter_map=None)

Create an Instruction out of this circuit.

Parameters

parameter_map (dict) – 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.

Returns

a composite instruction encapsulating this circuit (can be decomposed back)

Return type

qiskit.circuit.Instruction

toffoli

toffoli(control_qubit1, control_qubit2, target_qubit)

Apply CCXGate.

u

u(theta, phi, lam, qubit)

Apply UGate.

u1

u1(theta, qubit)

Apply U1Gate.

u2

u2(phi, lam, qubit)

Apply U2Gate.

u3

u3(theta, phi, lam, qubit)

Apply U3Gate.

uc

uc(gate_list, q_controls, q_target, up_to_diagonal=False)

Attach a uniformly controlled gates (also called multiplexed gates) to a circuit.

The decomposition was introduced by Bergholm et al. in https://arxiv.org/pdf/quant-ph/0410066.pdf.

Parameters

  • gate_list (list[ndarray]) – list of two qubit unitaries [U_0,…,U_{2^k-1}], where each single-qubit unitary U_i is a given as a 2*2 array
  • q_controls (QuantumRegister|list[(QuantumRegister,int)]) – list of k control qubits. The qubits are ordered according to their significance in the computational basis. For example if q_controls=[q[1],q[2]] (with q = QuantumRegister(2)), the unitary U_0 is performed if q[1] and q[2] are in the state zero, U_1 is performed if q[2] is in the state zero and q[1] is in the state one, and so on
  • q_target (QuantumRegister|(QuantumRegister,int)) – target qubit, where we act on with the single-qubit gates.
  • up_to_diagonal (bool) – If set to True, the uniformly controlled gate is decomposed up to a diagonal gate, i.e. a unitary u’ is implemented such that there exists a diagonal gate d with u = d.dot(u’), where the unitary u describes the uniformly controlled gate

Returns

the uniformly controlled gate is attached to the circuit.

Return type

QuantumCircuit

Raises

QiskitError – if the list number of control qubits does not correspond to the provided number of single-qubit unitaries; if an input is of the wrong type

ucrx

ucrx(angle_list, q_controls, q_target)

Attach a uniformly controlled (also called multiplexed) Rx rotation gate to a circuit.

The decomposition is base on https://arxiv.org/pdf/quant-ph/0406176.pdf by Shende et al.

Parameters

  • angle_list (list) – list of (real) rotation angles [a0,...,a2k1][a_0,...,a_{2^k-1}]
  • q_controls (QuantumRegister|list) – list of k control qubits (or empty list if no controls). The control qubits are ordered according to their significance in increasing order: For example if q_controls=[q[0],q[1]] (with q = QuantumRegister(2)), the rotation Rx(a_0) is performed if q[0] and q[1] are in the state zero, the rotation Rx(a_1) is performed if q[0] is in the state one and q[1] is in the state zero, and so on
  • q_target (QuantumRegister|Qubit) – target qubit, where we act on with the single-qubit rotation gates

Returns

the uniformly controlled rotation gate is attached to the circuit.

Return type

QuantumCircuit

Raises

QiskitError – if the list number of control qubits does not correspond to the provided number of single-qubit unitaries; if an input is of the wrong type

ucry

ucry(angle_list, q_controls, q_target)

Attach a uniformly controlled (also called multiplexed) Ry rotation gate to a circuit.

The decomposition is base on https://arxiv.org/pdf/quant-ph/0406176.pdf by Shende et al.

Parameters

  • angle_list (list[numbers) – list of (real) rotation angles [a0,...,a2k1][a_0,...,a_{2^k-1}]
  • q_controls (QuantumRegister|list[Qubit]) – list of k control qubits (or empty list if no controls). The control qubits are ordered according to their significance in increasing order: For example if q_controls=[q[0],q[1]] (with q = QuantumRegister(2)), the rotation Ry(a_0) is performed if q[0] and q[1] are in the state zero, the rotation Ry(a_1) is performed if q[0] is in the state one and q[1] is in the state zero, and so on
  • q_target (QuantumRegister|Qubit) – target qubit, where we act on with the single-qubit rotation gates

Returns

the uniformly controlled rotation gate is attached to the circuit.

Return type

QuantumCircuit

Raises

QiskitError – if the list number of control qubits does not correspond to the provided number of single-qubit unitaries; if an input is of the wrong type

ucrz

ucrz(angle_list, q_controls, q_target)

Attach a uniformly controlled (also called multiplexed gates) Rz rotation gate to a circuit.

The decomposition is base on https://arxiv.org/pdf/quant-ph/0406176.pdf by Shende et al.

Parameters

  • angle_list (list[numbers) – list of (real) rotation angles [a_0,…,a_{2^k-1}]
  • q_controls (QuantumRegister|list[Qubit]) – list of k control qubits (or empty list if no controls). The control qubits are ordered according to their significance in increasing order: For example if q_controls=[q[1],q[2]] (with q = QuantumRegister(2)), the rotation Rz(a_0)is performed if q[1] and q[2] are in the state zero, the rotation Rz(a_1) is performed if q[1] is in the state one and q[2] is in the state zero, and so on
  • q_target (QuantumRegister|Qubit) – target qubit, where we act on with the single-qubit rotation gates

Returns

the uniformly controlled rotation gate is attached to the circuit.

Return type

QuantumCircuit

Raises

QiskitError – if the list number of control qubits does not correspond to the provided number of single-qubit unitaries; if an input is of the wrong type

unitary

unitary(obj, qubits, label=None)

Apply unitary gate to q.

width

width()

Return number of qubits plus clbits in circuit.

Returns

Width of circuit.

Return type

int

x

x(qubit, label=None)

Apply XGate.

y

y(qubit)

Apply YGate.

z

z(qubit)

Apply ZGate.

Was this page helpful?
Report a bug or request content on GitHub.