English
Languages
English
Bengali
French
German
Japanese
Korean
Portuguese
Spanish
Tamil

QuantumCircuit

class QuantumCircuit(*regs, name=None, global_phase=0, metadata=None)[source]

Bases: object

Create a new circuit.

A circuit is a list of instructions bound to some registers.

Parameters
  • regs (list(Register) or list(int) or list(list(Bit))) –

    The registers to be included in the circuit.

    • If a list of Register objects, represents the QuantumRegister and/or 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 Bit objects, a collection of Bit s to be added to the circuit.

  • name (str) – the name of the quantum circuit. If not set, an automatically generated string will be assigned.

  • global_phase (float or ParameterExpression) – The global phase of the circuit in radians.

  • metadata (dict) – Arbitrary key value metadata to associate with the circuit. This gets stored as free-form data in a dict in the metadata attribute. It will not be directly used in the circuit.

Raises

CircuitError – if the circuit name, if given, is not valid.

Examples

Construct a simple Bell state circuit.

from qiskit import QuantumCircuit

qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')

(Source code, png, hires.png, pdf)

../_images/qiskit-circuit-QuantumCircuit-1.png

Construct a 5-qubit GHZ circuit.

from qiskit import QuantumCircuit

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

Construct a 4-qubit Bernstein-Vazirani circuit using registers.

from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit

qr = QuantumRegister(3, 'q')
anc = QuantumRegister(1, 'ancilla')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, anc, cr)

qc.x(anc[0])
qc.h(anc[0])
qc.h(qr[0:3])
qc.cx(qr[0:3], anc[0])
qc.h(qr[0:3])
qc.barrier(qr)
qc.measure(qr, cr)

qc.draw('mpl')

(Source code, png, hires.png, pdf)

../_images/qiskit-circuit-QuantumCircuit-2.png

Methods

add_bits

Add Bits to the circuit.

add_calibration

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

add_register

Add registers.

append

Append one or more instructions to the end of the circuit, modifying the circuit in place.

assign_parameters

Assign parameters to new parameters or values.

barrier

Apply Barrier.

bind_parameters

Assign numeric parameters to values yielding a new circuit.

break_loop

Apply BreakLoopOp.

cast

Best effort to cast value to type.

cbit_argument_conversion

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

ccx

Apply CCXGate.

ccz

Apply CCZGate.

ch

Apply CHGate.

clear

Clear all instructions in self.

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

Apply CXGate.

compose

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

continue_loop

Apply ContinueLoopOp.

control

Control this circuit on num_ctrl_qubits qubits.

copy

Copy the circuit.

copy_empty_like

Return a copy of self with the same structure but empty.

count_ops

Count each operation kind in the circuit.

cp

Apply CPhaseGate.

crx

Apply CRXGate.

cry

Apply CRYGate.

crz

Apply CRZGate.

cs

Apply CSGate.

csdg

Apply CSdgGate.

cswap

Apply CSwapGate.

csx

Apply CSXGate.

cu

Apply CUGate.

cx

Apply CXGate.

cy

Apply CYGate.

cz

Apply CZGate.

dcx

Apply DCXGate.

decompose

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

delay

Apply Delay.

depth

Return circuit depth (i.e., length of critical path).

diagonal

Attach a diagonal gate to a circuit.

draw

Draw the quantum circuit.

ecr

Apply ECRGate.

find_bit

Find locations in the circuit which can be used to reference a given Bit.

for_loop

Create a for loop on this circuit.

fredkin

Apply CSwapGate.

from_instructions

Construct a circuit from an iterable of CircuitInstructions.

from_qasm_file

Take in a QASM file and generate a QuantumCircuit object.

from_qasm_str

Take in a QASM string and generate a QuantumCircuit object.

get_instructions

Get instructions matching name.

h

Apply HGate.

hamiltonian

Apply hamiltonian evolution to qubits.

has_calibration_for

Return True if the circuit has a calibration defined for the instruction context.

has_register

Test if this circuit has the register r.

i

Apply IGate.

id

Apply IGate.

if_else

Apply IfElseOp.

if_test

Create an if statement on this circuit.

initialize

Initialize qubits in a specific state.

inverse

Invert (take adjoint of) this circuit.

iso

Attach an arbitrary isometry from m to n qubits to a circuit.

isometry

Attach an arbitrary isometry from m to n qubits to a circuit.

iswap

Apply iSwapGate.

mcp

Apply MCPhaseGate.

mcrx

Apply Multiple-Controlled X rotation gate

mcry

Apply Multiple-Controlled Y rotation gate

mcrz

Apply Multiple-Controlled Z rotation gate

mct

Apply MCXGate.

mcx

Apply MCXGate.

measure

Measure quantum bit into classical bit (tuples).

measure_active

Adds measurement to all non-idle qubits.

measure_all

Adds measurement to all qubits.

ms

Apply MSGate.

num_connected_components

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

Apply PhaseGate.

pauli

Apply PauliGate.

power

Raise this circuit to the power of power.

prepare_state

Prepare qubits in a specific state.

qasm

Return OpenQASM string.

qbit_argument_conversion

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

qubit_duration

Return the duration between the start and stop time of the first and last instructions, excluding delays, over the supplied qubits.

qubit_start_time

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

qubit_stop_time

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

r

Apply RGate.

rcccx

Apply RC3XGate.

rccx

Apply RCCXGate.

remove_final_measurements

Removes final measurements and barriers on all qubits if they are present.

repeat

Repeat this circuit reps times.

reset

Reset the quantum bit(s) to their default state.

reverse_bits

Return a circuit with the opposite order of wires.

reverse_ops

Reverse the circuit by reversing the order of instructions.

rv

Apply RVGate.

rx

Apply RXGate.

rxx

Apply RXXGate.

ry

Apply RYGate.

ryy

Apply RYYGate.

rz

Apply RZGate.

rzx

Apply RZXGate.

rzz

Apply RZZGate.

s

Apply SGate.

save_amplitudes

Save complex statevector amplitudes.

save_amplitudes_squared

Save squared statevector amplitudes (probabilities).

save_clifford

Save the current stabilizer simulator quantum state as a Clifford.

save_density_matrix

Save the current simulator quantum state as a density matrix.

save_expectation_value

Save the expectation value of a Hermitian operator.

save_expectation_value_variance

Save the expectation value of a Hermitian operator.

save_matrix_product_state

Save the current simulator quantum state as a matrix product state.

save_probabilities

Save measurement outcome probabilities vector.

save_probabilities_dict

Save measurement outcome probabilities vector.

save_stabilizer

Save the current stabilizer simulator quantum state as a StabilizerState.

save_state

Save the current simulator quantum state.

save_statevector

Save the current simulator quantum state as a statevector.

save_statevector_dict

Save the current simulator quantum state as a statevector as a dict.

save_superop

Save the current state of the superop simulator.

save_unitary

Save the current state of the unitary simulator.

sdg

Apply SdgGate.

set_density_matrix

Set the density matrix state of the simulator.

set_matrix_product_state

Set the matrix product state of the simulator.

set_stabilizer

Set the Clifford stabilizer state of the simulator.

set_statevector

Set the statevector state of the simulator.

set_superop

Set the superop state of the simulator.

set_unitary

Set the state state of the simulator.

size

Returns total number of instructions in circuit.

snapshot

Take a statevector snapshot of the internal simulator representation.

squ

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

swap

Apply SwapGate.

sx

Apply SXGate.

sxdg

Apply SXdgGate.

t

Apply TGate.

tdg

Apply TdgGate.

tensor

Tensor self with other.

to_gate

Create a Gate out of this circuit.

to_instruction

Create an Instruction out of this circuit.

toffoli

Apply CCXGate.

u

Apply UGate.

uc

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

ucrx

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

ucry

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

ucrz

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

unitary

Apply unitary gate specified by obj to qubits.

while_loop

Create a while loop on this circuit.

width

Return number of qubits plus clbits in circuit.

x

Apply XGate.

y

Apply YGate.

z

Apply ZGate.

Attributes

ancillas

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

Return type

List[AncillaQubit]

calibrations

Return calibration dictionary.

The custom pulse definition of a given gate is of the form {'gate_name': {(qubits, params): schedule}}

Return type

dict

clbits

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

Return type

List[Clbit]

data

Return the circuit data (instructions and context).

Returns

a list-like object containing the CircuitInstructions for each instruction.

Return type

QuantumCircuitData

extension_lib = 'include "qelib1.inc";'
global_phase

Return the global phase of the circuit in radians.

Return type

Union[ParameterExpression, float]

header = 'OPENQASM 2.0;'
instances = 2293
metadata

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 (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.

Return type

dict

num_ancillas

Return the number of ancilla qubits.

Return type

int

num_clbits

Return number of classical bits.

Return type

int

num_parameters

The number of parameter objects in the circuit.

Return type

int

num_qubits

Return number of qubits.

Return type

int

op_start_times

Return a list of operation start times.

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

Return type

List[int]

Returns

List of integers representing instruction start times. The index corresponds to the index of instruction in QuantumCircuit.data.

Raises

AttributeError – When circuit is not scheduled.

parameters

The parameters defined in the circuit.

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

Examples

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

>>> 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 unituitive when it comes to numbers. The literal “10” comes before “2” in strict alphabetical sorting.

>>> 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 ParameterVector can be used.


>>> 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])
])
Return type

ParameterView

Returns

The sorted Parameter objects in the circuit.

prefix = 'circuit'
qubits

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

Return type

List[Qubit]