QuantumCircuit

class QuantumCircuit(*regs, name=None)[ソース]

ベースクラス: object

Create a new circuit.

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

パラメータ
  • regs --

    list(Register) or list(int) The registers to be included 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

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

例外

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

サンプル

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()
        ┌───┐     ┌─┐   
q_0: |0>┤ H ├──■──┤M├───
        └───┘┌─┴─┐└╥┘┌─┐
q_1: |0>─────┤ X ├─╫─┤M├
             └───┘ ║ └╥┘
 c_0: 0 ═══════════╩══╬═
                      ║ 
 c_1: 0 ══════════════╩═
                        

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 Berstein-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()
              ┌───┐          ┌───┐           ░ ┌─┐      
      q_0: |0>┤ H ├───────■──┤ H ├───────────░─┤M├──────
              ├───┤       │  └───┘┌───┐      ░ └╥┘┌─┐   
      q_1: |0>┤ H ├───────┼────■──┤ H ├──────░──╫─┤M├───
              ├───┤       │    │  └───┘┌───┐ ░  ║ └╥┘┌─┐
      q_2: |0>┤ H ├───────┼────┼────■──┤ H ├─░──╫──╫─┤M├
              ├───┤┌───┐┌─┴─┐┌─┴─┐┌─┴─┐└───┘ ░  ║  ║ └╥┘
ancilla_0: |0>┤ X ├┤ H ├┤ X ├┤ X ├┤ X ├─────────╫──╫──╫─
              └───┘└───┘└───┘└───┘└───┘         ║  ║  ║ 
       c_0: 0 ══════════════════════════════════╩══╬══╬═
                                                   ║  ║ 
       c_1: 0 ═════════════════════════════════════╩══╬═
                                                      ║ 
       c_2: 0 ════════════════════════════════════════╩═
                                                        

Attributes Summary

clbits

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

data

Return the circuit data (instructions and context).

extension_lib

header

instances

n_qubits

Return number of qubits.

parameters

convenience function to get the parameters defined in the parameter table

prefix

qubits

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

Methods Summary

AND(qr_variables, qb_target, qr_ancillae[, ...])

Build a collective conjunction (AND) circuit in place using mct.

OR(qr_variables, qb_target, qr_ancillae[, ...])

Build a collective disjunction (OR) circuit in place using mct.

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.

barrier(*qargs)

Apply barrier to circuit.

bind_parameters(value_dict)

Assign 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(ctl1, ctl2, tgt)

Apply Toffoli to ctl1 and ctl2 to tgt.

ch(ctl, tgt)

Apply CH from ctl to tgt.

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(ctl, tgt)

Apply CX from ctl to tgt.

combine(rhs)

Append rhs to self if self contains compatible registers.

copy([name])

Copy the circuit.

count_ops()

Count each operation kind in the circuit.

cry(theta, q_control, q_target)

Apply Controlled-RY (cry) Gate.

crz(theta, ctl, tgt)

Apply crz from ctl to tgt with angle theta.

cswap(ctl, tgt1, tgt2)

Apply Fredkin to circuit.

cu1(theta, ctl, tgt)

Apply cu1 from ctl to tgt with angle theta.

cu3(theta, phi, lam, ctl, tgt)

Apply cu3 from ctl to tgt with angle theta, phi, lam.

cx(ctl, tgt)

Apply CX from ctl to tgt.

cy(ctl, tgt)

Apply CY to circuit.

cz(ctl, tgt)

Apply CZ to circuit.

decompose()

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

depth()

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

diag_gate(diag, qubit)

Attach a diagonal gate to a circuit.

draw([scale, filename, style, output, ...])

Draw the quantum circuit

extend(rhs)

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

fredkin(ctl, tgt1, tgt2)

Apply Fredkin to circuit.

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.

h(q)

Apply H to q.

has_register(register)

Test if this circuit has the register r.

iden(q)

Apply Identity to q.

initialize(params, qubits)

Apply initialize to circuit.

inverse()

Invert this circuit.

iso(isometry, q_input, q_ancillas_for_output)

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

mcmt(q_controls, q_ancillae, ...[, mode])

Apply a Multi-Control, Multi-Target using a generic gate.

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(q_controls, q_target, q_ancilla[, mode])

Apply Multiple-Control Toffoli operation

mcu1(lam, control_qubits, target_qubit)

Apply Multiple-Controlled U1 gate

measure(qubit, cbit)

Measure quantum bit into classical bit (tuples).

measure_active()

Adds measurement to all non-idle qubits.

measure_all()

Adds measurement to all qubits.

mirror()

Mirror the circuit by reversing the instructions.

ms(theta, qubits)

Apply MS to q1 and q2.

num_connected_components([unitary_only])

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

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.

qasm()

Return OpenQASM string.

qbit_argument_conversion(qubit_representation)

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

r(theta, phi, q)

Apply R to q.

rcccx(q_control_1, q_control_2, q_control_3, ...)

Apply 3-Control Relative-Phase Toffoli gate from q_control_1, q_control_2, and q_control_3 to q_target.

rccx(q_control_1, q_control_2, q_target)

Apply 2-Control Relative-Phase Toffoli gate from q_control_1 and q_control_2 to q_target.

remove_final_measurements()

Removes final measurement on all qubits if they are present.

reset(qubit)

Reset q.

rx(theta, q)

Apply Rx to q.

rxx(theta, qubit1, qubit2)

Apply RXX to circuit.

ry(theta, q)

Apply Ry to q.

rz(phi, q)

Apply Rz to q.

rzz(theta, qubit1, qubit2)

Apply RZZ to circuit.

s(q)

Apply S to q.

sdg(q)

Apply Sdg to q.

size()

Returns total number of gate operations in circuit.

snapshot(label[, snapshot_type, qubits, params])

Take a statevector snapshot of the internal simulator representation.

squ(u, qubit[, mode, up_to_diagonal])

Decompose an arbitrary 2*2 unitary into three rotation gates \(U=R_zR_yR_z\).

swap(qubit1, qubit2)

Apply SWAP from qubit1 to qubit2.

t(q)

Apply T to q.

tdg(q)

Apply Tdg to q.

to_gate([parameter_map])

Create a Gate out of this circuit.

to_instruction([parameter_map])

Create an Instruction out of this circuit.

toffoli(ctl1, ctl2, tgt)

Apply Toffoli to ctl1 and ctl2 to tgt.

u1(theta, q)

Apply u1 with angle theta to q.

u2(phi, lam, q)

Apply u2 to q.

u3(theta, phi, lam, q)

Apply u3 to q.

ucg(gate_list, q_controls, q_target[, ...])

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

ucx(angle_list, q_controls, q_target)

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

ucy(angle_list, q_controls, q_target)

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

ucz(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 u2 to q.

width()

Return number of qubits plus clbits in circuit.

x(q)

Apply X to q.

y(q)

Apply Y to q.

z(q)

Apply Z to q.

Attributes Documentation

clbits

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

data

Return the circuit data (instructions and context).

戻り値

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.

戻り値の型

QuantumCircuitData

extension_lib = 'include "qelib1.inc";'
header = 'OPENQASM 2.0;'
instances = 0
n_qubits

Return number of qubits.

parameters

convenience function to get the parameters defined in the parameter table

prefix = 'circuit'
qubits

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

Methods Documentation

AND(qr_variables, qb_target, qr_ancillae, flags=None, mct_mode='basic')

Build a collective conjunction (AND) circuit in place using mct.

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to build the conjunction on.

  • qr_variables (QuantumRegister) -- The QuantumRegister holding the variable qubits.

  • qb_target (Qubit) -- The target qubit to hold the conjunction result.

  • qr_ancillae (QuantumRegister) -- The ancillary QuantumRegister for building the mct.

  • flags (list[int]) -- A list of +1/-1/0 to mark negations or omissions of qubits.

  • mct_mode (str) -- The mct building mode.

OR(qr_variables, qb_target, qr_ancillae, flags=None, mct_mode='basic')

Build a collective disjunction (OR) circuit in place using mct.

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to build the disjunction on.

  • qr_variables (QuantumRegister) -- The QuantumRegister holding the variable qubits.

  • flags (list[int]) -- A list of +1/-1/0 to mark negations or omissions of qubits.

  • qb_target (Qubit) -- The target qubit to hold the disjunction result.

  • qr_ancillae (QuantumRegister) -- The ancillary QuantumRegister for building the mct.

  • mct_mode (str) -- The mct building mode.

add_register(*regs)[ソース]

Add registers.

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.

パラメータ
  • instruction (Instruction or Operation) -- Instruction instance to append

  • qargs (list(argument)) -- qubits to attach instruction to

  • cargs (list(argument)) -- clbits to attach instruction to

戻り値

a handle to the instruction that was just added

戻り値の型

Instruction

barrier(*qargs)

Apply barrier to circuit. If qargs is None, applies to all the qbits. Args is a list of QuantumRegister or single qubits. For QuantumRegister, applies barrier to all the qubits in that register.

bind_parameters(value_dict)[ソース]

Assign parameters to values yielding a new circuit.

パラメータ

value_dict (dict) -- {parameter: value, ...}

例外

CircuitError -- If value_dict contains parameters not present in the circuit

戻り値

copy of self with assignment substitution.

戻り値の型

QuantumCircuit

static cast(value, _type)[ソース]

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

cbit_argument_conversion(clbit_representation)[ソース]

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

パラメータ

clbit_representation (Object) -- representation to expand

戻り値

Where each tuple is a classical bit.

戻り値の型

List(tuple)

ccx(ctl1, ctl2, tgt)

Apply Toffoli to ctl1 and ctl2 to tgt.

ch(ctl, tgt)

Apply CH from ctl to tgt.

classmethod cls_instances()[ソース]

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

classmethod cls_prefix()[ソース]

Return the prefix to use for auto naming.

cnot(ctl, tgt)

Apply CX from ctl to tgt.

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.

パラメータ

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

戻り値

Returns a new QuantumCircuit object

戻り値の型

QuantumCircuit

例外

QiskitError -- if the rhs circuit is not compatible

copy(name=None)[ソース]

Copy the circuit.

パラメータ

name (str) -- name to be given to the copied circuit, if None then the name stays the same

戻り値

a deepcopy of the current circuit, with the specified name

戻り値の型

QuantumCircuit

count_ops()[ソース]

Count each operation kind in the circuit.

戻り値

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

戻り値の型

OrderedDict

cry(theta, q_control, q_target)

Apply Controlled-RY (cry) Gate.

パラメータ
  • self (QuantumCircuit) -- The circuit to apply the cry gate on.

  • theta (float) -- The rotation angle.

  • q_control (Union(Qubit, int)) -- The control qubit.

  • q_target (Union(Qubit, int)) -- The target qubit.

戻り値

instance self

戻り値の型

QuantumCircuit

例外

AquaError -- invalid input

crz(theta, ctl, tgt)

Apply crz from ctl to tgt with angle theta.

cswap(ctl, tgt1, tgt2)

Apply Fredkin to circuit.

cu1(theta, ctl, tgt)

Apply cu1 from ctl to tgt with angle theta.

cu3(theta, phi, lam, ctl, tgt)

Apply cu3 from ctl to tgt with angle theta, phi, lam.

cx(ctl, tgt)

Apply CX from ctl to tgt.

cy(ctl, tgt)

Apply CY to circuit.

cz(ctl, tgt)

Apply CZ to circuit.

decompose()[ソース]

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

戻り値

a circuit one level decomposed

戻り値の型

QuantumCircuit

depth()[ソース]

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

戻り値

Depth of circuit.

戻り値の型

int

メモ

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

diag_gate(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).

パラメータ
  • 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)

戻り値

the diagonal gate which was attached to the circuit.

戻り値の型

QuantumCircuit

例外

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(scale=0.7, filename=None, style=None, output=None, interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None, vertical_compression='medium', idle_wires=True, with_layout=True, fold=None, ax=None)[ソース]

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.

パラメータ
  • 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 that will be open, parsed, and then used just as the input dict. See: Style Dict Doc for more information on the contents.

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

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

  • line_length (int) -- Deprecated, see fold which supersedes this option. Sets the length of the lines generated by text output type. This 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 you're running in jupyter the default line length is set to 80 characters. If you don't want pagination at all, set line_length=-1.

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

戻り値

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

例外
  • VisualizationError -- when an invalid output method is selected

  • ImportError -- when the output methods requires 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:

パラメータ
  • 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. The default values are:

    {
        'id': '#F0E442',
        'u0': '#E7AB3B',
        'u1': '#E7AB3B',
        'u2': '#E7AB3B',
        'u3': '#E7AB3B',
        'x': '#58C698',
        'y': '#58C698',
        'z': '#58C698',
        'h': '#70B7EB',
        's': '#E0722D',
        'sdg': '#E0722D',
        't': '#E0722D',
        'tdg': '#E0722D',
        'rx': '#ffffff',
        'ry': '#ffffff',
        'rz': '#ffffff',
        'reset': '#D188B4',
        'target': '#70B7EB',
        'meas': '#D188B4'
    }
    

    Also, just like displaytext there is no provision for an incomplete dict passed in.

  • 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

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.

パラメータ

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

戻り値

Returns this QuantumCircuit object (which has been modified)

戻り値の型

QuantumCircuit

例外

QiskitError -- if the rhs circuit is not compatible

fredkin(ctl, tgt1, tgt2)

Apply Fredkin to circuit.

static from_qasm_file(path)[ソース]

Take in a QASM file and generate a QuantumCircuit object.

パラメータ

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

戻り値

The QuantumCircuit object for the input QASM

戻り値の型

QuantumCircuit

static from_qasm_str(qasm_str)[ソース]

Take in a QASM string and generate a QuantumCircuit object.

パラメータ

qasm_str (str) -- A QASM program string

戻り値

The QuantumCircuit object for the input QASM

戻り値の型

QuantumCircuit

h(q)

Apply H to q.

has_register(register)[ソース]

Test if this circuit has the register r.

パラメータ

register (Register) -- a quantum or classical register.

戻り値

True if the register is contained in this circuit.

戻り値の型

bool

iden(q)

Apply Identity to q.

Identity gate corresponds to a single-qubit gate wait cycle, and should not be optimized or unrolled (it is an opaque gate).

initialize(params, qubits)

Apply initialize to circuit.

inverse()[ソース]

Invert this circuit.

This is done by recursively inverting all gates.

戻り値

the inverted circuit

戻り値の型

QuantumCircuit

例外

CircuitError -- if the circuit cannot be inverted.

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.

パラメータ
  • 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.

戻り値

the isometry is attached to the quantum circuit.

戻り値の型

QuantumCircuit

例外

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

mcmt(q_controls, q_ancillae, single_control_gate_fun, q_targets, mode='basic')

Apply a Multi-Control, Multi-Target using a generic gate. It can also be used to implement a generic Multi-Control gate, as the target could also be of length 1.

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the mcmt gate on.

  • q_controls (Union(QuantumRegister, list[Qubit])) -- The list of control qubits

  • q_ancillae (Union(QuantumRegister, list[Qubit])) -- The list of ancillary qubits

  • single_control_gate_fun (Gate) -- The single control gate function (e.g QuantumCircuit.cz or QuantumCircuit.ch)

  • q_targets (Union(QuantumRegister, list[Qubit])) -- A list of qubits or a QuantumRegister to which the gate function should be applied.

  • mode (str) -- The implementation mode to use (at the moment, only the basic mode is supported)

例外

AquaError -- invalid input

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

Apply Multiple-Controlled X rotation gate

パラメータ
  • 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 basis gates

例外

AquaError -- invalid input

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

Apply Multiple-Controlled Y rotation gate

パラメータ
  • 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 (Union(QuantumRegister,tuple(QuantumRegister, int))) -- The list of ancillary qubits.

  • mode (str) -- The implementation mode to use

  • use_basis_gates (bool) -- use basis gates

例外

AquaError -- invalid input

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

Apply Multiple-Controlled Z rotation gate

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the mcrz gate on.

  • lam (float) -- angle lam

  • q_controls (list[Qubit]) -- The list of control qubits

  • q_target (Qubit) -- The target qubit

  • use_basis_gates (bool) -- use basis gates

例外

AquaError -- invalid input

mct(q_controls, q_target, q_ancilla, mode='basic')

Apply Multiple-Control Toffoli operation

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the mct gate on.

  • q_controls (Union(QuantumRegister, list[Qubit])) -- The list of control qubits

  • q_target (Qubit) -- The target qubit

  • q_ancilla (Union(QuantumRegister, list[Qubit])) -- The list of ancillary qubits

  • mode (str) -- The implementation mode to use

例外

AquaError -- invalid input

mcu1(lam, control_qubits, target_qubit)

Apply Multiple-Controlled U1 gate

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the mcu1 gate on.

  • lam (float) -- angle lambda

  • control_qubits (list[Qubit]) -- The list of control qubits

  • target_qubit (Qubit) -- The target qubit

measure(qubit, cbit)

Measure quantum bit into classical bit (tuples).

パラメータ
  • qubit (QuantumRegister|list|tuple) -- quantum register

  • cbit (ClassicalRegister|list|tuple) -- classical register

戻り値

the attached measure instruction.

戻り値の型

qiskit.Instruction

例外

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

measure_active()[ソース]

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

measure_all()[ソース]

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

mirror()[ソース]

Mirror the circuit by reversing the instructions.

This is done by recursively mirroring all instructions. It does not invert any gate.

戻り値

the mirrored circuit

戻り値の型

QuantumCircuit

ms(theta, qubits)

Apply MS to q1 and q2.

num_connected_components(unitary_only=False)[ソース]

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

パラメータ

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

戻り値

Number of connected components in circuit.

戻り値の型

int

num_tensor_factors()[ソース]

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

メモ

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()[ソース]

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

qasm()[ソース]

Return OpenQASM string.

qbit_argument_conversion(qubit_representation)[ソース]

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

パラメータ

qubit_representation (Object) -- representation to expand

戻り値

Where each tuple is a qubit.

戻り値の型

List(tuple)

r(theta, phi, q)

Apply R to q.

rcccx(q_control_1, q_control_2, q_control_3, q_target)

Apply 3-Control Relative-Phase Toffoli gate from q_control_1, q_control_2, and q_control_3 to q_target.

The implementation is based on https://arxiv.org/pdf/1508.03273.pdf Figure 4

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the rcccx gate on.

  • q_control_1 (Qubit) -- The 1st control qubit.

  • q_control_2 (Qubit) -- The 2nd control qubit.

  • q_control_3 (Qubit) -- The 3rd control qubit.

  • q_target (Qubit) -- The target qubit.

例外

AquaError -- invalid input

rccx(q_control_1, q_control_2, q_target)

Apply 2-Control Relative-Phase Toffoli gate from q_control_1 and q_control_2 to q_target.

The implementation is based on https://arxiv.org/pdf/1508.03273.pdf Figure 3

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the rccx gate on.

  • q_control_1 (Qubit) -- The 1st control qubit.

  • q_control_2 (Qubit) -- The 2nd control qubit.

  • q_target (Qubit) -- The target qubit.

例外

AquaError -- invalid input

remove_final_measurements()[ソース]

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.

reset(qubit)

Reset q.

rx(theta, q)

Apply Rx to q.

rxx(theta, qubit1, qubit2)

Apply RXX to circuit.

ry(theta, q)

Apply Ry to q.

rz(phi, q)

Apply Rz to q.

rzz(theta, qubit1, qubit2)

Apply RZZ to circuit.

s(q)

Apply S to q.

sdg(q)

Apply Sdg to q.

size()[ソース]

Returns total number of gate operations in circuit.

戻り値

Total number of gate operations.

戻り値の型

int

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

For other types of snapshots use the Snapshot extension directly.

パラメータ
  • label (str) -- a snapshot label to report the result

  • snapshot_type (str) -- the type of the snapshot.

  • qubits (list or None) -- the qubits to apply snapshot to [Default: None].

  • params (list or None) -- the parameters for snapshot_type [Default: None].

戻り値

with attached command

戻り値の型

QuantumCircuit

例外

ExtensionError -- malformed command

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

Decompose an arbitrary 2*2 unitary into three rotation gates \(U=R_zR_yR_z\).

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".)

パラメータ
  • u (ndarray) -- 2*2 unitary (given as a (complex) ndarray)

  • qubit (QuantumRegister|Qubit) -- the qubit, on 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')

戻り値

the single-qubit unitary (up to a diagonal gate if up_to_diagonal = True) is attached to the circuit.

戻り値の型

QuantumCircuit

例外

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

swap(qubit1, qubit2)

Apply SWAP from qubit1 to qubit2.

t(q)

Apply T to q.

tdg(q)

Apply Tdg to q.

to_gate(parameter_map=None)[ソース]

Create a Gate out of this circuit.

パラメータ

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.

戻り値

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

戻り値の型

Gate

to_instruction(parameter_map=None)[ソース]

Create an Instruction out of this circuit.

パラメータ

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.

戻り値

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

戻り値の型

Instruction

toffoli(ctl1, ctl2, tgt)

Apply Toffoli to ctl1 and ctl2 to tgt.

u1(theta, q)

Apply u1 with angle theta to q.

u2(phi, lam, q)

Apply u2 to q.

u3(theta, phi, lam, q)

Apply u3 to q.

ucg(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.

パラメータ
  • 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

戻り値

the uniformly controlled gate is attached to the circuit.

戻り値の型

QuantumCircuit

例外

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

ucx(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.

パラメータ
  • angle_list (list) -- list of (real) rotation angles [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[1],q[2]] (with q = QuantumRegister(2)), the rotation Rx(a_0)is performed if q[1] and q[2] are in the state zero, the rotation Rx(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

戻り値

the uniformly controlled rotation gate is attached to the circuit.

戻り値の型

QuantumCircuit

例外

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

ucy(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.

パラメータ
  • 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 Ry(a_0)is performed if q[1] and q[2] are in the state zero, the rotation Ry(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

戻り値

the uniformly controlled rotation gate is attached to the circuit.

戻り値の型

QuantumCircuit

例外

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

ucz(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.

パラメータ
  • 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

戻り値

the uniformly controlled rotation gate is attached to the circuit.

戻り値の型

QuantumCircuit

例外

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(obj, qubits, label=None)

Apply u2 to q.

width()[ソース]

Return number of qubits plus clbits in circuit.

戻り値

Width of circuit.

戻り値の型

int

x(q)

Apply X to q.

y(q)

Apply Y to q.

z(q)

Apply Z to q.

AND(qr_variables, qb_target, qr_ancillae, flags=None, mct_mode='basic')

Build a collective conjunction (AND) circuit in place using mct.

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to build the conjunction on.

  • qr_variables (QuantumRegister) -- The QuantumRegister holding the variable qubits.

  • qb_target (Qubit) -- The target qubit to hold the conjunction result.

  • qr_ancillae (QuantumRegister) -- The ancillary QuantumRegister for building the mct.

  • flags (list[int]) -- A list of +1/-1/0 to mark negations or omissions of qubits.

  • mct_mode (str) -- The mct building mode.

OR(qr_variables, qb_target, qr_ancillae, flags=None, mct_mode='basic')

Build a collective disjunction (OR) circuit in place using mct.

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to build the disjunction on.

  • qr_variables (QuantumRegister) -- The QuantumRegister holding the variable qubits.

  • flags (list[int]) -- A list of +1/-1/0 to mark negations or omissions of qubits.

  • qb_target (Qubit) -- The target qubit to hold the disjunction result.

  • qr_ancillae (QuantumRegister) -- The ancillary QuantumRegister for building the mct.

  • mct_mode (str) -- The mct building mode.

add_register(*regs)[ソース]

Add registers.

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.

パラメータ
  • instruction (Instruction or Operation) -- Instruction instance to append

  • qargs (list(argument)) -- qubits to attach instruction to

  • cargs (list(argument)) -- clbits to attach instruction to

戻り値

a handle to the instruction that was just added

戻り値の型

Instruction

barrier(*qargs)

Apply barrier to circuit. If qargs is None, applies to all the qbits. Args is a list of QuantumRegister or single qubits. For QuantumRegister, applies barrier to all the qubits in that register.

bind_parameters(value_dict)[ソース]

Assign parameters to values yielding a new circuit.

パラメータ

value_dict (dict) -- {parameter: value, ...}

例外

CircuitError -- If value_dict contains parameters not present in the circuit

戻り値

copy of self with assignment substitution.

戻り値の型

QuantumCircuit

static cast(value, _type)[ソース]

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

cbit_argument_conversion(clbit_representation)[ソース]

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

パラメータ

clbit_representation (Object) -- representation to expand

戻り値

Where each tuple is a classical bit.

戻り値の型

List(tuple)

ccx(ctl1, ctl2, tgt)

Apply Toffoli to ctl1 and ctl2 to tgt.

ch(ctl, tgt)

Apply CH from ctl to tgt.

property clbits

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

classmethod cls_instances()[ソース]

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

classmethod cls_prefix()[ソース]

Return the prefix to use for auto naming.

cnot(ctl, tgt)

Apply CX from ctl to tgt.

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.

パラメータ

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

戻り値

Returns a new QuantumCircuit object

戻り値の型

QuantumCircuit

例外

QiskitError -- if the rhs circuit is not compatible

copy(name=None)[ソース]

Copy the circuit.

パラメータ

name (str) -- name to be given to the copied circuit, if None then the name stays the same

戻り値

a deepcopy of the current circuit, with the specified name

戻り値の型

QuantumCircuit

count_ops()[ソース]

Count each operation kind in the circuit.

戻り値

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

戻り値の型

OrderedDict

cry(theta, q_control, q_target)

Apply Controlled-RY (cry) Gate.

パラメータ
  • self (QuantumCircuit) -- The circuit to apply the cry gate on.

  • theta (float) -- The rotation angle.

  • q_control (Union(Qubit, int)) -- The control qubit.

  • q_target (Union(Qubit, int)) -- The target qubit.

戻り値

instance self

戻り値の型

QuantumCircuit

例外

AquaError -- invalid input

crz(theta, ctl, tgt)

Apply crz from ctl to tgt with angle theta.

cswap(ctl, tgt1, tgt2)

Apply Fredkin to circuit.

cu1(theta, ctl, tgt)

Apply cu1 from ctl to tgt with angle theta.

cu3(theta, phi, lam, ctl, tgt)

Apply cu3 from ctl to tgt with angle theta, phi, lam.

cx(ctl, tgt)

Apply CX from ctl to tgt.

cy(ctl, tgt)

Apply CY to circuit.

cz(ctl, tgt)

Apply CZ to circuit.

property data

Return the circuit data (instructions and context).

戻り値

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.

戻り値の型

QuantumCircuitData

decompose()[ソース]

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

戻り値

a circuit one level decomposed

戻り値の型

QuantumCircuit

depth()[ソース]

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

戻り値

Depth of circuit.

戻り値の型

int

メモ

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

diag_gate(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).

パラメータ
  • 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)

戻り値

the diagonal gate which was attached to the circuit.

戻り値の型

QuantumCircuit

例外

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(scale=0.7, filename=None, style=None, output=None, interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None, vertical_compression='medium', idle_wires=True, with_layout=True, fold=None, ax=None)[ソース]

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.

パラメータ
  • 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 that will be open, parsed, and then used just as the input dict. See: Style Dict Doc for more information on the contents.

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

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

  • line_length (int) -- Deprecated, see fold which supersedes this option. Sets the length of the lines generated by text output type. This 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 you're running in jupyter the default line length is set to 80 characters. If you don't want pagination at all, set line_length=-1.

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

戻り値

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

例外
  • VisualizationError -- when an invalid output method is selected

  • ImportError -- when the output methods requires 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:

パラメータ
  • 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. The default values are:

    {
        'id': '#F0E442',
        'u0': '#E7AB3B',
        'u1': '#E7AB3B',
        'u2': '#E7AB3B',
        'u3': '#E7AB3B',
        'x': '#58C698',
        'y': '#58C698',
        'z': '#58C698',
        'h': '#70B7EB',
        's': '#E0722D',
        'sdg': '#E0722D',
        't': '#E0722D',
        'tdg': '#E0722D',
        'rx': '#ffffff',
        'ry': '#ffffff',
        'rz': '#ffffff',
        'reset': '#D188B4',
        'target': '#70B7EB',
        'meas': '#D188B4'
    }
    

    Also, just like displaytext there is no provision for an incomplete dict passed in.

  • 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

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.

パラメータ

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

戻り値

Returns this QuantumCircuit object (which has been modified)

戻り値の型

QuantumCircuit

例外

QiskitError -- if the rhs circuit is not compatible

fredkin(ctl, tgt1, tgt2)

Apply Fredkin to circuit.

static from_qasm_file(path)[ソース]

Take in a QASM file and generate a QuantumCircuit object.

パラメータ

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

戻り値

The QuantumCircuit object for the input QASM

戻り値の型

QuantumCircuit

static from_qasm_str(qasm_str)[ソース]

Take in a QASM string and generate a QuantumCircuit object.

パラメータ

qasm_str (str) -- A QASM program string

戻り値

The QuantumCircuit object for the input QASM

戻り値の型

QuantumCircuit

h(q)

Apply H to q.

has_register(register)[ソース]

Test if this circuit has the register r.

パラメータ

register (Register) -- a quantum or classical register.

戻り値

True if the register is contained in this circuit.

戻り値の型

bool

iden(q)

Apply Identity to q.

Identity gate corresponds to a single-qubit gate wait cycle, and should not be optimized or unrolled (it is an opaque gate).

initialize(params, qubits)

Apply initialize to circuit.

inverse()[ソース]

Invert this circuit.

This is done by recursively inverting all gates.

戻り値

the inverted circuit

戻り値の型

QuantumCircuit

例外

CircuitError -- if the circuit cannot be inverted.

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.

パラメータ
  • 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.

戻り値

the isometry is attached to the quantum circuit.

戻り値の型

QuantumCircuit

例外

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

mcmt(q_controls, q_ancillae, single_control_gate_fun, q_targets, mode='basic')

Apply a Multi-Control, Multi-Target using a generic gate. It can also be used to implement a generic Multi-Control gate, as the target could also be of length 1.

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the mcmt gate on.

  • q_controls (Union(QuantumRegister, list[Qubit])) -- The list of control qubits

  • q_ancillae (Union(QuantumRegister, list[Qubit])) -- The list of ancillary qubits

  • single_control_gate_fun (Gate) -- The single control gate function (e.g QuantumCircuit.cz or QuantumCircuit.ch)

  • q_targets (Union(QuantumRegister, list[Qubit])) -- A list of qubits or a QuantumRegister to which the gate function should be applied.

  • mode (str) -- The implementation mode to use (at the moment, only the basic mode is supported)

例外

AquaError -- invalid input

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

Apply Multiple-Controlled X rotation gate

パラメータ
  • 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 basis gates

例外

AquaError -- invalid input

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

Apply Multiple-Controlled Y rotation gate

パラメータ
  • 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 (Union(QuantumRegister,tuple(QuantumRegister, int))) -- The list of ancillary qubits.

  • mode (str) -- The implementation mode to use

  • use_basis_gates (bool) -- use basis gates

例外

AquaError -- invalid input

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

Apply Multiple-Controlled Z rotation gate

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the mcrz gate on.

  • lam (float) -- angle lam

  • q_controls (list[Qubit]) -- The list of control qubits

  • q_target (Qubit) -- The target qubit

  • use_basis_gates (bool) -- use basis gates

例外

AquaError -- invalid input

mct(q_controls, q_target, q_ancilla, mode='basic')

Apply Multiple-Control Toffoli operation

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the mct gate on.

  • q_controls (Union(QuantumRegister, list[Qubit])) -- The list of control qubits

  • q_target (Qubit) -- The target qubit

  • q_ancilla (Union(QuantumRegister, list[Qubit])) -- The list of ancillary qubits

  • mode (str) -- The implementation mode to use

例外

AquaError -- invalid input

mcu1(lam, control_qubits, target_qubit)

Apply Multiple-Controlled U1 gate

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the mcu1 gate on.

  • lam (float) -- angle lambda

  • control_qubits (list[Qubit]) -- The list of control qubits

  • target_qubit (Qubit) -- The target qubit

measure(qubit, cbit)

Measure quantum bit into classical bit (tuples).

パラメータ
  • qubit (QuantumRegister|list|tuple) -- quantum register

  • cbit (ClassicalRegister|list|tuple) -- classical register

戻り値

the attached measure instruction.

戻り値の型

qiskit.Instruction

例外

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

measure_active()[ソース]

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

measure_all()[ソース]

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

mirror()[ソース]

Mirror the circuit by reversing the instructions.

This is done by recursively mirroring all instructions. It does not invert any gate.

戻り値

the mirrored circuit

戻り値の型

QuantumCircuit

ms(theta, qubits)

Apply MS to q1 and q2.

property n_qubits

Return number of qubits.

num_connected_components(unitary_only=False)[ソース]

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

パラメータ

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

戻り値

Number of connected components in circuit.

戻り値の型

int

num_tensor_factors()[ソース]

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

メモ

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()[ソース]

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

property parameters

convenience function to get the parameters defined in the parameter table

qasm()[ソース]

Return OpenQASM string.

qbit_argument_conversion(qubit_representation)[ソース]

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

パラメータ

qubit_representation (Object) -- representation to expand

戻り値

Where each tuple is a qubit.

戻り値の型

List(tuple)

property qubits

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

r(theta, phi, q)

Apply R to q.

rcccx(q_control_1, q_control_2, q_control_3, q_target)

Apply 3-Control Relative-Phase Toffoli gate from q_control_1, q_control_2, and q_control_3 to q_target.

The implementation is based on https://arxiv.org/pdf/1508.03273.pdf Figure 4

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the rcccx gate on.

  • q_control_1 (Qubit) -- The 1st control qubit.

  • q_control_2 (Qubit) -- The 2nd control qubit.

  • q_control_3 (Qubit) -- The 3rd control qubit.

  • q_target (Qubit) -- The target qubit.

例外

AquaError -- invalid input

rccx(q_control_1, q_control_2, q_target)

Apply 2-Control Relative-Phase Toffoli gate from q_control_1 and q_control_2 to q_target.

The implementation is based on https://arxiv.org/pdf/1508.03273.pdf Figure 3

パラメータ
  • self (QuantumCircuit) -- The QuantumCircuit object to apply the rccx gate on.

  • q_control_1 (Qubit) -- The 1st control qubit.

  • q_control_2 (Qubit) -- The 2nd control qubit.

  • q_target (Qubit) -- The target qubit.

例外

AquaError -- invalid input

remove_final_measurements()[ソース]

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.

reset(qubit)

Reset q.

rx(theta, q)

Apply Rx to q.

rxx(theta, qubit1, qubit2)

Apply RXX to circuit.

ry(theta, q)

Apply Ry to q.

rz(phi, q)

Apply Rz to q.

rzz(theta, qubit1, qubit2)

Apply RZZ to circuit.

s(q)

Apply S to q.

sdg(q)

Apply Sdg to q.

size()[ソース]

Returns total number of gate operations in circuit.

戻り値

Total number of gate operations.

戻り値の型

int

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

For other types of snapshots use the Snapshot extension directly.

パラメータ
  • label (str) -- a snapshot label to report the result

  • snapshot_type (str) -- the type of the snapshot.

  • qubits (list or None) -- the qubits to apply snapshot to [Default: None].

  • params (list or None) -- the parameters for snapshot_type [Default: None].

戻り値

with attached command

戻り値の型

QuantumCircuit

例外

ExtensionError -- malformed command

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

Decompose an arbitrary 2*2 unitary into three rotation gates \(U=R_zR_yR_z\).

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".)

パラメータ
  • u (ndarray) -- 2*2 unitary (given as a (complex) ndarray)

  • qubit (QuantumRegister|Qubit) -- the qubit, on 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')

戻り値

the single-qubit unitary (up to a diagonal gate if up_to_diagonal = True) is attached to the circuit.

戻り値の型

QuantumCircuit

例外

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

swap(qubit1, qubit2)

Apply SWAP from qubit1 to qubit2.

t(q)

Apply T to q.

tdg(q)

Apply Tdg to q.

to_gate(parameter_map=None)[ソース]

Create a Gate out of this circuit.

パラメータ

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.

戻り値

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

戻り値の型

Gate

to_instruction(parameter_map=None)[ソース]

Create an Instruction out of this circuit.

パラメータ

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.

戻り値

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

戻り値の型

Instruction

toffoli(ctl1, ctl2, tgt)

Apply Toffoli to ctl1 and ctl2 to tgt.

u1(theta, q)

Apply u1 with angle theta to q.

u2(phi, lam, q)

Apply u2 to q.

u3(theta, phi, lam, q)

Apply u3 to q.

ucg(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.

パラメータ
  • 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

戻り値

the uniformly controlled gate is attached to the circuit.

戻り値の型

QuantumCircuit

例外

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

ucx(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.

パラメータ
  • angle_list (list) -- list of (real) rotation angles [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[1],q[2]] (with q = QuantumRegister(2)), the rotation Rx(a_0)is performed if q[1] and q[2] are in the state zero, the rotation Rx(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

戻り値

the uniformly controlled rotation gate is attached to the circuit.

戻り値の型

QuantumCircuit

例外

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

ucy(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.

パラメータ
  • 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 Ry(a_0)is performed if q[1] and q[2] are in the state zero, the rotation Ry(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

戻り値

the uniformly controlled rotation gate is attached to the circuit.

戻り値の型

QuantumCircuit

例外

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

ucz(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.

パラメータ
  • 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

戻り値

the uniformly controlled rotation gate is attached to the circuit.

戻り値の型

QuantumCircuit

例外

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(obj, qubits, label=None)

Apply u2 to q.

width()[ソース]

Return number of qubits plus clbits in circuit.

戻り値

Width of circuit.

戻り値の型

int

x(q)

Apply X to q.

y(q)

Apply Y to q.

z(q)

Apply Z to q.