Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
387
190k
source
stringlengths
32
125
--- title: assembler description: API reference for qiskit.assembler in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.assembler --- <span id="module-qiskit.assembler" /> <span id="qiskit-assembler" /> <span id="circuit-and-schedule-assembler-qiskit-assembler" /> # Circuit and Schedule Assembler <span id="module-qiskit.assembler" /> `qiskit.assembler` ## Circuit Assembler ### assemble\_circuits <Function id="qiskit.assembler.assemble_circuits" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/assembler/assemble_circuits.py#L302-L408" signature="qiskit.assembler.assemble_circuits(circuits, run_config, qobj_id, qobj_header)"> Assembles a list of circuits into a qobj that can be run on the backend. **Parameters** * **circuits** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")*]*) – circuit(s) to assemble * **run\_config** ([*RunConfig*](qiskit.assembler.RunConfig "qiskit.assembler.run_config.RunConfig")) – configuration of the runtime environment * **qobj\_id** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) – identifier for the generated qobj * **qobj\_header** ([*QobjHeader*](qiskit.qobj.QobjHeader "qiskit.qobj.common.QobjHeader")) – header to pass to the results **Returns** The qobj to be run on the backends **Return type** [*QasmQobj*](qiskit.qobj.QasmQobj "qiskit.qobj.qasm_qobj.QasmQobj") **Examples** ```python from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.assembler import assemble_circuits from qiskit.assembler.run_config import RunConfig # Build a circuit to convert into a Qobj q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) # Assemble a Qobj from the input circuit qobj = assemble_circuits(circuits=[qc], qobj_id="custom-id", qobj_header=[], run_config=RunConfig(shots=2000, memory=True, init_qubits=True)) ``` </Function> ## Schedule Assembler ### assemble\_schedules <Function id="qiskit.assembler.assemble_schedules" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/assembler/assemble_schedules.py#L27-L103" signature="qiskit.assembler.assemble_schedules(schedules, qobj_id, qobj_header, run_config)"> Assembles a list of schedules into a qobj that can be run on the backend. **Parameters** * **schedules** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock "qiskit.pulse.schedule.ScheduleBlock") *|*[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule") *|*[*Instruction*](pulse#qiskit.pulse.instructions.Instruction "qiskit.pulse.instructions.instruction.Instruction") *|*[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*,* [*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule") *|*[*Instruction*](pulse#qiskit.pulse.instructions.Instruction "qiskit.pulse.instructions.instruction.Instruction")*]]*) – Schedules to assemble. * **qobj\_id** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) – Identifier for the generated qobj. * **qobj\_header** ([*QobjHeader*](qiskit.qobj.QobjHeader "qiskit.qobj.common.QobjHeader")) – Header to pass to the results. * **run\_config** ([*RunConfig*](qiskit.assembler.RunConfig "qiskit.assembler.run_config.RunConfig")) – Configuration of the runtime environment. **Returns** The Qobj to be run on the backends. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") – when frequency settings are not supplied. **Return type** [*PulseQobj*](qiskit.qobj.PulseQobj "qiskit.qobj.pulse_qobj.PulseQobj") **Examples** ```python from qiskit import pulse from qiskit.assembler import assemble_schedules from qiskit.assembler.run_config import RunConfig # Construct a Qobj header for the output Qobj header = {"backend_name": "FakeOpenPulse2Q", "backend_version": "0.0.0"} # Build a configuration object for the output Qobj config = RunConfig(shots=1024, memory=False, meas_level=1, meas_return='avg', memory_slot_size=100, parametric_pulses=[], init_qubits=True, qubit_lo_freq=[4900000000.0, 5000000000.0], meas_lo_freq=[6500000000.0, 6600000000.0], schedule_los=[]) # Build a Pulse schedule to assemble into a Qobj schedule = pulse.Schedule() schedule += pulse.Play(pulse.Waveform([0.1] * 16, name="test0"), pulse.DriveChannel(0), name="test1") schedule += pulse.Play(pulse.Waveform([0.1] * 16, name="test1"), pulse.DriveChannel(0), name="test2") schedule += pulse.Play(pulse.Waveform([0.5] * 16, name="test0"), pulse.DriveChannel(0), name="test1") # Assemble a Qobj from the schedule. pulseQobj = assemble_schedules(schedules=[schedule], qobj_id="custom-id", qobj_header=header, run_config=config) ``` </Function> ## Disassembler ### disassemble <Function id="qiskit.assembler.disassemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/assembler/disassemble.py#L40-L83" signature="qiskit.assembler.disassemble(qobj)"> Disassemble a qobj and return the circuits or pulse schedules, run\_config, and user header. <Admonition title="Note" type="note"> `disassemble(assemble(qc))` is not guaranteed to produce an exactly equal circuit to the input, due to limitations in the [`QasmQobj`](qiskit.qobj.QasmQobj "qiskit.qobj.QasmQobj") format that need to be maintained for backend system compatibility. This is most likely to be the case when using newer features of [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"). In most cases, the output should be equivalent, if not quite equal. </Admonition> **Parameters** **qobj** (*Qobj*) – The input qobj object to disassemble **Returns** The disassembled program which consists of: > * programs: A list of quantum circuits or pulse schedules > * run\_config: The dict of the run config > * user\_qobj\_header: The dict of any user headers in the qobj **Return type** Union\[CircuitModule, PulseModule] **Examples** ```python from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler.assembler import assemble from qiskit.assembler.disassemble import disassemble # Create a circuit to assemble into a qobj q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) # Assemble the circuit into a Qobj qobj = assemble(qc, shots=2000, memory=True) # Disassemble the qobj back into a circuit circuits, run_config_out, headers = disassemble(qobj) ``` </Function> ## RunConfig | | | | -------------------------------------------------------------------------------------------------------------- | ---------------------------- | | [`RunConfig`](qiskit.assembler.RunConfig "qiskit.assembler.RunConfig")(\[shots, seed\_simulator, memory, ...]) | Class for Run Configuration. |
repo/docs/api/qiskit/1.0\assembler.mdx
--- title: circuit description: API reference for qiskit.circuit in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.circuit --- <span id="module-qiskit.circuit" /> <span id="qiskit-circuit" /> <span id="quantum-circuits-qiskit-circuit" /> # Quantum Circuits <span id="module-qiskit.circuit" /> `qiskit.circuit` ## Overview The fundamental element of quantum computing is the **quantum circuit**. A quantum circuit is a computational routine consisting of coherent quantum operations on quantum data, such as qubits. It is an ordered sequence of quantum gates, measurements and resets, which may be conditioned on real-time classical computation. A set of quantum gates is said to be universal if any unitary transformation of the quantum data can be efficiently approximated arbitrarily well as a sequence of gates in the set. Any quantum program can be represented by a sequence of quantum circuits and classical near-time computation. In Qiskit, this core element is represented by the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") class. Below is an example of a quantum circuit that makes a three-qubit GHZ state defined as: $$ |\psi\rangle = \left(|000\rangle+|111\rangle\right)/\sqrt{2} $$ ```python from qiskit import QuantumCircuit # Create a circuit with a register of three qubits circ = QuantumCircuit(3) # H gate on qubit 0, putting this qubit in a superposition of |0> + |1>. circ.h(0) # A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state. circ.cx(0, 1) # CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state. circ.cx(0, 2) # Draw the circuit circ.draw('mpl') ``` ![../\_images/circuit-1.png](/images/api/qiskit/1.0/circuit-1.png) ## Supplementary Information ### Quantum Circuit with conditionals When building a quantum circuit, there can be interest in applying a certain gate only if a classical register has a specific value. This can be done with the [`InstructionSet.c_if()`](qiskit.circuit.InstructionSet#c_if "qiskit.circuit.InstructionSet.c_if") method. In the following example, we start with a single-qubit circuit formed by only a Hadamard gate ([`HGate`](qiskit.circuit.library.HGate "qiskit.circuit.library.HGate")), in which we expect to get $|0\rangle$ and $|1\rangle$ with equal probability. ```python from qiskit import transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.draw('mpl') ``` ![../\_images/circuit-2.png](/images/api/qiskit/1.0/circuit-2.png) ```python from qiskit.providers.basic_provider import BasicSimulator backend = BasicSimulator() tqc = transpile(qc, backend) counts = backend.run(tqc).result().get_counts() print(counts) ``` ```python {'0': 524, '1': 500} ``` Now, we add an [`XGate`](qiskit.circuit.library.XGate "qiskit.circuit.library.XGate") only if the value of the [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister") is 0. That way, if the state is $|0\rangle$, it will be changed to $|1\rangle$ and if the state is $|1\rangle$, it will not be changed at all, so the final state will always be $|1\rangle$. ```python from qiskit import transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.x(0).c_if(cr, 0) qc.measure(0, 0) qc.draw('mpl') ``` ![../\_images/circuit-3.png](/images/api/qiskit/1.0/circuit-3.png) ```python from qiskit.providers.basic_provider import BasicSimulator backend = BasicSimulator() tqc = transpile(qc, backend) counts = backend.run(tqc).result().get_counts() print(counts) ``` ```python {'1': 1024} ``` ### Quantum Circuit Properties When constructing quantum circuits, there are several properties that help quantify the “size” of the circuits, and their ability to be run on a noisy quantum device. Some of these, like number of qubits, are straightforward to understand, while others like depth and number of tensor components require a bit more explanation. Here we will explain all of these properties, and, in preparation for understanding how circuits change when run on actual devices, highlight the conditions under which they change. Consider the following circuit: ```python from qiskit import QuantumCircuit qc = QuantumCircuit(12) for idx in range(5): qc.h(idx) qc.cx(idx, idx+5) qc.cx(1, 7) qc.x(8) qc.cx(1, 9) qc.x(7) qc.cx(1, 11) qc.swap(6, 11) qc.swap(6, 9) qc.swap(6, 10) qc.x(6) qc.draw('mpl') ``` ![../\_images/circuit-4.png](/images/api/qiskit/1.0/circuit-4.png) From the plot, it is easy to see that this circuit has 12 qubits, and a collection of Hadamard, CNOT, X, and SWAP gates. But how to quantify this programmatically? Because we can do single-qubit gates on all the qubits simultaneously, the number of qubits in this circuit is equal to the **width** of the circuit: ```python qc.width() ``` ```python 12 ``` We can also just get the number of qubits directly: ```python qc.num_qubits ``` ```python 12 ``` <Admonition title="Important" type="danger"> For a quantum circuit composed from just qubits, the circuit width is equal to the number of qubits. This is the definition used in quantum computing. However, for more complicated circuits with classical registers, and classically controlled gates, this equivalence breaks down. As such, from now on we will not refer to the number of qubits in a quantum circuit as the width. </Admonition> It is also straightforward to get the number and type of the gates in a circuit using [`QuantumCircuit.count_ops()`](qiskit.circuit.QuantumCircuit#count_ops "qiskit.circuit.QuantumCircuit.count_ops"): ```python qc.count_ops() ``` ```python OrderedDict([('cx', 8), ('h', 5), ('x', 3), ('swap', 3)]) ``` We can also get just the raw count of operations by computing the circuits [`QuantumCircuit.size()`](qiskit.circuit.QuantumCircuit#size "qiskit.circuit.QuantumCircuit.size"): ```python qc.size() ``` ```python 19 ``` A particularly important circuit property is known as the circuit **depth**. The depth of a quantum circuit is a measure of how many “layers” of quantum gates, executed in parallel, it takes to complete the computation defined by the circuit. Because quantum gates take time to implement, the depth of a circuit roughly corresponds to the amount of time it takes the quantum computer to execute the circuit. Thus, the depth of a circuit is one important quantity used to measure if a quantum circuit can be run on a device. The depth of a quantum circuit has a mathematical definition as the longest path in a directed acyclic graph (DAG). However, such a definition is a bit hard to grasp, even for experts. Fortunately, the depth of a circuit can be easily understood by anyone familiar with playing [Tetris](https://en.wikipedia.org/wiki/Tetris). Lets see how to compute this graphically: ![../\_images/depth.gif](/images/api/qiskit/1.0/depth.gif) We can verify our graphical result using [`QuantumCircuit.depth()`](qiskit.circuit.QuantumCircuit#depth "qiskit.circuit.QuantumCircuit.depth"): ```python qc.depth() ``` ```python 9 ``` ## Quantum Circuit API ### Quantum Circuit Construction | | | | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")(\*regs\[, name, global\_phase, ...]) | Create a new circuit. | | [`QuantumRegister`](qiskit.circuit.QuantumRegister "qiskit.circuit.QuantumRegister")(\[size, name, bits]) | Implement a quantum register. | | [`Qubit`](qiskit.circuit.Qubit "qiskit.circuit.Qubit")(\[register, index]) | Implement a quantum bit. | | [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister")(\[size, name, bits]) | Implement a classical register. | | [`Clbit`](qiskit.circuit.Clbit "qiskit.circuit.Clbit")(\[register, index]) | Implement a classical bit. | | [`AncillaRegister`](qiskit.circuit.AncillaRegister "qiskit.circuit.AncillaRegister")(\[size, name, bits]) | Implement an ancilla register. | | [`AncillaQubit`](qiskit.circuit.AncillaQubit "qiskit.circuit.AncillaQubit")(\[register, index]) | A qubit used as ancillary qubit. | | [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction") | A single instruction in a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"), comprised of the `operation` and various operands. | | [`Register`](qiskit.circuit.Register "qiskit.circuit.Register")(\[size, name, bits]) | Implement a generic register. | | [`Bit`](qiskit.circuit.Bit "qiskit.circuit.Bit")(\[register, index]) | Implement a generic bit. | ### Gates and Instructions | | | | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate")(name, num\_qubits, params\[, label, ...]) | Unitary gate. | | [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")(name, num\_qubits, params\[, ...]) | Controlled unitary gate. | | [`Delay`](qiskit.circuit.Delay "qiskit.circuit.Delay")(duration\[, unit]) | Do nothing and just delay/wait/idle for a specified duration. | | [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction")(name, num\_qubits, num\_clbits, params) | Generic quantum instruction. | | [`InstructionSet`](qiskit.circuit.InstructionSet "qiskit.circuit.InstructionSet")(\*\[, resource\_requester]) | Instruction collection, and their contexts. | | [`Operation`](qiskit.circuit.Operation "qiskit.circuit.Operation")() | Quantum Operation Interface Class. | | [`EquivalenceLibrary`](qiskit.circuit.EquivalenceLibrary "qiskit.circuit.EquivalenceLibrary")(\*\[, base]) | A library providing a one-way mapping of Gates to their equivalent implementations as QuantumCircuits. | ### Annotated Operations | | | | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation")(base\_op, modifiers) | Annotated operation. | | [`InverseModifier`](qiskit.circuit.InverseModifier "qiskit.circuit.InverseModifier")() | Inverse modifier: specifies that the operation is inverted. | | [`ControlModifier`](qiskit.circuit.ControlModifier "qiskit.circuit.ControlModifier")(\[num\_ctrl\_qubits, ctrl\_state]) | Control modifier: specifies that the operation is controlled by `num_ctrl_qubits` and has control state `ctrl_state`. | | [`PowerModifier`](qiskit.circuit.PowerModifier "qiskit.circuit.PowerModifier")(power) | Power modifier: specifies that the operation is raised to the power `power`. | ### Control Flow Operations | | | | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`ControlFlowOp`](qiskit.circuit.ControlFlowOp "qiskit.circuit.ControlFlowOp")(name, num\_qubits, num\_clbits, ...) | Abstract class to encapsulate all control flow operations. | | [`IfElseOp`](qiskit.circuit.IfElseOp "qiskit.circuit.IfElseOp")(condition, true\_body\[, false\_body, ...]) | A circuit operation which executes a program (`true_body`) if a provided condition (`condition`) evaluates to true, and optionally evaluates another program (`false_body`) otherwise. | | [`WhileLoopOp`](qiskit.circuit.WhileLoopOp "qiskit.circuit.WhileLoopOp")(condition, body\[, label]) | A circuit operation which repeatedly executes a subcircuit (`body`) until a condition (`condition`) evaluates as False. | | [`ForLoopOp`](qiskit.circuit.ForLoopOp "qiskit.circuit.ForLoopOp")(indexset, loop\_parameter, body\[, ...]) | A circuit operation which repeatedly executes a subcircuit (`body`) parameterized by a parameter `loop_parameter` through the set of integer values provided in `indexset`. | | [`SwitchCaseOp`](qiskit.circuit.SwitchCaseOp "qiskit.circuit.SwitchCaseOp")(target, cases, \*\[, label]) | A circuit operation that executes one particular circuit block based on matching a given `target` against an ordered list of `values`. | | [`BreakLoopOp`](qiskit.circuit.BreakLoopOp "qiskit.circuit.BreakLoopOp")(num\_qubits, num\_clbits\[, label]) | A circuit operation which, when encountered, jumps to the end of the nearest enclosing loop. | | [`ContinueLoopOp`](qiskit.circuit.ContinueLoopOp "qiskit.circuit.ContinueLoopOp")(num\_qubits, num\_clbits\[, label]) | A circuit operation which, when encountered, moves to the next iteration of the nearest enclosing loop. | The [`SwitchCaseOp`](qiskit.circuit.SwitchCaseOp "qiskit.circuit.SwitchCaseOp") also understands a special value: **qiskit.circuit.CASE\_DEFAULT** A special object that represents the “default” case of a switch statement. If you use this as a case target, it must be the last case, and will match anything that wasn’t already matched. For example: ```python from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import SwitchCaseOp, CASE_DEFAULT body0 = QuantumCircuit(2, 2) body0.x(0) body1 = QuantumCircuit(2, 2) body1.z(0) body2 = QuantumCircuit(2, 2) body2.cx(0, 1) qr, cr = QuantumRegister(2), ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.switch(cr, [(0, body0), (1, body1), (CASE_DEFAULT, body2)], qr, cr) ``` When using the builder interface of [`QuantumCircuit.switch()`](qiskit.circuit.QuantumCircuit#switch "qiskit.circuit.QuantumCircuit.switch"), this can also be accessed as the `DEFAULT` attribute of the bound case-builder object, such as: ```python from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qr, cr = QuantumRegister(2), ClassicalRegister(2) qc = QuantumCircuit(qr, cr) with qc.switch(cr) as case: with case(0): qc.x(0) with case(1): qc.z(0) with case(case.DEFAULT): qc.cx(0, 1) ``` ### Parametric Quantum Circuits | | | | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter")(name, \*\[, uuid]) | Parameter Class for variable parameters. | | [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector")(name\[, length]) | ParameterVector class to quickly generate lists of parameters. | | [`ParameterExpression`](qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")(symbol\_map, expr) | ParameterExpression class to enable creating expressions of Parameters. | ### Gate Commutation | | | | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | [`CommutationChecker`](qiskit.circuit.CommutationChecker "qiskit.circuit.CommutationChecker")(\[...]) | This code is essentially copy-pasted from commutative\_analysis.py. | ### Random Circuits #### random\_circuit <Function id="qiskit.circuit.random.random_circuit" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/random/utils.py#L23-L209" signature="qiskit.circuit.random.random_circuit(num_qubits, depth, max_operands=4, measure=False, conditional=False, reset=False, seed=None)"> Generate random circuit of arbitrary size and form. This function will generate a random circuit by randomly selecting gates from the set of standard gates in `qiskit.circuit.library.standard_gates`. For example: ```python from qiskit.circuit.random import random_circuit circ = random_circuit(2, 2, measure=True) circ.draw(output='mpl') ``` ![../\_images/circuit-5.png](/images/api/qiskit/1.0/circuit-5.png) **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) – number of quantum wires * **depth** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) – layers of operations (i.e. critical path length) * **max\_operands** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) – maximum qubit operands of each gate (between 1 and 4) * **measure** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) – if True, measure all qubits at the end * **conditional** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) – if True, insert middle measurements and conditionals * **reset** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) – if True, insert middle resets * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) – sets random seed (optional) **Returns** constructed circuit **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") **Raises** [**CircuitError**](#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") – when invalid options given </Function> ### Exceptions Almost all circuit functions and methods will raise a [`CircuitError`](#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") when encountering an error that is particular to usage of Qiskit (as opposed to regular typing or indexing problems, which will typically raise the corresponding standard Python error). #### CircuitError <Class id="qiskit.circuit.CircuitError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/exceptions.py#L18-L19" signature="qiskit.circuit.CircuitError(*message)" modifiers="exception"> Base class for errors raised while processing a circuit. Set the error message. </Class>
repo/docs/api/qiskit/1.0\circuit.mdx
--- title: classical description: API reference for qiskit.circuit.classical in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.circuit.classical --- <span id="module-qiskit.circuit.classical" /> <span id="qiskit-circuit-classical" /> <span id="classical-expressions-qiskit-circuit-classical" /> # Classical expressions <span id="module-qiskit.circuit.classical" /> `qiskit.circuit.classical` This module contains an exploratory representation of runtime operations on classical values during circuit execution. Currently, only simple expressions on bits and registers that result in a Boolean value are supported, and these are only valid for use in the conditions of [`QuantumCircuit.if_test()`](qiskit.circuit.QuantumCircuit#if_test "qiskit.circuit.QuantumCircuit.if_test") ([`IfElseOp`](qiskit.circuit.IfElseOp "qiskit.circuit.IfElseOp")) and [`QuantumCircuit.while_loop()`](qiskit.circuit.QuantumCircuit#while_loop "qiskit.circuit.QuantumCircuit.while_loop") ([`WhileLoopOp`](qiskit.circuit.WhileLoopOp "qiskit.circuit.WhileLoopOp")), and in the target of [`QuantumCircuit.switch()`](qiskit.circuit.QuantumCircuit#switch "qiskit.circuit.QuantumCircuit.switch") ([`SwitchCaseOp`](qiskit.circuit.SwitchCaseOp "qiskit.circuit.SwitchCaseOp")). <Admonition title="Note" type="note"> This is an exploratory module, and while we will commit to the standard Qiskit deprecation policy within it, please be aware that the module will be deliberately limited in scope at the start, and early versions may not evolve cleanly into the final version. It is possible that various components of this module will be replaced (subject to deprecations) instead of improved into a new form. The type system and expression tree will be expanded over time, and it is possible that the allowed types of some operations may need to change between versions of Qiskit as the classical processing capabilities develop. </Admonition> <span id="module-qiskit.circuit.classical.expr" /> <span id="expressions-qiskit-circuit-classical-expr" /> ## Expressions <span id="module-qiskit.circuit.classical" /> `qiskit.circuit.classical.expr` The necessary components for building expressions are all exported from the [`expr`](#module-qiskit.circuit.classical.expr "qiskit.circuit.classical.expr") namespace within [`qiskit.circuit.classical`](#module-qiskit.circuit.classical "qiskit.circuit.classical"), so you can choose whether to use qualified access (for example [`expr.Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.expr.Value")) or import the names you need directly and call them without the prefix. There are two pathways for constructing expressions. The classes that form [the representation of the expression system](#circuit-classical-expressions-expr-representation) have constructors that perform zero type checking; it is up to the caller to ensure that they are building valid objects. For a more user-friendly interface to direct construction, there are helper functions associated with most of the classes that do type validation and inference. These are described below, in [Construction](#circuit-classical-expressions-expr-construction). <span id="circuit-classical-expressions-expr-representation" /> ### Representation The expression system is based on tree representation. All nodes in the tree are final (uninheritable) instances of the abstract base class: #### Expr <Class id="qiskit.circuit.classical.expr.Expr" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/expr.py#L47-L79" signature="qiskit.circuit.classical.expr.Expr" modifiers="class"> Root base class of all nodes in the expression tree. The base case should never be instantiated directly. This must not be subclassed by users; subclasses form the internal data of the representation of expressions, and it does not make sense to add more outside of Qiskit library code. All subclasses are responsible for setting their `type` attribute in their `__init__`, and should not call the parent initialiser. </Class> These objects are mutable and should not be reused in a different location without a copy. The entry point from general circuit objects to the expression system is by wrapping the object in a [`Var`](#qiskit.circuit.classical.expr.Var "qiskit.circuit.classical.expr.Var") node and associating a [`Type`](#qiskit.circuit.classical.types.Type "qiskit.circuit.classical.types.Type") with it. #### Var <Class id="qiskit.circuit.classical.expr.Var" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/expr.py#L109-L168" signature="qiskit.circuit.classical.expr.Var(var, type)" modifiers="final class"> A classical variable. Variables are immutable after construction, so they can be used as dictionary keys. </Class> Similarly, literals used in comparison (such as integers) should be lifted to [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes with associated types. #### Value <Class id="qiskit.circuit.classical.expr.Value" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/expr.py#L171-L188" signature="qiskit.circuit.classical.expr.Value(value, type)" modifiers="final class"> A single scalar value. </Class> The operations traditionally associated with pre-, post- or infix operators in programming are represented by the [`Unary`](#qiskit.circuit.classical.expr.Unary "qiskit.circuit.classical.expr.Unary") and [`Binary`](#qiskit.circuit.classical.expr.Binary "qiskit.circuit.classical.expr.Binary") nodes as appropriate. These each take an operation type code, which are exposed as enumerations inside each class as [`Unary.Op`](#qiskit.circuit.classical.expr.Unary.Op "qiskit.circuit.classical.expr.Unary.Op") and [`Binary.Op`](#qiskit.circuit.classical.expr.Binary.Op "qiskit.circuit.classical.expr.Binary.Op") respectively. #### Unary <Class id="qiskit.circuit.classical.expr.Unary" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/expr.py#L191-L244" signature="qiskit.circuit.classical.expr.Unary(op, operand, type)" modifiers="final class"> A unary expression. **Parameters** * **op** ([*Unary.Op*](#qiskit.circuit.classical.expr.Unary.Op "qiskit.circuit.classical.expr.Unary.Op")) – The opcode describing which operation is being done. * **operand** ([*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.Expr")) – The operand of the operation. * **type** ([*Type*](#qiskit.circuit.classical.types.Type "qiskit.circuit.classical.types.types.Type")) – The resolved type of the result. ##### Op <Class id="qiskit.circuit.classical.expr.Unary.Op" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/expr.py#L203-L225" signature="Op(value)" modifiers="class"> Enumeration of the opcodes for unary operations. The bitwise negation [`BIT_NOT`](#qiskit.circuit.classical.expr.Unary.Op.BIT_NOT "qiskit.circuit.classical.expr.Unary.Op.BIT_NOT") takes a single bit or an unsigned integer of known width, and returns a value of the same type. The logical negation [`LOGIC_NOT`](#qiskit.circuit.classical.expr.Unary.Op.LOGIC_NOT "qiskit.circuit.classical.expr.Unary.Op.LOGIC_NOT") takes an input that is implicitly coerced to a Boolean, and returns a Boolean. ###### BIT\_NOT <Attribute id="qiskit.circuit.classical.expr.Unary.Op.BIT_NOT" attributeValue="1"> Bitwise negation. `~operand`. </Attribute> ###### LOGIC\_NOT <Attribute id="qiskit.circuit.classical.expr.Unary.Op.LOGIC_NOT" attributeValue="2"> Logical negation. `!operand`. </Attribute> </Class> </Class> #### Binary <Class id="qiskit.circuit.classical.expr.Binary" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/expr.py#L247-L327" signature="qiskit.circuit.classical.expr.Binary(op, left, right, type)" modifiers="final class"> A binary expression. **Parameters** * **op** ([*Binary.Op*](#qiskit.circuit.classical.expr.Binary.Op "qiskit.circuit.classical.expr.Binary.Op")) – The opcode describing which operation is being done. * **left** ([*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.Expr")) – The left-hand operand. * **right** ([*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.Expr")) – The right-hand operand. * **type** ([*Type*](#qiskit.circuit.classical.types.Type "qiskit.circuit.classical.types.types.Type")) – The resolved type of the result. ##### Op <Class id="qiskit.circuit.classical.expr.Binary.Op" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/expr.py#L260-L306" signature="Op(value)" modifiers="class"> Enumeration of the opcodes for binary operations. The bitwise operations [`BIT_AND`](#qiskit.circuit.classical.expr.Binary.Op.BIT_AND "qiskit.circuit.classical.expr.Binary.Op.BIT_AND"), [`BIT_OR`](#qiskit.circuit.classical.expr.Binary.Op.BIT_OR "qiskit.circuit.classical.expr.Binary.Op.BIT_OR") and [`BIT_XOR`](#qiskit.circuit.classical.expr.Binary.Op.BIT_XOR "qiskit.circuit.classical.expr.Binary.Op.BIT_XOR") apply to two operands of the same type, which must be a single bit or an unsigned integer of fixed width. The resultant type is the same as the two input types. The logical operations [`LOGIC_AND`](#qiskit.circuit.classical.expr.Binary.Op.LOGIC_AND "qiskit.circuit.classical.expr.Binary.Op.LOGIC_AND") and [`LOGIC_OR`](#qiskit.circuit.classical.expr.Binary.Op.LOGIC_OR "qiskit.circuit.classical.expr.Binary.Op.LOGIC_OR") first implicitly coerce their arguments to Booleans, and then apply the logical operation. The resultant type is always Boolean. The binary mathematical relations [`EQUAL`](#qiskit.circuit.classical.expr.Binary.Op.EQUAL "qiskit.circuit.classical.expr.Binary.Op.EQUAL"), [`NOT_EQUAL`](#qiskit.circuit.classical.expr.Binary.Op.NOT_EQUAL "qiskit.circuit.classical.expr.Binary.Op.NOT_EQUAL"), [`LESS`](#qiskit.circuit.classical.expr.Binary.Op.LESS "qiskit.circuit.classical.expr.Binary.Op.LESS"), [`LESS_EQUAL`](#qiskit.circuit.classical.expr.Binary.Op.LESS_EQUAL "qiskit.circuit.classical.expr.Binary.Op.LESS_EQUAL"), [`GREATER`](#qiskit.circuit.classical.expr.Binary.Op.GREATER "qiskit.circuit.classical.expr.Binary.Op.GREATER") and [`GREATER_EQUAL`](#qiskit.circuit.classical.expr.Binary.Op.GREATER_EQUAL "qiskit.circuit.classical.expr.Binary.Op.GREATER_EQUAL") take unsigned integers (with an implicit cast to make them the same width), and return a Boolean. ###### BIT\_AND <Attribute id="qiskit.circuit.classical.expr.Binary.Op.BIT_AND" attributeValue="1"> Bitwise “and”. `lhs & rhs`. </Attribute> ###### BIT\_OR <Attribute id="qiskit.circuit.classical.expr.Binary.Op.BIT_OR" attributeValue="2"> Bitwise “or”. `lhs | rhs`. </Attribute> ###### BIT\_XOR <Attribute id="qiskit.circuit.classical.expr.Binary.Op.BIT_XOR" attributeValue="3"> Bitwise “exclusive or”. `lhs ^ rhs`. </Attribute> ###### LOGIC\_AND <Attribute id="qiskit.circuit.classical.expr.Binary.Op.LOGIC_AND" attributeValue="4"> Logical “and”. `lhs && rhs`. </Attribute> ###### LOGIC\_OR <Attribute id="qiskit.circuit.classical.expr.Binary.Op.LOGIC_OR" attributeValue="5"> Logical “or”. `lhs || rhs`. </Attribute> ###### EQUAL <Attribute id="qiskit.circuit.classical.expr.Binary.Op.EQUAL" attributeValue="6"> Numeric equality. `lhs == rhs`. </Attribute> ###### NOT\_EQUAL <Attribute id="qiskit.circuit.classical.expr.Binary.Op.NOT_EQUAL" attributeValue="7"> Numeric inequality. `lhs != rhs`. </Attribute> ###### LESS <Attribute id="qiskit.circuit.classical.expr.Binary.Op.LESS" attributeValue="8"> Numeric less than. `lhs < rhs`. </Attribute> ###### LESS\_EQUAL <Attribute id="qiskit.circuit.classical.expr.Binary.Op.LESS_EQUAL" attributeValue="9"> Numeric less than or equal to. `lhs <= rhs` </Attribute> ###### GREATER <Attribute id="qiskit.circuit.classical.expr.Binary.Op.GREATER" attributeValue="10"> Numeric greater than. `lhs > rhs`. </Attribute> ###### GREATER\_EQUAL <Attribute id="qiskit.circuit.classical.expr.Binary.Op.GREATER_EQUAL" attributeValue="11"> Numeric greater than or equal to. `lhs >= rhs`. </Attribute> </Class> </Class> When constructing expressions, one must ensure that the types are valid for the operation. Attempts to construct expressions with invalid types will raise a regular Python `TypeError`. Expressions in this system are defined to act only on certain sets of types. However, values may be cast to a suitable supertype in order to satisfy the typing requirements. In these cases, a node in the expression tree is used to represent the promotion. In all cases where operations note that they “implicitly cast” or “coerce” their arguments, the expression tree must have this node representing the conversion. #### Cast <Class id="qiskit.circuit.classical.expr.Cast" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/expr.py#L82-L106" signature="qiskit.circuit.classical.expr.Cast(operand, type, implicit=False)" modifiers="final class"> A cast from one type to another, implied by the use of an expression in a different context. </Class> <span id="circuit-classical-expressions-expr-construction" /> ### Construction Constructing the tree representation directly is verbose and easy to make a mistake with the typing. In many cases, much of the typing can be inferred, scalar values can automatically be promoted to [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") instances, and any required promotions can be resolved into suitable [`Cast`](#qiskit.circuit.classical.expr.Cast "qiskit.circuit.classical.expr.Cast") nodes. The functions and methods described in this section are a more user-friendly way to build the expression tree, while staying close to the internal representation. All these functions will automatically lift valid Python scalar values into corresponding [`Var`](#qiskit.circuit.classical.expr.Var "qiskit.circuit.classical.expr.Var") or [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") objects, and will resolve any required implicit casts on your behalf. If you want to directly use some scalar value as an [`Expr`](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.Expr") node, you can manually [`lift()`](#qiskit.circuit.classical.expr.lift "qiskit.circuit.classical.expr.lift") it yourself. #### lift <Function id="qiskit.circuit.classical.expr.lift" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L94-L147" signature="qiskit.circuit.classical.expr.lift(value, /, type=None)"> Lift the given Python `value` to a [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.expr.Value") or [`Var`](#qiskit.circuit.classical.expr.Var "qiskit.circuit.classical.expr.expr.Var"). If an explicit `type` is given, the typing in the output will reflect that. **Examples** Lifting simple circuit objects to be [`Var`](#qiskit.circuit.classical.expr.Var "qiskit.circuit.classical.expr.expr.Var") instances: ```python >>> from qiskit.circuit import Clbit, ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.lift(Clbit()) Var(<clbit>, Bool()) >>> expr.lift(ClassicalRegister(3, "c")) Var(ClassicalRegister(3, "c"), Uint(3)) ``` The type of the return value can be influenced, if the given value could be interpreted losslessly as the given type (use [`cast()`](#qiskit.circuit.classical.expr.cast "qiskit.circuit.classical.expr.cast") to perform a full set of casting operations, include lossy ones): ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr, types >>> expr.lift(ClassicalRegister(3, "c"), types.Uint(5)) Var(ClassicalRegister(3, "c"), Uint(5)) >>> expr.lift(5, types.Uint(4)) Value(5, Uint(4)) ``` **Return type** [Expr](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.Expr") </Function> You can manually specify casts in cases where the cast is allowed in explicit form, but may be lossy (such as the cast of a higher precision [`Uint`](#qiskit.circuit.classical.types.Uint "qiskit.circuit.classical.types.Uint") to a lower precision one). #### cast <Function id="qiskit.circuit.classical.expr.cast" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L150-L165" signature="qiskit.circuit.classical.expr.cast(operand, type, /)"> Create an explicit cast from the given value to the given type. **Examples** Add an explicit cast node that explicitly casts a higher precision type to a lower precision one: ```python >>> from qiskit.circuit.classical import expr, types >>> value = expr.value(5, types.Uint(32)) >>> expr.cast(value, types.Uint(8)) Cast(Value(5, types.Uint(32)), types.Uint(8), implicit=False) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> There are helper constructor functions for each of the unary operations. #### bit\_not <Function id="qiskit.circuit.classical.expr.bit_not" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L168-L183" signature="qiskit.circuit.classical.expr.bit_not(operand, /)"> Create a bitwise ‘not’ expression node from the given value, resolving any implicit casts and lifting the value into a [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") node if required. **Examples** Bitwise negation of a [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister"): ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_not(ClassicalRegister(3, "c")) Unary(Unary.Op.BIT_NOT, Var(ClassicalRegister(3, 'c'), Uint(3)), Uint(3)) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> #### logic\_not <Function id="qiskit.circuit.classical.expr.logic_not" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L186-L202" signature="qiskit.circuit.classical.expr.logic_not(operand, /)"> Create a logical ‘not’ expression node from the given value, resolving any implicit casts and lifting the value into a [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") node if required. **Examples** Logical negation of a [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister"): ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.logic_not(ClassicalRegister(3, "c")) Unary(Unary.Op.LOGIC_NOT, Cast(Var(ClassicalRegister(3, 'c'), Uint(3)), Bool(), implicit=True), Bool()) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> Similarly, the binary operations and relations have helper functions defined. #### bit\_and <Function id="qiskit.circuit.classical.expr.bit_and" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L258-L274" signature="qiskit.circuit.classical.expr.bit_and(left, right, /)"> Create a bitwise ‘and’ expression node from the given value, resolving any implicit casts and lifting the values into [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes if required. **Examples** Bitwise ‘and’ of a classical register and an integer literal: ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_and(ClassicalRegister(3, "c"), 0b111) Binary(Binary.Op.BIT_AND, Var(ClassicalRegister(3, 'c'), Uint(3)), Value(7, Uint(3)), Uint(3)) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> #### bit\_or <Function id="qiskit.circuit.classical.expr.bit_or" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L277-L293" signature="qiskit.circuit.classical.expr.bit_or(left, right, /)"> Create a bitwise ‘or’ expression node from the given value, resolving any implicit casts and lifting the values into [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes if required. **Examples** Bitwise ‘or’ of a classical register and an integer literal: ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_or(ClassicalRegister(3, "c"), 0b101) Binary(Binary.Op.BIT_OR, Var(ClassicalRegister(3, 'c'), Uint(3)), Value(5, Uint(3)), Uint(3)) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> #### bit\_xor <Function id="qiskit.circuit.classical.expr.bit_xor" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L296-L312" signature="qiskit.circuit.classical.expr.bit_xor(left, right, /)"> Create a bitwise ‘exclusive or’ expression node from the given value, resolving any implicit casts and lifting the values into [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes if required. **Examples** Bitwise ‘exclusive or’ of a classical register and an integer literal: ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_xor(ClassicalRegister(3, "c"), 0b101) Binary(Binary.Op.BIT_XOR, Var(ClassicalRegister(3, 'c'), Uint(3)), Value(5, Uint(3)), Uint(3)) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> #### logic\_and <Function id="qiskit.circuit.classical.expr.logic_and" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L322-L334" signature="qiskit.circuit.classical.expr.logic_and(left, right, /)"> Create a logical ‘and’ expression node from the given value, resolving any implicit casts and lifting the values into [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes if required. **Examples** Logical ‘and’ of two classical bits: ```python >>> from qiskit.circuit import Clbit >>> from qiskit.circuit.classical import expr >>> expr.logical_and(Clbit(), Clbit()) Binary(Binary.Op.LOGIC_AND, Var(<clbit 0>, Bool()), Var(<clbit 1>, Bool()), Bool()) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> #### logic\_or <Function id="qiskit.circuit.classical.expr.logic_or" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L337-L349" signature="qiskit.circuit.classical.expr.logic_or(left, right, /)"> Create a logical ‘or’ expression node from the given value, resolving any implicit casts and lifting the values into [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes if required. **Examples** Logical ‘or’ of two classical bits ```python >>> from qiskit.circuit import Clbit >>> from qiskit.circuit.classical import expr >>> expr.logical_and(Clbit(), Clbit()) Binary(Binary.Op.LOGIC_OR, Var(<clbit 0>, Bool()), Var(<clbit 1>, Bool()), Bool()) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> #### equal <Function id="qiskit.circuit.classical.expr.equal" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L360-L375" signature="qiskit.circuit.classical.expr.equal(left, right, /)"> Create an ‘equal’ expression node from the given value, resolving any implicit casts and lifting the values into [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes if required. **Examples** Equality between a classical register and an integer: ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.equal(ClassicalRegister(3, "c"), 7) Binary(Binary.Op.EQUAL, Var(ClassicalRegister(3, "c"), Uint(3)), Value(7, Uint(3)), Uint(3)) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> #### not\_equal <Function id="qiskit.circuit.classical.expr.not_equal" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L378-L393" signature="qiskit.circuit.classical.expr.not_equal(left, right, /)"> Create a ‘not equal’ expression node from the given value, resolving any implicit casts and lifting the values into [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes if required. **Examples** Inequality between a classical register and an integer: ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.not_equal(ClassicalRegister(3, "c"), 7) Binary(Binary.Op.NOT_EQUAL, Var(ClassicalRegister(3, "c"), Uint(3)), Value(7, Uint(3)), Uint(3)) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> #### less <Function id="qiskit.circuit.classical.expr.less" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L404-L419" signature="qiskit.circuit.classical.expr.less(left, right, /)"> Create a ‘less than’ expression node from the given value, resolving any implicit casts and lifting the values into [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes if required. **Examples** Query if a classical register is less than an integer: ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "c"), 5) Binary(Binary.Op.LESS, Var(ClassicalRegister(3, "c"), Uint(3)), Value(5, Uint(3)), Uint(3)) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> #### less\_equal <Function id="qiskit.circuit.classical.expr.less_equal" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L422-L437" signature="qiskit.circuit.classical.expr.less_equal(left, right, /)"> Create a ‘less than or equal to’ expression node from the given value, resolving any implicit casts and lifting the values into [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes if required. **Examples** Query if a classical register is less than or equal to another: ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "a"), ClassicalRegister(3, "b")) Binary(Binary.Op.LESS_EQUAL, Var(ClassicalRegister(3, "a"), Uint(3)), Var(ClassicalRegister(3, "b"), Uint(3)), Uint(3)) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> #### greater <Function id="qiskit.circuit.classical.expr.greater" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L440-L455" signature="qiskit.circuit.classical.expr.greater(left, right, /)"> Create a ‘greater than’ expression node from the given value, resolving any implicit casts and lifting the values into [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes if required. **Examples** Query if a classical register is greater than an integer: ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "c"), 5) Binary(Binary.Op.GREATER, Var(ClassicalRegister(3, "c"), Uint(3)), Value(5, Uint(3)), Uint(3)) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> #### greater\_equal <Function id="qiskit.circuit.classical.expr.greater_equal" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L458-L473" signature="qiskit.circuit.classical.expr.greater_equal(left, right, /)"> Create a ‘greater than or equal to’ expression node from the given value, resolving any implicit casts and lifting the values into [`Value`](#qiskit.circuit.classical.expr.Value "qiskit.circuit.classical.expr.Value") nodes if required. **Examples** Query if a classical register is greater than or equal to another: ```python >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "a"), ClassicalRegister(3, "b")) Binary(Binary.Op.GREATER_EQUAL, Var(ClassicalRegister(3, "a"), Uint(3)), Var(ClassicalRegister(3, "b"), Uint(3)), Uint(3)) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") </Function> Qiskit’s legacy method for specifying equality conditions for use in conditionals is to use a two-tuple of a [`Clbit`](qiskit.circuit.Clbit "qiskit.circuit.Clbit") or [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister") and an integer. This represents an exact equality condition, and there are no ways to specify any other relations. The helper function [`lift_legacy_condition()`](#qiskit.circuit.classical.expr.lift_legacy_condition "qiskit.circuit.classical.expr.lift_legacy_condition") converts this legacy format into the new expression syntax. #### lift\_legacy\_condition <Function id="qiskit.circuit.classical.expr.lift_legacy_condition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/constructors.py#L63-L91" signature="qiskit.circuit.classical.expr.lift_legacy_condition(condition, /)"> Lift a legacy two-tuple equality condition into a new-style [`Expr`](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.Expr"). **Examples** Taking an old-style conditional instruction and getting an [`Expr`](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.Expr") from its condition: ```python from qiskit.circuit import ClassicalRegister from qiskit.circuit.library import HGate from qiskit.circuit.classical import expr cr = ClassicalRegister(2) instr = HGate().c_if(cr, 3) lifted = expr.lift_legacy_condition(instr.condition) ``` **Return type** [Expr](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.Expr") </Function> ### Working with the expression tree A typical consumer of the expression tree wants to recursively walk through the tree, potentially statefully, acting on each node differently depending on its type. This is naturally a double-dispatch problem; the logic of ‘what is to be done’ is likely stateful and users should be free to define their own operations, yet each node defines ‘what is being acted on’. We enable this double dispatch by providing a base visitor class for the expression tree. #### ExprVisitor <Class id="qiskit.circuit.classical.expr.ExprVisitor" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/visitors.py#L30-L56" signature="qiskit.circuit.classical.expr.ExprVisitor" modifiers="class"> Base class for visitors to the [`Expr`](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.Expr") tree. Subclasses should override whichever of the `visit_*` methods that they are able to handle, and should be organised such that non-existent methods will never be called. ##### visit\_binary <Function id="qiskit.circuit.classical.expr.ExprVisitor.visit_binary" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/visitors.py#L52-L53" signature="visit_binary(node, /)"> **Return type** *\_T\_co* </Function> ##### visit\_cast <Function id="qiskit.circuit.classical.expr.ExprVisitor.visit_cast" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/visitors.py#L55-L56" signature="visit_cast(node, /)"> **Return type** *\_T\_co* </Function> ##### visit\_generic <Function id="qiskit.circuit.classical.expr.ExprVisitor.visit_generic" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/visitors.py#L40-L41" signature="visit_generic(node, /)"> **Return type** *\_T\_co* </Function> ##### visit\_unary <Function id="qiskit.circuit.classical.expr.ExprVisitor.visit_unary" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/visitors.py#L49-L50" signature="visit_unary(node, /)"> **Return type** *\_T\_co* </Function> ##### visit\_value <Function id="qiskit.circuit.classical.expr.ExprVisitor.visit_value" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/visitors.py#L46-L47" signature="visit_value(node, /)"> **Return type** *\_T\_co* </Function> ##### visit\_var <Function id="qiskit.circuit.classical.expr.ExprVisitor.visit_var" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/visitors.py#L43-L44" signature="visit_var(node, /)"> **Return type** *\_T\_co* </Function> </Class> Consumers of the expression tree should subclass the visitor, and override the `visit_*` methods that they wish to handle. Any non-overridden methods will call [`visit_generic()`](#qiskit.circuit.classical.expr.ExprVisitor.visit_generic "qiskit.circuit.classical.expr.ExprVisitor.visit_generic"), which unless overridden will raise a `RuntimeError` to ensure that you are aware if new nodes have been added to the expression tree that you are not yet handling. For the convenience of simple visitors that only need to inspect the variables in an expression and not the general structure, the iterator method [`iter_vars()`](#qiskit.circuit.classical.expr.iter_vars "qiskit.circuit.classical.expr.iter_vars") is provided. #### iter\_vars <Function id="qiskit.circuit.classical.expr.iter_vars" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/visitors.py#L82-L99" signature="qiskit.circuit.classical.expr.iter_vars(node)"> Get an iterator over the [`Var`](#qiskit.circuit.classical.expr.Var "qiskit.circuit.classical.expr.expr.Var") nodes referenced at any level in the given [`Expr`](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr"). **Examples** Print out the name of each [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister") encountered: ```python from qiskit.circuit import ClassicalRegister from qiskit.circuit.classical import expr cr1 = ClassicalRegister(3, "a") cr2 = ClassicalRegister(3, "b") for node in expr.iter_vars(expr.bit_and(expr.bit_not(cr1), cr2)): if isinstance(node.var, ClassicalRegister): print(node.var.name) ``` **Return type** [*Iterator*](https://docs.python.org/3/library/typing.html#typing.Iterator "(in Python v3.12)")\[[*Var*](#qiskit.circuit.classical.expr.Var "qiskit.circuit.classical.expr.expr.Var")] </Function> Two expressions can be compared for direct structural equality by using the built-in Python `==` operator. In general, though, one might want to compare two expressions slightly more semantically, allowing that the [`Var`](#qiskit.circuit.classical.expr.Var "qiskit.circuit.classical.expr.Var") nodes inside them are bound to different memory-location descriptions between two different circuits. In this case, one can use [`structurally_equivalent()`](#qiskit.circuit.classical.expr.structurally_equivalent "qiskit.circuit.classical.expr.structurally_equivalent") with two suitable “key” functions to do the comparison. #### structurally\_equivalent <Function id="qiskit.circuit.classical.expr.structurally_equivalent" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/expr/visitors.py#L168-L217" signature="qiskit.circuit.classical.expr.structurally_equivalent(left, right, left_var_key=None, right_var_key=None)"> Do these two expressions have exactly the same tree structure, up to some key function for the [`Var`](#qiskit.circuit.classical.expr.Var "qiskit.circuit.classical.expr.expr.Var") objects? In other words, are these two expressions the exact same trees, except we compare the `Var.var` fields by calling the appropriate `*_var_key` function on them, and comparing that output for equality. This function does not allow any semantic “equivalences” such as asserting that `a == b` is equivalent to `b == a`; the evaluation order of the operands could, in general, cause such a statement to be false (consider hypothetical `extern` functions that access global state). There’s no requirements on the key functions, except that their outputs should have general `__eq__` methods. If a key function returns `None`, the variable will be used verbatim instead. **Parameters** * **left** ([*expr.Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr")) – one of the [`Expr`](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") nodes. * **right** ([*expr.Expr*](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr")) – the other [`Expr`](#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.expr.Expr") node. * **left\_var\_key** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.12)")*\[\[*[*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)")*],* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)")*] | None*) – a callable whose output should be used when comparing `Var.var` attributes. If this argument is `None` or its output is `None` for a given variable in `left`, the variable will be used verbatim. * **right\_var\_key** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.12)")*\[\[*[*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)")*],* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)")*] | None*) – same as `left_var_key`, but used on the variables in `right` instead. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)") **Examples** Comparing two expressions for structural equivalence, with no remapping of the variables. These are different because the different [`Clbit`](qiskit.circuit.Clbit "qiskit.circuit.Clbit") instances compare differently: ```python >>> from qiskit.circuit import Clbit >>> from qiskit.circuit.classical import expr >>> left_bits = [Clbit(), Clbit()] >>> right_bits = [Clbit(), Clbit()] >>> left = expr.logic_and(expr.logic_not(left_bits[0]), left_bits[1]) >>> right = expr.logic_and(expr.logic_not(right_bits[0]), right_bits[1]) >>> expr.structurally_equivalent(left, right) False ``` Comparing the same two expressions, but this time using mapping functions that associate the bits with simple indices: ```python >>> left_key = {var: i for i, var in enumerate(left_bits)}.get >>> right_key = {var: i for i, var in enumerate(right_bits)}.get >>> expr.structurally_equivalent(left, right, left_key, right_key) True ``` </Function> <span id="module-qiskit.circuit.classical.types" /> <span id="typing-qiskit-circuit-classical-types" /> ## Typing <span id="module-qiskit.circuit.classical" /> `qiskit.circuit.classical.types` <span id="id1" /> ### Representation The type system of the expression tree is exposed through this module. This is inherently linked to the expression system in the [`expr`](#module-qiskit.circuit.classical.expr "qiskit.circuit.classical.expr") module, as most expressions can only be understood with the context of the types that they act on. All types inherit from an abstract base class: #### Type <Class id="qiskit.circuit.classical.types.Type" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/types/types.py#L49-L80" signature="qiskit.circuit.classical.types.Type" modifiers="class"> Root base class of all nodes in the type tree. The base case should never be instantiated directly. This must not be subclassed by users; subclasses form the internal data of the representation of expressions, and it does not make sense to add more outside of Qiskit library code. </Class> Types should be considered immutable objects, and you must not mutate them. It is permissible to reuse a [`Type`](#qiskit.circuit.classical.types.Type "qiskit.circuit.classical.types.Type") that you take from another object without copying it, and generally this will be the best approach for performance. [`Type`](#qiskit.circuit.classical.types.Type "qiskit.circuit.classical.types.Type") objects are designed to be small amounts of data, and it’s best to point to the same instance of the data where possible rather than heap-allocating a new version of the same thing. Where possible, the class constructors will return singleton instances to facilitate this. The two different types available are for Booleans (corresponding to [`Clbit`](qiskit.circuit.Clbit "qiskit.circuit.Clbit") and the literals `True` and `False`), and unsigned integers (corresponding to [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister") and Python integers). #### Bool <Class id="qiskit.circuit.classical.types.Bool" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/types/types.py#L83-L96" signature="qiskit.circuit.classical.types.Bool" modifiers="final class"> The Boolean type. This has exactly two values: `True` and `False`. </Class> #### Uint <Class id="qiskit.circuit.classical.types.Uint" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/types/types.py#L99-L117" signature="qiskit.circuit.classical.types.Uint(width)" modifiers="final class"> An unsigned integer of fixed bit width. </Class> Note that [`Uint`](#qiskit.circuit.classical.types.Uint "qiskit.circuit.classical.types.Uint") defines a family of types parametrised by their width; it is not one single type, which may be slightly different to the ‘classical’ programming languages you are used to. ### Working with types There are some functions on these types exposed here as well. These are mostly expected to be used only in manipulations of the expression tree; users who are building expressions using the [user-facing construction interface](#circuit-classical-expressions-expr-construction) should not need to use these. #### Partial ordering of types The type system is equipped with a partial ordering, where $a < b$ is interpreted as “$a$ is a strict subtype of $b$”. Note that the partial ordering is a subset of the directed graph that describes the allowed explicit casting operations between types. The partial ordering defines when one type may be lossless directly interpreted as another. The low-level interface to querying the subtyping relationship is the [`order()`](#qiskit.circuit.classical.types.order "qiskit.circuit.classical.types.order") function. ##### order <Function id="qiskit.circuit.classical.types.order" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/types/ordering.py#L76-L93" signature="qiskit.circuit.classical.types.order(left, right, /)"> Get the ordering relationship between the two types as an enumeration value. **Examples** Compare two [`Uint`](#qiskit.circuit.classical.types.Uint "qiskit.circuit.classical.types.Uint") types of different widths: ```python >>> from qiskit.circuit.classical import types >>> types.order(types.Uint(8), types.Uint(16)) Ordering.LESS ``` Compare two types that have no ordering between them: ```python >>> types.order(types.Uint(8), types.Bool()) Ordering.NONE ``` **Return type** [*Ordering*](#qiskit.circuit.classical.types.Ordering "qiskit.circuit.classical.types.ordering.Ordering") </Function> The return value is an enumeration [`Ordering`](#qiskit.circuit.classical.types.Ordering "qiskit.circuit.classical.types.Ordering") that describes what, if any, subtyping relationship exists between the two types. ##### Ordering <Class id="qiskit.circuit.classical.types.Ordering" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/types/ordering.py#L38-L55" signature="qiskit.circuit.classical.types.Ordering(value)" modifiers="class"> Enumeration listing the possible relations between two types. Types only have a partial ordering, so it’s possible for two types to have no sub-typing relationship. Note that the sub-/supertyping relationship is not the same as whether a type can be explicitly cast from one to another. </Class> Some helper methods are then defined in terms of this low-level [`order()`](#qiskit.circuit.classical.types.order "qiskit.circuit.classical.types.order") primitive: ##### is\_subtype <Function id="qiskit.circuit.classical.types.is_subtype" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/types/ordering.py#L96-L116" signature="qiskit.circuit.classical.types.is_subtype(left, right, /, strict=False)"> Does the relation $\text{left} \le \text{right}$ hold? If there is no ordering relation between the two types, then this returns `False`. If `strict`, then the equality is also forbidden. **Examples** Check if one type is a subclass of another: ```python >>> from qiskit.circuit.classical import types >>> types.is_subtype(types.Uint(8), types.Uint(16)) True ``` Check if one type is a strict subclass of another: ```python >>> types.is_subtype(types.Bool(), types.Bool()) True >>> types.is_subtype(types.Bool(), types.Bool(), strict=True) False ``` **Return type** [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)") </Function> ##### is\_supertype <Function id="qiskit.circuit.classical.types.is_supertype" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/types/ordering.py#L119-L139" signature="qiskit.circuit.classical.types.is_supertype(left, right, /, strict=False)"> Does the relation $\text{left} \ge \text{right}$ hold? If there is no ordering relation between the two types, then this returns `False`. If `strict`, then the equality is also forbidden. **Examples** Check if one type is a superclass of another: ```python >>> from qiskit.circuit.classical import types >>> types.is_supertype(types.Uint(8), types.Uint(16)) False ``` Check if one type is a strict superclass of another: ```python >>> types.is_supertype(types.Bool(), types.Bool()) True >>> types.is_supertype(types.Bool(), types.Bool(), strict=True) False ``` **Return type** [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)") </Function> ##### greater <Function id="qiskit.circuit.classical.types.greater" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/types/ordering.py#L142-L165" signature="qiskit.circuit.classical.types.greater(left, right, /)"> Get the greater of the two types, assuming that there is an ordering relation between them. Technically, this is a slightly restricted version of the concept of the ‘meet’ of the two types in that the return value must be one of the inputs. In practice in the type system there is no concept of a ‘sum’ type, so the ‘meet’ exists if and only if there is an ordering between the two types, and is equal to the greater of the two types. **Returns** The greater of the two types. **Raises** [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.12)") – if there is no ordering relation between the two types. **Return type** [*Type*](#qiskit.circuit.classical.types.Type "qiskit.circuit.classical.types.types.Type") **Examples** Find the greater of two [`Uint`](#qiskit.circuit.classical.types.Uint "qiskit.circuit.classical.types.Uint") types: ```python >>> from qiskit.circuit.classical import types >>> types.greater(types.Uint(8), types.Uint(16)) types.Uint(16) ``` </Function> #### Casting between types It is common to need to cast values of one type to another type. The casting rules for this are embedded into the [`types`](https://docs.python.org/3/library/types.html#module-types "(in Python v3.12)") module. You can query the casting kinds using [`cast_kind()`](#qiskit.circuit.classical.types.cast_kind "qiskit.circuit.classical.types.cast_kind"): ##### cast\_kind <Function id="qiskit.circuit.classical.types.cast_kind" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/types/ordering.py#L203-L222" signature="qiskit.circuit.classical.types.cast_kind(from_, to_, /)"> Determine the sort of cast that is required to move from the left type to the right type. **Examples** ```python >>> from qiskit.circuit.classical import types >>> types.cast_kind(types.Bool(), types.Bool()) <CastKind.EQUAL: 1> >>> types.cast_kind(types.Uint(8), types.Bool()) <CastKind.IMPLICIT: 2> >>> types.cast_kind(types.Bool(), types.Uint(8)) <CastKind.LOSSLESS: 3> >>> types.cast_kind(types.Uint(16), types.Uint(8)) <CastKind.DANGEROUS: 4> ``` **Return type** [*CastKind*](#qiskit.circuit.classical.types.CastKind "qiskit.circuit.classical.types.ordering.CastKind") </Function> The return values from this function are an enumeration explaining the types of cast that are allowed from the left type to the right type. ##### CastKind <Class id="qiskit.circuit.classical.types.CastKind" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classical/types/ordering.py#L168-L184" signature="qiskit.circuit.classical.types.CastKind(value)" modifiers="class"> A return value indicating the type of cast that can occur from one type to another. </Class>
repo/docs/api/qiskit/1.0\circuit_classical.mdx
--- title: library description: API reference for qiskit.circuit.library in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.circuit.library --- <span id="module-qiskit.circuit.library" /> <span id="qiskit-circuit-library" /> <span id="circuit-library-qiskit-circuit-library" /> # Circuit Library <span id="module-qiskit.circuit.library" /> `qiskit.circuit.library` The circuit library is a collection of well-studied and valuable circuits, directives, and gates. We call them valuable for different reasons, for instance they can serve as building blocks for algorithms or they are circuits that we think are hard to simulate classically. Each element can be plugged into a circuit using the [`QuantumCircuit.append()`](qiskit.circuit.QuantumCircuit#append "qiskit.circuit.QuantumCircuit.append") method and so the circuit library allows users to program at higher levels of abstraction. For example, to append a multi-controlled CNOT: ```python from qiskit.circuit.library import MCXGate gate = MCXGate(4) from qiskit import QuantumCircuit circuit = QuantumCircuit(5) circuit.append(gate, [0, 1, 4, 2, 3]) circuit.draw('mpl') ``` ![../\_images/circuit\_library-1.png](/images/api/qiskit/1.0/circuit_library-1.png) The library is organized in several sections. ## Standard gates These operations are reversible unitary gates and they all subclass [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). As a consequence, they all have the methods [`to_matrix()`](qiskit.circuit.Gate#to_matrix "qiskit.circuit.Gate.to_matrix"), [`power()`](qiskit.circuit.Gate#power "qiskit.circuit.Gate.power"), and [`control()`](qiskit.circuit.Gate#control "qiskit.circuit.Gate.control"), which we can generally only apply to unitary operations. For example: ```python from qiskit.circuit.library import XGate gate = XGate() print(gate.to_matrix()) # X gate print(gate.power(1/2).to_matrix()) # √X gate print(gate.control(1).to_matrix()) # CX (controlled X) gate ``` ```python [[0.+0.j 1.+0.j] [1.+0.j 0.+0.j]] [[0.5+0.5j 0.5-0.5j] [0.5-0.5j 0.5+0.5j]] [[1.+0.j 0.+0.j 0.+0.j 0.+0.j] [0.+0.j 0.+0.j 0.+0.j 1.+0.j] [0.+0.j 0.+0.j 1.+0.j 0.+0.j] [0.+0.j 1.+0.j 0.+0.j 0.+0.j]] ``` | | | | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | [`C3XGate`](qiskit.circuit.library.C3XGate "qiskit.circuit.library.C3XGate")(\*args\[, \_force\_mutable]) | The X gate controlled on 3 qubits. | | [`C3SXGate`](qiskit.circuit.library.C3SXGate "qiskit.circuit.library.C3SXGate")(\*args\[, \_force\_mutable]) | The 3-qubit controlled sqrt-X gate. | | [`C4XGate`](qiskit.circuit.library.C4XGate "qiskit.circuit.library.C4XGate")(\*args\[, \_force\_mutable]) | The 4-qubit controlled X gate. | | [`CCXGate`](qiskit.circuit.library.CCXGate "qiskit.circuit.library.CCXGate")(\*args\[, \_force\_mutable]) | CCX gate, also known as Toffoli gate. | | [`DCXGate`](qiskit.circuit.library.DCXGate "qiskit.circuit.library.DCXGate")(\*args\[, \_force\_mutable]) | Double-CNOT gate. | | [`CHGate`](qiskit.circuit.library.CHGate "qiskit.circuit.library.CHGate")(\*args\[, \_force\_mutable]) | Controlled-Hadamard gate. | | [`CPhaseGate`](qiskit.circuit.library.CPhaseGate "qiskit.circuit.library.CPhaseGate")(theta\[, label, ctrl\_state, ...]) | Controlled-Phase gate. | | [`CRXGate`](qiskit.circuit.library.CRXGate "qiskit.circuit.library.CRXGate")(theta\[, label, ctrl\_state, ...]) | Controlled-RX gate. | | [`CRYGate`](qiskit.circuit.library.CRYGate "qiskit.circuit.library.CRYGate")(theta\[, label, ctrl\_state, ...]) | Controlled-RY gate. | | [`CRZGate`](qiskit.circuit.library.CRZGate "qiskit.circuit.library.CRZGate")(theta\[, label, ctrl\_state, ...]) | Controlled-RZ gate. | | [`CSGate`](qiskit.circuit.library.CSGate "qiskit.circuit.library.CSGate")(\*args\[, \_force\_mutable]) | Controlled-S gate. | | [`CSdgGate`](qiskit.circuit.library.CSdgGate "qiskit.circuit.library.CSdgGate")(\*args\[, \_force\_mutable]) | Controlled-S^dagger gate. | | [`CSwapGate`](qiskit.circuit.library.CSwapGate "qiskit.circuit.library.CSwapGate")(\*args\[, \_force\_mutable]) | Controlled-SWAP gate, also known as the Fredkin gate. | | [`CSXGate`](qiskit.circuit.library.CSXGate "qiskit.circuit.library.CSXGate")(\*args\[, \_force\_mutable]) | Controlled-√X gate. | | [`CUGate`](qiskit.circuit.library.CUGate "qiskit.circuit.library.CUGate")(theta, phi, lam, gamma\[, label, ...]) | Controlled-U gate (4-parameter two-qubit gate). | | [`CU1Gate`](qiskit.circuit.library.CU1Gate "qiskit.circuit.library.CU1Gate")(theta\[, label, ctrl\_state, ...]) | Controlled-U1 gate. | | [`CU3Gate`](qiskit.circuit.library.CU3Gate "qiskit.circuit.library.CU3Gate")(theta, phi, lam\[, label, ...]) | Controlled-U3 gate (3-parameter two-qubit gate). | | [`CXGate`](qiskit.circuit.library.CXGate "qiskit.circuit.library.CXGate")(\*args\[, \_force\_mutable]) | Controlled-X gate. | | [`CYGate`](qiskit.circuit.library.CYGate "qiskit.circuit.library.CYGate")(\*args\[, \_force\_mutable]) | Controlled-Y gate. | | [`CZGate`](qiskit.circuit.library.CZGate "qiskit.circuit.library.CZGate")(\*args\[, \_force\_mutable]) | Controlled-Z gate. | | [`CCZGate`](qiskit.circuit.library.CCZGate "qiskit.circuit.library.CCZGate")(\*args\[, \_force\_mutable]) | CCZ gate. | | [`ECRGate`](qiskit.circuit.library.ECRGate "qiskit.circuit.library.ECRGate")(\*args\[, \_force\_mutable]) | An echoed cross-resonance gate. | | [`HGate`](qiskit.circuit.library.HGate "qiskit.circuit.library.HGate")(\*args\[, \_force\_mutable]) | Single-qubit Hadamard gate. | | [`IGate`](qiskit.circuit.library.IGate "qiskit.circuit.library.IGate")(\*args\[, \_force\_mutable]) | Identity gate. | | [`MSGate`](qiskit.circuit.library.MSGate "qiskit.circuit.library.MSGate")(num\_qubits, theta\[, label]) | MSGate has been deprecated. | | [`PhaseGate`](qiskit.circuit.library.PhaseGate "qiskit.circuit.library.PhaseGate")(theta\[, label, duration, unit]) | Single-qubit rotation about the Z axis. | | [`RCCXGate`](qiskit.circuit.library.RCCXGate "qiskit.circuit.library.RCCXGate")(\*args\[, \_force\_mutable]) | The simplified Toffoli gate, also referred to as Margolus gate. | | [`RC3XGate`](qiskit.circuit.library.RC3XGate "qiskit.circuit.library.RC3XGate")(\*args\[, \_force\_mutable]) | The simplified 3-controlled Toffoli gate. | | [`RGate`](qiskit.circuit.library.RGate "qiskit.circuit.library.RGate")(theta, phi\[, label, duration, unit]) | Rotation θ around the cos(φ)x + sin(φ)y axis. | | [`RXGate`](qiskit.circuit.library.RXGate "qiskit.circuit.library.RXGate")(theta\[, label, duration, unit]) | Single-qubit rotation about the X axis. | | [`RXXGate`](qiskit.circuit.library.RXXGate "qiskit.circuit.library.RXXGate")(theta\[, label, duration, unit]) | A parametric 2-qubit $X \otimes X$ interaction (rotation about XX). | | [`RYGate`](qiskit.circuit.library.RYGate "qiskit.circuit.library.RYGate")(theta\[, label, duration, unit]) | Single-qubit rotation about the Y axis. | | [`RYYGate`](qiskit.circuit.library.RYYGate "qiskit.circuit.library.RYYGate")(theta\[, label, duration, unit]) | A parametric 2-qubit $Y \otimes Y$ interaction (rotation about YY). | | [`RZGate`](qiskit.circuit.library.RZGate "qiskit.circuit.library.RZGate")(phi\[, label, duration, unit]) | Single-qubit rotation about the Z axis. | | [`RZZGate`](qiskit.circuit.library.RZZGate "qiskit.circuit.library.RZZGate")(theta\[, label, duration, unit]) | A parametric 2-qubit $Z \otimes Z$ interaction (rotation about ZZ). | | [`RZXGate`](qiskit.circuit.library.RZXGate "qiskit.circuit.library.RZXGate")(theta\[, label, duration, unit]) | A parametric 2-qubit $Z \otimes X$ interaction (rotation about ZX). | | [`XXMinusYYGate`](qiskit.circuit.library.XXMinusYYGate "qiskit.circuit.library.XXMinusYYGate")(theta\[, beta, label, ...]) | XX-YY interaction gate. | | [`XXPlusYYGate`](qiskit.circuit.library.XXPlusYYGate "qiskit.circuit.library.XXPlusYYGate")(theta\[, beta, label, duration, ...]) | XX+YY interaction gate. | | [`SGate`](qiskit.circuit.library.SGate "qiskit.circuit.library.SGate")(\*args\[, \_force\_mutable]) | Single qubit S gate (Z\*\*0.5). | | [`SdgGate`](qiskit.circuit.library.SdgGate "qiskit.circuit.library.SdgGate")(\*args\[, \_force\_mutable]) | Single qubit S-adjoint gate (\~Z\*\*0.5). | | [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")(\*args\[, \_force\_mutable]) | The SWAP gate. | | [`iSwapGate`](qiskit.circuit.library.iSwapGate "qiskit.circuit.library.iSwapGate")(\*args\[, \_force\_mutable]) | iSWAP gate. | | [`SXGate`](qiskit.circuit.library.SXGate "qiskit.circuit.library.SXGate")(\*args\[, \_force\_mutable]) | The single-qubit Sqrt(X) gate ($\sqrt{X}$). | | [`SXdgGate`](qiskit.circuit.library.SXdgGate "qiskit.circuit.library.SXdgGate")(\*args\[, \_force\_mutable]) | The inverse single-qubit Sqrt(X) gate. | | [`TGate`](qiskit.circuit.library.TGate "qiskit.circuit.library.TGate")(\*args\[, \_force\_mutable]) | Single qubit T gate (Z\*\*0.25). | | [`TdgGate`](qiskit.circuit.library.TdgGate "qiskit.circuit.library.TdgGate")(\*args\[, \_force\_mutable]) | Single qubit T-adjoint gate (\~Z\*\*0.25). | | [`UGate`](qiskit.circuit.library.UGate "qiskit.circuit.library.UGate")(theta, phi, lam\[, label, duration, unit]) | Generic single-qubit rotation gate with 3 Euler angles. | | [`U1Gate`](qiskit.circuit.library.U1Gate "qiskit.circuit.library.U1Gate")(theta\[, label, duration, unit]) | Single-qubit rotation about the Z axis. | | [`U2Gate`](qiskit.circuit.library.U2Gate "qiskit.circuit.library.U2Gate")(phi, lam\[, label, duration, unit]) | Single-qubit rotation about the X+Z axis. | | [`U3Gate`](qiskit.circuit.library.U3Gate "qiskit.circuit.library.U3Gate")(theta, phi, lam\[, label, duration, unit]) | Generic single-qubit rotation gate with 3 Euler angles. | | [`XGate`](qiskit.circuit.library.XGate "qiskit.circuit.library.XGate")(\*args\[, \_force\_mutable]) | The single-qubit Pauli-X gate ($\sigma_x$). | | [`YGate`](qiskit.circuit.library.YGate "qiskit.circuit.library.YGate")(\*args\[, \_force\_mutable]) | The single-qubit Pauli-Y gate ($\sigma_y$). | | [`ZGate`](qiskit.circuit.library.ZGate "qiskit.circuit.library.ZGate")(\*args\[, \_force\_mutable]) | The single-qubit Pauli-Z gate ($\sigma_z$). | | [`GlobalPhaseGate`](qiskit.circuit.library.GlobalPhaseGate "qiskit.circuit.library.GlobalPhaseGate")(phase\[, label, duration, unit]) | The global phase gate ($e^{i\theta}$). | ## Standard Directives Directives are operations to the quantum stack that are meant to be interpreted by the backend or the transpiler. In general, the transpiler or backend might optionally ignore them if there is no implementation for them. | | | | --------------------------------------------------------------------------------------------------- | -------------------- | | [`Barrier`](qiskit.circuit.library.Barrier "qiskit.circuit.library.Barrier")(num\_qubits\[, label]) | Barrier instruction. | ## Standard Operations Operations are non-reversible changes in the quantum state of the circuit. | | | | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | | [`Measure`](qiskit.circuit.library.Measure "qiskit.circuit.library.Measure")(\*args\[, \_force\_mutable]) | Quantum measurement in the computational basis. | | [`Reset`](qiskit.circuit.library.Reset "qiskit.circuit.library.Reset")(\*args\[, \_force\_mutable]) | Qubit reset. | ## Generalized Gates These “gates” (many are [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") subclasses) allow to set the amount of qubits involved at instantiation time. ```python from qiskit.circuit.library import Diagonal diagonal = Diagonal([1, 1]) print(diagonal.num_qubits) diagonal = Diagonal([1, 1, 1, 1]) print(diagonal.num_qubits) ``` ```python 1 2 ``` | | | | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | [`Diagonal`](qiskit.circuit.library.Diagonal "qiskit.circuit.library.Diagonal")(diag) | Diagonal circuit. | | [`DiagonalGate`](qiskit.circuit.library.DiagonalGate "qiskit.circuit.library.DiagonalGate")(diag) | Gate implementing a diagonal transformation. | | [`MCMT`](qiskit.circuit.library.MCMT "qiskit.circuit.library.MCMT")(gate, num\_ctrl\_qubits, num\_target\_qubits) | The multi-controlled multi-target gate, for an arbitrary singly controlled target gate. | | [`MCMTVChain`](qiskit.circuit.library.MCMTVChain "qiskit.circuit.library.MCMTVChain")(gate, num\_ctrl\_qubits, ...) | The MCMT implementation using the CCX V-chain. | | [`Permutation`](qiskit.circuit.library.Permutation "qiskit.circuit.library.Permutation")(num\_qubits\[, pattern, seed]) | An n\_qubit circuit that permutes qubits. | | [`PermutationGate`](qiskit.circuit.library.PermutationGate "qiskit.circuit.library.PermutationGate")(pattern) | A gate that permutes qubits. | | [`GMS`](qiskit.circuit.library.GMS "qiskit.circuit.library.GMS")(num\_qubits, theta) | Global Mølmer–Sørensen gate. | | [`GR`](qiskit.circuit.library.GR "qiskit.circuit.library.GR")(num\_qubits, theta, phi) | Global R gate. | | [`GRX`](qiskit.circuit.library.GRX "qiskit.circuit.library.GRX")(num\_qubits, theta) | Global RX gate. | | [`GRY`](qiskit.circuit.library.GRY "qiskit.circuit.library.GRY")(num\_qubits, theta) | Global RY gate. | | [`GRZ`](qiskit.circuit.library.GRZ "qiskit.circuit.library.GRZ")(num\_qubits, phi) | Global RZ gate. | | [`MCPhaseGate`](qiskit.circuit.library.MCPhaseGate "qiskit.circuit.library.MCPhaseGate")(lam, num\_ctrl\_qubits\[, label, ...]) | Multi-controlled-Phase gate. | | [`MCXGate`](qiskit.circuit.library.MCXGate "qiskit.circuit.library.MCXGate")(\[num\_ctrl\_qubits, label, ...]) | The general, multi-controlled X gate. | | [`MCXGrayCode`](qiskit.circuit.library.MCXGrayCode "qiskit.circuit.library.MCXGrayCode")(\[num\_ctrl\_qubits, label, ...]) | Implement the multi-controlled X gate using the Gray code. | | [`MCXRecursive`](qiskit.circuit.library.MCXRecursive "qiskit.circuit.library.MCXRecursive")(\[num\_ctrl\_qubits, label, ...]) | Implement the multi-controlled X gate using recursion. | | [`MCXVChain`](qiskit.circuit.library.MCXVChain "qiskit.circuit.library.MCXVChain")(\[num\_ctrl\_qubits, dirty\_ancillas, ...]) | Implement the multi-controlled X gate using a V-chain of CX gates. | | [`RVGate`](qiskit.circuit.library.RVGate "qiskit.circuit.library.RVGate")(v\_x, v\_y, v\_z\[, basis]) | Rotation around arbitrary rotation axis $\vec{v}$ where $\|\vec{v}\|_2$ is angle of rotation in radians. | | [`PauliGate`](qiskit.circuit.library.PauliGate "qiskit.circuit.library.PauliGate")(label) | A multi-qubit Pauli gate. | | [`LinearFunction`](qiskit.circuit.library.LinearFunction "qiskit.circuit.library.LinearFunction")(linear\[, validate\_input]) | A linear reversible circuit on n qubits. | | [`Isometry`](qiskit.circuit.library.Isometry "qiskit.circuit.library.Isometry")(isometry, num\_ancillas\_zero, ...\[, ...]) | Decomposition of arbitrary isometries from $m$ to $n$ qubits. | | [`UnitaryGate`](qiskit.circuit.library.UnitaryGate "qiskit.circuit.library.UnitaryGate")(data\[, label, check\_input]) | Class quantum gates specified by a unitary matrix. | | [`UCGate`](qiskit.circuit.library.UCGate "qiskit.circuit.library.UCGate")(gate\_list\[, up\_to\_diagonal]) | Uniformly controlled gate (also called multiplexed gate). | | [`UCPauliRotGate`](qiskit.circuit.library.UCPauliRotGate "qiskit.circuit.library.UCPauliRotGate")(angle\_list, rot\_axis) | Uniformly controlled Pauli rotations. | | [`UCRXGate`](qiskit.circuit.library.UCRXGate "qiskit.circuit.library.UCRXGate")(angle\_list) | Uniformly controlled Pauli-X rotations. | | [`UCRYGate`](qiskit.circuit.library.UCRYGate "qiskit.circuit.library.UCRYGate")(angle\_list) | Uniformly controlled Pauli-Y rotations. | | [`UCRZGate`](qiskit.circuit.library.UCRZGate "qiskit.circuit.library.UCRZGate")(angle\_list) | Uniformly controlled Pauli-Z rotations. | ## Boolean Logic Circuits These are [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") subclasses that implement boolean logic operations, such as the logical or of a set of qubit states. | | | | ------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------- | | [`AND`](qiskit.circuit.library.AND "qiskit.circuit.library.AND")(num\_variable\_qubits\[, flags, mcx\_mode]) | A circuit implementing the logical AND operation on a number of qubits. | | [`OR`](qiskit.circuit.library.OR "qiskit.circuit.library.OR")(num\_variable\_qubits\[, flags, mcx\_mode]) | A circuit implementing the logical OR operation on a number of qubits. | | [`XOR`](qiskit.circuit.library.XOR "qiskit.circuit.library.XOR")(num\_qubits\[, amount, seed]) | An n\_qubit circuit for bitwise xor-ing the input with some integer `amount`. | | [`InnerProduct`](qiskit.circuit.library.InnerProduct "qiskit.circuit.library.InnerProduct")(num\_qubits) | A 2n-qubit Boolean function that computes the inner product of two n-qubit vectors over $F_2$. | ## Basis Change Circuits These circuits allow basis transformations of the qubit states. For example, in the case of the Quantum Fourier Transform (QFT), it transforms between the computational basis and the Fourier basis. | | | | ------------------------------------------------------------------------------------------------------------ | ---------------------------------- | | [`QFT`](qiskit.circuit.library.QFT "qiskit.circuit.library.QFT")(\[num\_qubits, approximation\_degree, ...]) | Quantum Fourier Transform Circuit. | ## Arithmetic Circuits These [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")s perform classical arithmetic, such as addition or multiplication. ### Amplitude Functions | | | | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | [`LinearAmplitudeFunction`](qiskit.circuit.library.LinearAmplitudeFunction "qiskit.circuit.library.LinearAmplitudeFunction")(num\_state\_qubits, ...) | A circuit implementing a (piecewise) linear function on qubit amplitudes. | ### Functional Pauli Rotations | | | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------- | | [`FunctionalPauliRotations`](qiskit.circuit.library.FunctionalPauliRotations "qiskit.circuit.library.FunctionalPauliRotations")(\[num\_state\_qubits, ...]) | Base class for functional Pauli rotations. | | [`LinearPauliRotations`](qiskit.circuit.library.LinearPauliRotations "qiskit.circuit.library.LinearPauliRotations")(\[num\_state\_qubits, ...]) | Linearly-controlled X, Y or Z rotation. | | [`PolynomialPauliRotations`](qiskit.circuit.library.PolynomialPauliRotations "qiskit.circuit.library.PolynomialPauliRotations")(\[num\_state\_qubits, ...]) | A circuit implementing polynomial Pauli rotations. | | [`PiecewiseLinearPauliRotations`](qiskit.circuit.library.PiecewiseLinearPauliRotations "qiskit.circuit.library.PiecewiseLinearPauliRotations")(\[...]) | Piecewise-linearly-controlled Pauli rotations. | | [`PiecewisePolynomialPauliRotations`](qiskit.circuit.library.PiecewisePolynomialPauliRotations "qiskit.circuit.library.PiecewisePolynomialPauliRotations")(\[...]) | Piecewise-polynomially-controlled Pauli rotations. | | [`PiecewiseChebyshev`](qiskit.circuit.library.PiecewiseChebyshev "qiskit.circuit.library.PiecewiseChebyshev")(f\_x\[, degree, ...]) | Piecewise Chebyshev approximation to an input function. | ### Adders | | | | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | [`DraperQFTAdder`](qiskit.circuit.library.DraperQFTAdder "qiskit.circuit.library.DraperQFTAdder")(num\_state\_qubits\[, kind, name]) | A circuit that uses QFT to perform in-place addition on two qubit registers. | | [`CDKMRippleCarryAdder`](qiskit.circuit.library.CDKMRippleCarryAdder "qiskit.circuit.library.CDKMRippleCarryAdder")(num\_state\_qubits\[, ...]) | A ripple-carry circuit to perform in-place addition on two qubit registers. | | [`VBERippleCarryAdder`](qiskit.circuit.library.VBERippleCarryAdder "qiskit.circuit.library.VBERippleCarryAdder")(num\_state\_qubits\[, ...]) | The VBE ripple carry adder \[1]. | | [`WeightedAdder`](qiskit.circuit.library.WeightedAdder "qiskit.circuit.library.WeightedAdder")(\[num\_state\_qubits, weights, name]) | A circuit to compute the weighted sum of qubit registers. | ### Multipliers | | | | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | [`HRSCumulativeMultiplier`](qiskit.circuit.library.HRSCumulativeMultiplier "qiskit.circuit.library.HRSCumulativeMultiplier")(num\_state\_qubits\[, ...]) | A multiplication circuit to store product of two input registers out-of-place. | | [`RGQFTMultiplier`](qiskit.circuit.library.RGQFTMultiplier "qiskit.circuit.library.RGQFTMultiplier")(num\_state\_qubits\[, ...]) | A QFT multiplication circuit to store product of two input registers out-of-place. | ### Comparators | | | | --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | | [`IntegerComparator`](qiskit.circuit.library.IntegerComparator "qiskit.circuit.library.IntegerComparator")(\[num\_state\_qubits, value, ...]) | Integer Comparator. | ### Functions on binary variables | | | | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | [`QuadraticForm`](qiskit.circuit.library.QuadraticForm "qiskit.circuit.library.QuadraticForm")(\[num\_result\_qubits, ...]) | Implements a quadratic form on binary variables encoded in qubit registers. | ### Other arithmetic functions | | | | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | | [`ExactReciprocal`](qiskit.circuit.library.ExactReciprocal "qiskit.circuit.library.ExactReciprocal")(num\_state\_qubits, scaling\[, ...]) | Exact reciprocal | ## Particular Quantum Circuits | | | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | [`FourierChecking`](qiskit.circuit.library.FourierChecking "qiskit.circuit.library.FourierChecking")(f, g) | Fourier checking circuit. | | [`GraphState`](qiskit.circuit.library.GraphState "qiskit.circuit.library.GraphState")(adjacency\_matrix) | Circuit to prepare a graph state. | | [`HiddenLinearFunction`](qiskit.circuit.library.HiddenLinearFunction "qiskit.circuit.library.HiddenLinearFunction")(adjacency\_matrix) | Circuit to solve the hidden linear function problem. | | [`IQP`](qiskit.circuit.library.IQP "qiskit.circuit.library.IQP")(interactions) | Instantaneous quantum polynomial (IQP) circuit. | | [`QuantumVolume`](qiskit.circuit.library.QuantumVolume "qiskit.circuit.library.QuantumVolume")(num\_qubits\[, depth, seed, ...]) | A quantum volume model circuit. | | [`PhaseEstimation`](qiskit.circuit.library.PhaseEstimation "qiskit.circuit.library.PhaseEstimation")(num\_evaluation\_qubits, unitary) | Phase Estimation circuit. | | [`GroverOperator`](qiskit.circuit.library.GroverOperator "qiskit.circuit.library.GroverOperator")(oracle\[, state\_preparation, ...]) | The Grover operator. | | [`PhaseOracle`](qiskit.circuit.library.PhaseOracle "qiskit.circuit.library.PhaseOracle")(expression\[, synthesizer, var\_order]) | Phase Oracle. | | [`PauliEvolutionGate`](qiskit.circuit.library.PauliEvolutionGate "qiskit.circuit.library.PauliEvolutionGate")(operator\[, time, label, ...]) | Time-evolution of an operator consisting of Paulis. | | [`HamiltonianGate`](qiskit.circuit.library.HamiltonianGate "qiskit.circuit.library.HamiltonianGate")(data, time\[, label]) | Class for representing evolution by a Hamiltonian operator as a gate. | | [`UnitaryOverlap`](qiskit.circuit.library.UnitaryOverlap "qiskit.circuit.library.UnitaryOverlap")(unitary1, unitary2\[, ...]) | Circuit that returns the overlap between two unitaries $U_2^{\dag} U_1$. | ## N-local circuits These `BlueprintCircuit` subclasses are used as parameterized models (a.k.a. ansatzes or variational forms) in variational algorithms. They are heavily used in near-term algorithms in e.g. Chemistry, Physics or Optimization. | | | | ----------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | [`NLocal`](qiskit.circuit.library.NLocal "qiskit.circuit.library.NLocal")(\[num\_qubits, rotation\_blocks, ...]) | The n-local circuit class. | | [`TwoLocal`](qiskit.circuit.library.TwoLocal "qiskit.circuit.library.TwoLocal")(\[num\_qubits, rotation\_blocks, ...]) | The two-local circuit. | | [`PauliTwoDesign`](qiskit.circuit.library.PauliTwoDesign "qiskit.circuit.library.PauliTwoDesign")(\[num\_qubits, reps, seed, ...]) | The Pauli Two-Design ansatz. | | [`RealAmplitudes`](qiskit.circuit.library.RealAmplitudes "qiskit.circuit.library.RealAmplitudes")(\[num\_qubits, entanglement, ...]) | The real-amplitudes 2-local circuit. | | [`EfficientSU2`](qiskit.circuit.library.EfficientSU2 "qiskit.circuit.library.EfficientSU2")(\[num\_qubits, su2\_gates, ...]) | The hardware efficient SU(2) 2-local circuit. | | [`EvolvedOperatorAnsatz`](qiskit.circuit.library.EvolvedOperatorAnsatz "qiskit.circuit.library.EvolvedOperatorAnsatz")(\[operators, reps, ...]) | The evolved operator ansatz. | | [`ExcitationPreserving`](qiskit.circuit.library.ExcitationPreserving "qiskit.circuit.library.ExcitationPreserving")(\[num\_qubits, mode, ...]) | The heuristic excitation-preserving wave function ansatz. | | [`QAOAAnsatz`](qiskit.circuit.library.QAOAAnsatz "qiskit.circuit.library.QAOAAnsatz")(\[cost\_operator, reps, ...]) | A generalized QAOA quantum circuit with a support of custom initial states and mixers. | ## Data encoding circuits These `BlueprintCircuit` encode classical data in quantum states and are used as feature maps for classification. | | | | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | | [`PauliFeatureMap`](qiskit.circuit.library.PauliFeatureMap "qiskit.circuit.library.PauliFeatureMap")(\[feature\_dimension, reps, ...]) | The Pauli Expansion circuit. | | [`ZFeatureMap`](qiskit.circuit.library.ZFeatureMap "qiskit.circuit.library.ZFeatureMap")(feature\_dimension\[, reps, ...]) | The first order Pauli Z-evolution circuit. | | [`ZZFeatureMap`](qiskit.circuit.library.ZZFeatureMap "qiskit.circuit.library.ZZFeatureMap")(feature\_dimension\[, reps, ...]) | Second-order Pauli-Z evolution circuit. | | [`StatePreparation`](qiskit.circuit.library.StatePreparation "qiskit.circuit.library.StatePreparation")(params\[, num\_qubits, ...]) | Complex amplitude state preparation. | | [`Initialize`](qiskit.circuit.library.Initialize "qiskit.circuit.library.Initialize")(params\[, num\_qubits, normalize]) | Complex amplitude initialization. | ## Template circuits Templates are functions that return circuits that compute the identity. They are used at circuit optimization where matching part of the template allows the compiler to replace the match with the inverse of the remainder from the template. In this example, the identity constant in a template is checked: ```python from qiskit.circuit.library.templates import template_nct_4b_1 from qiskit.quantum_info import Operator import numpy as np template = template_nct_4b_1() identity = np.identity(2 ** len(template.qubits), dtype=complex) data = Operator(template).data np.allclose(data, identity) # True, template_nct_4b_1 is the identity ``` ### NCT (Not-CNOT-Toffoli) template circuits Template circuits for [`XGate`](qiskit.circuit.library.XGate "qiskit.circuit.library.XGate"), [`CXGate`](qiskit.circuit.library.CXGate "qiskit.circuit.library.CXGate"), and [`CCXGate`](qiskit.circuit.library.CCXGate "qiskit.circuit.library.CCXGate") (Toffoli) gates. **Reference:** Maslov, D. and Dueck, G. W. and Miller, D. M., Techniques for the synthesis of reversible Toffoli networks, 2007 [http://dx.doi.org/10.1145/1278349.1278355](http://dx.doi.org/10.1145/1278349.1278355) #### template\_nct\_2a\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_2a_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_2a_1.py#L24-L32" signature="qiskit.circuit.library.templates.nct.template_nct_2a_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_2a\_2 <Function id="qiskit.circuit.library.templates.nct.template_nct_2a_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_2a_2.py#L25-L33" signature="qiskit.circuit.library.templates.nct.template_nct_2a_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_2a\_3 <Function id="qiskit.circuit.library.templates.nct.template_nct_2a_3" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_2a_3.py#L27-L35" signature="qiskit.circuit.library.templates.nct.template_nct_2a_3()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_4a\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_4a_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_4a_1.py#L31-L41" signature="qiskit.circuit.library.templates.nct.template_nct_4a_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_4a\_2 <Function id="qiskit.circuit.library.templates.nct.template_nct_4a_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_4a_2.py#L29-L39" signature="qiskit.circuit.library.templates.nct.template_nct_4a_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_4a\_3 <Function id="qiskit.circuit.library.templates.nct.template_nct_4a_3" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_4a_3.py#L27-L37" signature="qiskit.circuit.library.templates.nct.template_nct_4a_3()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_4b\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_4b_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_4b_1.py#L29-L39" signature="qiskit.circuit.library.templates.nct.template_nct_4b_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_4b\_2 <Function id="qiskit.circuit.library.templates.nct.template_nct_4b_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_4b_2.py#L27-L37" signature="qiskit.circuit.library.templates.nct.template_nct_4b_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_5a\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_5a_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_5a_1.py#L27-L38" signature="qiskit.circuit.library.templates.nct.template_nct_5a_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_5a\_2 <Function id="qiskit.circuit.library.templates.nct.template_nct_5a_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_5a_2.py#L27-L38" signature="qiskit.circuit.library.templates.nct.template_nct_5a_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_5a\_3 <Function id="qiskit.circuit.library.templates.nct.template_nct_5a_3" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_5a_3.py#L27-L38" signature="qiskit.circuit.library.templates.nct.template_nct_5a_3()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_5a\_4 <Function id="qiskit.circuit.library.templates.nct.template_nct_5a_4" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_5a_4.py#L26-L37" signature="qiskit.circuit.library.templates.nct.template_nct_5a_4()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_6a\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_6a_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_6a_1.py#L26-L38" signature="qiskit.circuit.library.templates.nct.template_nct_6a_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_6a\_2 <Function id="qiskit.circuit.library.templates.nct.template_nct_6a_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_6a_2.py#L27-L39" signature="qiskit.circuit.library.templates.nct.template_nct_6a_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_6a\_3 <Function id="qiskit.circuit.library.templates.nct.template_nct_6a_3" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_6a_3.py#L27-L39" signature="qiskit.circuit.library.templates.nct.template_nct_6a_3()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_6a\_4 <Function id="qiskit.circuit.library.templates.nct.template_nct_6a_4" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_6a_4.py#L27-L39" signature="qiskit.circuit.library.templates.nct.template_nct_6a_4()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_6b\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_6b_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_6b_1.py#L27-L39" signature="qiskit.circuit.library.templates.nct.template_nct_6b_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_6b\_2 <Function id="qiskit.circuit.library.templates.nct.template_nct_6b_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_6b_2.py#L27-L39" signature="qiskit.circuit.library.templates.nct.template_nct_6b_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_6c\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_6c_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_6c_1.py#L27-L39" signature="qiskit.circuit.library.templates.nct.template_nct_6c_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_7a\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_7a_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_7a_1.py#L28-L41" signature="qiskit.circuit.library.templates.nct.template_nct_7a_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_7b\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_7b_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_7b_1.py#L28-L41" signature="qiskit.circuit.library.templates.nct.template_nct_7b_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_7c\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_7c_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_7c_1.py#L28-L41" signature="qiskit.circuit.library.templates.nct.template_nct_7c_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_7d\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_7d_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_7d_1.py#L28-L41" signature="qiskit.circuit.library.templates.nct.template_nct_7d_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_7e\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_7e_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_7e_1.py#L28-L41" signature="qiskit.circuit.library.templates.nct.template_nct_7e_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9a\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_9a_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9a_1.py#L28-L43" signature="qiskit.circuit.library.templates.nct.template_nct_9a_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_1.py#L26-L41" signature="qiskit.circuit.library.templates.nct.template_nct_9c_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_2 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_2.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9c_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_3 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_3" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_3.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9c_3()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_4 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_4" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_4.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9c_4()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_5 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_5" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_5.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9c_5()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_6 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_6" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_6.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9c_6()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_7 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_7" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_7.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9c_7()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_8 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_8" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_8.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9c_8()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_9 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_9" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_9.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9c_9()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_10 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_10" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_10.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9c_10()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_11 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_11" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_11.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9c_11()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9c\_12 <Function id="qiskit.circuit.library.templates.nct.template_nct_9c_12" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9c_12.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9c_12()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9d\_1 <Function id="qiskit.circuit.library.templates.nct.template_nct_9d_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9d_1.py#L26-L41" signature="qiskit.circuit.library.templates.nct.template_nct_9d_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9d\_2 <Function id="qiskit.circuit.library.templates.nct.template_nct_9d_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9d_2.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9d_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9d\_3 <Function id="qiskit.circuit.library.templates.nct.template_nct_9d_3" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9d_3.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9d_3()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9d\_4 <Function id="qiskit.circuit.library.templates.nct.template_nct_9d_4" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9d_4.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9d_4()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9d\_5 <Function id="qiskit.circuit.library.templates.nct.template_nct_9d_5" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9d_5.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9d_5()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9d\_6 <Function id="qiskit.circuit.library.templates.nct.template_nct_9d_6" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9d_6.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9d_6()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9d\_7 <Function id="qiskit.circuit.library.templates.nct.template_nct_9d_7" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9d_7.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9d_7()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9d\_8 <Function id="qiskit.circuit.library.templates.nct.template_nct_9d_8" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9d_8.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9d_8()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9d\_9 <Function id="qiskit.circuit.library.templates.nct.template_nct_9d_9" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9d_9.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9d_9()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### template\_nct\_9d\_10 <Function id="qiskit.circuit.library.templates.nct.template_nct_9d_10" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/nct/template_nct_9d_10.py#L27-L42" signature="qiskit.circuit.library.templates.nct.template_nct_9d_10()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> ### Clifford template circuits Template circuits over Clifford gates. #### clifford\_2\_1 <Function id="qiskit.circuit.library.clifford_2_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_2_1.py#L25-L33" signature="qiskit.circuit.library.clifford_2_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_2\_2 <Function id="qiskit.circuit.library.clifford_2_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_2_2.py#L26-L34" signature="qiskit.circuit.library.clifford_2_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_2\_3 <Function id="qiskit.circuit.library.clifford_2_3" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_2_3.py#L24-L32" signature="qiskit.circuit.library.clifford_2_3()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_2\_4 <Function id="qiskit.circuit.library.clifford_2_4" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_2_4.py#L25-L33" signature="qiskit.circuit.library.clifford_2_4()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_3\_1 <Function id="qiskit.circuit.library.clifford_3_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_3_1.py#L25-L34" signature="qiskit.circuit.library.clifford_3_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_4\_1 <Function id="qiskit.circuit.library.clifford_4_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_4_1.py#L27-L37" signature="qiskit.circuit.library.clifford_4_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_4\_2 <Function id="qiskit.circuit.library.clifford_4_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_4_2.py#L26-L36" signature="qiskit.circuit.library.clifford_4_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_4\_3 <Function id="qiskit.circuit.library.clifford_4_3" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_4_3.py#L27-L37" signature="qiskit.circuit.library.clifford_4_3()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_4\_4 <Function id="qiskit.circuit.library.clifford_4_4" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_4_4.py#L26-L36" signature="qiskit.circuit.library.clifford_4_4()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_5\_1 <Function id="qiskit.circuit.library.clifford_5_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_5_1.py#L28-L39" signature="qiskit.circuit.library.clifford_5_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_6\_1 <Function id="qiskit.circuit.library.clifford_6_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_6_1.py#L27-L39" signature="qiskit.circuit.library.clifford_6_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_6\_2 <Function id="qiskit.circuit.library.clifford_6_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_6_2.py#L27-L39" signature="qiskit.circuit.library.clifford_6_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_6\_3 <Function id="qiskit.circuit.library.clifford_6_3" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_6_3.py#L27-L39" signature="qiskit.circuit.library.clifford_6_3()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_6\_4 <Function id="qiskit.circuit.library.clifford_6_4" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_6_4.py#L25-L37" signature="qiskit.circuit.library.clifford_6_4()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_6\_5 <Function id="qiskit.circuit.library.clifford_6_5" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_6_5.py#L27-L39" signature="qiskit.circuit.library.clifford_6_5()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_8\_1 <Function id="qiskit.circuit.library.clifford_8_1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_8_1.py#L27-L41" signature="qiskit.circuit.library.clifford_8_1()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_8\_2 <Function id="qiskit.circuit.library.clifford_8_2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_8_2.py#L27-L41" signature="qiskit.circuit.library.clifford_8_2()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> #### clifford\_8\_3 <Function id="qiskit.circuit.library.clifford_8_3" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/clifford/clifford_8_3.py#L26-L40" signature="qiskit.circuit.library.clifford_8_3()"> **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") </Function> ### RZXGate template circuits Template circuits with [`RZXGate`](qiskit.circuit.library.RZXGate "qiskit.circuit.library.RZXGate"). #### rzx\_yz <Function id="qiskit.circuit.library.rzx_yz" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/rzx/rzx_yz.py#L30-L43" signature="qiskit.circuit.library.rzx_yz(theta=None)"> Template for CX - RYGate - CX. </Function> #### rzx\_xz <Function id="qiskit.circuit.library.rzx_xz" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/rzx/rzx_xz.py#L36-L53" signature="qiskit.circuit.library.rzx_xz(theta=None)"> Template for CX - RXGate - CX. </Function> #### rzx\_cy <Function id="qiskit.circuit.library.rzx_cy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/rzx/rzx_cy.py#L31-L46" signature="qiskit.circuit.library.rzx_cy(theta=None)"> Template for CX - RYGate - CX. </Function> #### rzx\_zz1 <Function id="qiskit.circuit.library.rzx_zz1" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/rzx/rzx_zz1.py#L40-L67" signature="qiskit.circuit.library.rzx_zz1(theta=None)"> Template for CX - RZGate - CX. </Function> #### rzx\_zz2 <Function id="qiskit.circuit.library.rzx_zz2" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/rzx/rzx_zz2.py#L36-L58" signature="qiskit.circuit.library.rzx_zz2(theta=None)"> Template for CX - RZGate - CX. </Function> #### rzx\_zz3 <Function id="qiskit.circuit.library.rzx_zz3" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/templates/rzx/rzx_zz3.py#L35-L57" signature="qiskit.circuit.library.rzx_zz3(theta=None)"> Template for CX - RZGate - CX. </Function>
repo/docs/api/qiskit/1.0\circuit_library.mdx
--- title: singleton description: API reference for qiskit.circuit.singleton in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.circuit.singleton --- <span id="module-qiskit.circuit.singleton" /> <span id="qiskit-circuit-singleton" /> <span id="singleton-instructions-qiskit-circuit-singleton" /> # Singleton instructions <span id="module-qiskit.circuit.singleton" /> `qiskit.circuit.singleton` The machinery in this module is for defining subclasses of [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") and [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate") that preferentially return a shared immutable singleton instance when instantiated. Taking the example of [`XGate`](qiskit.circuit.library.XGate "qiskit.circuit.library.XGate"), the final user-facing result is that: * There is a regular class called `XGate`, which derives from [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). * Doing something like `XGate(label="my_gate")` produces an object whose type is exactly `XGate`, and all the mutability works completely as expected; all the methods resolve to exactly those defined by [`XGate`](qiskit.circuit.library.XGate "qiskit.circuit.library.XGate"), [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"), or parents. * Doing `XGate()` produces a singleton object whose type is a synthetic `_SingletonXGate` class, which derives [`XGate`](qiskit.circuit.library.XGate "qiskit.circuit.library.XGate") but overrides [`__setattr__()`](https://docs.python.org/3/reference/datamodel.html#object.__setattr__ "(in Python v3.12)") to make itself immutable. The object itself has precisely the same instance attributes as `XGate()` would have if there was no singleton handling. This object will return itself under [`copy()`](https://docs.python.org/3/library/copy.html#copy.copy "(in Python v3.12)"), [`deepcopy()`](https://docs.python.org/3/library/copy.html#copy.deepcopy "(in Python v3.12)") and roundtrip through [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle "(in Python v3.12)"). The same can be true for, for example, [`Measure`](qiskit.circuit.library.Measure "qiskit.circuit.library.Measure"), except that it’s a subclass of [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") only, and not [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). <Admonition title="Note" type="note"> The classes in this module are for advanced use, because they are closely entwined with the heart of Qiskit’s data model for circuits. </Admonition> From a library-author perspective, the minimum that is needed to enhance a [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate") or [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") with this behaviour is to inherit from [`SingletonGate`](#qiskit.circuit.singleton.SingletonGate "qiskit.circuit.singleton.SingletonGate") ([`SingletonInstruction`](#qiskit.circuit.singleton.SingletonInstruction "qiskit.circuit.singleton.SingletonInstruction")) instead of [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate") ([`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction")), and for the `__init__` method to have defaults for all of its arguments (these will be the state of the singleton instance). For example: ```python class XGate(SingletonGate): def __init__(self, label=None): super().__init__("x", 1, [], label=label) assert XGate() is XGate() ``` ## Interface The public classes correspond to the standard classes [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") and [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"), respectively, and are subclasses of these. ### SingletonInstruction <Class id="qiskit.circuit.singleton.SingletonInstruction" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/singleton.py#L503-L522" signature="qiskit.circuit.singleton.SingletonInstruction(*args, _force_mutable=False, **kwargs)" modifiers="class"> A base class to use for [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") objects that by default are singleton instances. This class should be used for instruction classes that have fixed definitions and do not contain any unique state. The canonical example of something like this is [`Measure`](qiskit.circuit.library.Measure "qiskit.circuit.library.Measure") which has an immutable definition and any instance of [`Measure`](qiskit.circuit.library.Measure "qiskit.circuit.library.Measure") is the same. Using singleton instructions as a base class for these types of gate classes provides a large advantage in the memory footprint of multiple instructions. The exception to be aware of with this class though are the [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") attributes [`label`](qiskit.circuit.Instruction#label "qiskit.circuit.Instruction.label"), [`condition`](qiskit.circuit.Instruction#condition "qiskit.circuit.Instruction.condition"), [`duration`](qiskit.circuit.Instruction#duration "qiskit.circuit.Instruction.duration"), and [`unit`](qiskit.circuit.Instruction#unit "qiskit.circuit.Instruction.unit") which can be set differently for specific instances of gates. For [`SingletonInstruction`](#qiskit.circuit.singleton.SingletonInstruction "qiskit.circuit.singleton.SingletonInstruction") usage to be sound setting these attributes is not available and they can only be set at creation time, or on an object that has been specifically made mutable using [`to_mutable()`](qiskit.circuit.Instruction#to_mutable "qiskit.circuit.Instruction.to_mutable"). If any of these attributes are used during creation, then instead of using a single shared global instance of the same gate a new separate instance will be created. </Class> ### SingletonGate <Class id="qiskit.circuit.singleton.SingletonGate" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/singleton.py#L534-L541" signature="qiskit.circuit.singleton.SingletonGate(*args, _force_mutable=False, **kwargs)" modifiers="class"> A base class to use for [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate") objects that by default are singleton instances. This class is very similar to [`SingletonInstruction`](#qiskit.circuit.singleton.SingletonInstruction "qiskit.circuit.singleton.SingletonInstruction"), except implies unitary [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate") semantics as well. The same caveats around setting attributes in that class apply here as well. </Class> ### SingletonControlledGate <Class id="qiskit.circuit.singleton.SingletonControlledGate" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/singleton.py#L554-L566" signature="qiskit.circuit.singleton.SingletonControlledGate(*args, _force_mutable=False, **kwargs)" modifiers="class"> A base class to use for [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate") objects that by default are singleton instances This class is very similar to [`SingletonInstruction`](#qiskit.circuit.singleton.SingletonInstruction "qiskit.circuit.singleton.SingletonInstruction"), except implies unitary [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate") semantics as well. The same caveats around setting attributes in that class apply here as well. </Class> When inheriting from one of these classes, the produced class will have an eagerly created singleton instance that will be returned whenever the class is constructed with arguments that have been defined to be singletons. Typically this will be the defaults. These instances are immutable; attempts to modify their properties will raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.12)"). *All* subclasses of [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") have a [`mutable`](qiskit.circuit.Instruction#mutable "qiskit.circuit.Instruction.mutable") property. For most instructions this is `True`, while for the singleton instances it is `False`. One can use the [`to_mutable()`](qiskit.circuit.Instruction#to_mutable "qiskit.circuit.Instruction.to_mutable") method to get a version of the instruction that is owned and safe to mutate. The singleton instances are not exact instances of their base class; they are special subclasses that cannot construct new objects. This means that: ```python type(XGate()) is not XGate ``` You should not rely on [`type`](https://docs.python.org/3/library/functions.html#type "(in Python v3.12)") having an exact value; use [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance "(in Python v3.12)") instead for type checking. If you need to reliably retrieve the base class from an [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction"), see the [`Instruction.base_class`](qiskit.circuit.Instruction#base_class "qiskit.circuit.Instruction.base_class") attribute; singleton instances set this correctly. For most cases in using Qiskit, [`Instruction.name`](qiskit.circuit.Instruction#name "qiskit.circuit.Instruction.name") is a more suitable determiner of what an instruction “means” in a circuit. ### Deriving new singletons The simplest example of deriving a new singleton instruction is simply to inherit from the correct base and supply an [`__init__()`](https://docs.python.org/3/reference/datamodel.html#object.__init__ "(in Python v3.12)") method that has immutable defaults for any arguments. For example: ```python from qiskit.circuit.singleton import SingletonInstruction class MyInstruction(SingletonInstruction): def __init__(self, label=None): super().__init__("my_instruction", 1, 0, label=label) assert MyInstruction() is MyInstruction() assert MyInstruction(label="some label") is not MyInstruction() assert MyInstruction(label="some label").mutable ``` The singleton instance will use all the constructor’s defaults. You can also derive from an instruction that is itself a singleton. The singleton nature of the class will be inherited, though the singleton instances of the two classes will be different: ```python class MyOtherInstruction(MyInstruction): pass assert MyOtherInstruction() is MyOtherInstruction() assert MyOtherInstruction() is not MyInstruction() ``` If for some reason you want to derive from [`SingletonInstruction`](#qiskit.circuit.singleton.SingletonInstruction "qiskit.circuit.singleton.SingletonInstruction"), or one of the related or subclasses but *do not* want the default singleton instance to be created, such as if you are defining a new abstract base class, you can set the keyword argument `create_default_singleton=False` in the class definition: ```python class NotASingleton(SingletonInstruction, create_default_singleton=False): def __init__(self): return super().__init__("my_mutable", 1, 0, []) assert NotASingleton() is not NotASingleton() ``` If your constructor does not have defaults for all its arguments, you must set `create_default_singleton=False`. Subclasses of [`SingletonInstruction`](#qiskit.circuit.singleton.SingletonInstruction "qiskit.circuit.singleton.SingletonInstruction") and the other associated classes can control how their constructor’s arguments are interpreted, in order to help the singleton machinery return the singleton even in the case than an optional argument is explicitly set to its default. #### \_singleton\_lookup\_key <Function id="qiskit.circuit.singleton.SingletonInstruction._singleton_lookup_key" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/singleton.py#L411-L451" signature="SingletonInstruction._singleton_lookup_key(*_args, **_kwargs)" modifiers="static"> Given the arguments to the constructor, return a key tuple that identifies the singleton instance to retrieve, or `None` if the arguments imply that a mutable object must be created. For performance, as a special case, this method will not be called if the class constructor was given zero arguments (e.g. the construction `XGate()` will not call this method, but `XGate(label=None)` will), and the default singleton will immediately be returned. This static method can (and probably should) be overridden by subclasses. The derived signature should match the class’s `__init__`; this method should then examine the arguments to determine whether it requires mutability, or what the cache key (if any) should be. The function should return either `None` or valid `dict` key (i.e. hashable and implements equality). Returning `None` means that the created instance must be mutable. No further singleton-based processing will be done, and the class creation will proceed as if there was no singleton handling. Otherwise, the returned key can be anything hashable and no special meaning is ascribed to it. Whenever this method returns the same key, the same singleton instance will be returned. We suggest that you use a tuple of the values of all arguments that can be set while maintaining the singleton nature. Only keys that match the default arguments or arguments given to `additional_singletons` at class-creation time will actually return singletons; other values will return a standard mutable instance. <Admonition title="Note" type="note"> The singleton machinery will handle an unhashable return from this function gracefully by returning a mutable instance. Subclasses should ensure that their key is hashable in the happy path, but they do not need to manually verify that the user-supplied arguments are hashable. For example, it’s safe to implement this as: ```python @staticmethod def _singleton_lookup_key(*args, **kwargs): return None if kwargs else args ``` even though a user might give some unhashable type as one of the `args`. </Admonition> </Function> This is set by all Qiskit standard-library gates such that the `label` and similar keyword arguments are ignored in the key calculation if they are their defaults, or a mutable instance is returned if they are not. You can also specify other combinations of constructor arguments to produce singleton instances for, using the `additional_singletons` argument in the class definition. This takes an iterable of `(args, kwargs)` tuples, and will build singletons equivalent to `cls(*args, **kwargs)`. You do not need to handle the case of the default arguments with this. For example, given a class definition: ```python class MySingleton(SingletonGate, additional_singletons=[((2,), {"label": "two"})]): def __init__(self, n=1, label=None): super().__init__("my", n, [], label=label) @staticmethod def _singleton_lookup_key(n=1, label=None): return (n, label) ``` there will be two singleton instances instantiated. One corresponds to `n=1` and `label=None`, and the other to `n=2` and `label="two"`. Whenever `MySingleton` is constructed with arguments consistent with one of those two cases, the relevant singleton will be returned. For example: ```python assert MySingleton() is MySingleton(1, label=None) assert MySingleton(2, "two") is MySingleton(n=2, label="two") ``` The case of the class being instantiated with zero arguments is handled specially to allow an absolute fast-path for inner-loop performance (although the general machinery is not desperately slow anyway). ## Implementation <Admonition title="Note" type="note"> This section is primarily developer documentation for the code; none of the machinery described here is public, and it is not safe to inherit from any of it directly. </Admonition> There are several moving parts to tackle here. The behaviour of having `XGate()` return some singleton object that is an (inexact) instance of [`XGate`](qiskit.circuit.library.XGate "qiskit.circuit.library.XGate") but *without* calling `__init__` requires us to override [`type.__call__`](https://docs.python.org/3/library/functions.html#type "(in Python v3.12)"). This means that [`XGate`](qiskit.circuit.library.XGate "qiskit.circuit.library.XGate") must have a metaclass that defines `__call__` to return the singleton instance. Next, we need to ensure that there *is* a singleton instance for `XGate()` to return. This can be done dynamically on each call (i.e. check if the instance exists and create it if not), but since we also want that instance to be very special, it’s easier to hook in and create it during the definition of the `XGate` type object. This also has the advantage that we do not need to make the singleton object pickleable; we only need to specify where to retrieve it from during the unpickle, because the creation of the base type object will recreate the singleton. We want the singleton instance to: * be immutable; it should reject all attempts to mutate itself. * have exactly the same state as an `XGate()` would have had if there was no singleton handling. We do this in a three-step procedure: 1. Before creating any singletons, we separately define the overrides needed to make an [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") and a [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate") immutable. This is `_SingletonInstructionOverrides` and the other `_*Overrides` classes. 2. While we are creating the `XGate` type object, we dynamically *also* create a subclass of it that has the immutable overrides in its method-resolution order in the correct place. These override the standard methods / properties that are defined on the mutable gate (we do not attempt to override any cases where the type object we are creating has extra inplace methods). 3. We can’t instantiate this new subclass, because when it calls `XGate.__init__`, it will attempt to set some attributes, and these will be rejected by immutability. Instead, we first create a completely regular `XGate` instance, and then we dynamically change its type to the singleton class, freezing it. We could do this entirely within the metaclass machinery, but that would require `XGate` to be defined as something like: ```python class XGate(Gate, metaclass=_SingletonMeta, overrides=_SingletonGateOverrides): ... ``` which is super inconvenient (or we’d have to have `_SingletonMeta` do a bunch of fragile introspection). Instead, we use the [`abc.ABC`](https://docs.python.org/3/library/abc.html#abc.ABC "(in Python v3.12)")/[`abc.ABCMeta`](https://docs.python.org/3/library/abc.html#abc.ABCMeta "(in Python v3.12)") pattern of defining a concrete middle class ([`SingletonGate`](#qiskit.circuit.singleton.SingletonGate "qiskit.circuit.singleton.SingletonGate") in the [`XGate`](qiskit.circuit.library.XGate "qiskit.circuit.library.XGate") case) that sets the metaclass, selects the overrides to be applied, and has an [`__init_subclass__()`](https://docs.python.org/3/reference/datamodel.html#object.__init_subclass__ "(in Python v3.12)") that applies the singleton-subclass-creation steps above. The overrides are in separate classes so that *mutable* [`XGate`](qiskit.circuit.library.XGate "qiskit.circuit.library.XGate") instances do not have them in their own method-resolution orders; doing this is easier to implement, but requires all the setters and checkers to dance around at runtime trying to validate whether mutating the instance is allowed. Finally, to actually build all this machinery up, the base is `_SingletonMeta`, which is a metaclass compatible with any metaclass of [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction"). This defines the [`__call__()`](https://docs.python.org/3/reference/datamodel.html#object.__call__ "(in Python v3.12)") machinery that overrides [`type.__call__`](https://docs.python.org/3/library/functions.html#type "(in Python v3.12)") to return the singleton instances. The other component of it is its [`__new__()`](https://docs.python.org/3/reference/datamodel.html#object.__new__ "(in Python v3.12)"), which is called (non-trivially) during the creation of [`SingletonGate`](#qiskit.circuit.singleton.SingletonGate "qiskit.circuit.singleton.SingletonGate") and [`SingletonInstruction`](#qiskit.circuit.singleton.SingletonInstruction "qiskit.circuit.singleton.SingletonInstruction") with its `overrides` keyword argument set to define the `__init_subclass__` of those classes with the above properties. We use the metaclass to add this method dynamically, because the [`__init_subclass__()`](https://docs.python.org/3/reference/datamodel.html#object.__init_subclass__ "(in Python v3.12)") machinery wants to be abstract, closing over the `overrides` and the base class, but still able to call [`super`](https://docs.python.org/3/library/functions.html#super "(in Python v3.12)"). It’s more convenient to do this dynamically, closing over the desired class variable and using the two-argument form of [`super`](https://docs.python.org/3/library/functions.html#super "(in Python v3.12)"), since the zero-argument form does magic introspection based on where its containing function was defined. Handling multiple singletons requires storing the initialization arguments in some form, to allow the [`to_mutable()`](qiskit.circuit.Instruction#to_mutable "qiskit.circuit.Instruction.to_mutable") method and pickling to be defined. We do this as a lookup dictionary on the singleton *type object*. This is logically an instance attribute, but because we need to dynamically switch in the dynamic \_Singleton type onto an instance of the base type, that gets rather complex; either we have to require that the base already has an instance dictionary, or we risk breaking the `__slots__` layout during the switch. Since the singletons have lifetimes that last until garbage collection of their base class’s type object, we can fake out this instance dictionary using a type-object dictionary that maps instance pointers to the data we want to store. An alternative would be to build a new type object for each individual singleton that closes over (or stores) the initializer arguments, but type objects are quite heavy and the principle is largely same anyway.
repo/docs/api/qiskit/1.0\circuit_singleton.mdx
--- title: classicalfunction description: API reference for qiskit.circuit.classicalfunction in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.circuit.classicalfunction --- <span id="module-qiskit.circuit.classicalfunction" /> <span id="qiskit-circuit-classicalfunction" /> <span id="classicalfunction-compiler-qiskit-circuit-classicalfunction" /> # ClassicalFunction compiler <span id="module-qiskit.circuit.classicalfunction" /> `qiskit.circuit.classicalfunction` ## Overview The classical function compiler provides the necessary tools to map a classical potentially irreversible functions into quantum circuits. Below is a simple example of how to synthesize a simple boolean function defined using Python into a QuantumCircuit: > ```python > from qiskit.circuit.classicalfunction import classical_function > from qiskit.circuit.classicalfunction.types import Int1 > > @classical_function > def grover_oracle(a: Int1, b: Int1, c: Int1, d: Int1) -> Int1: > return (not a and b and not c and d) > > quantum_circuit = grover_oracle.synth(registerless=False) > quantum_circuit.draw('text') > > a: ──o── > │ > b: ──■── > │ > c: ──o── > │ > d: ──■── > ┌─┴─┐ > return: ┤ X ├ > └───┘ > ``` Following Qiskit’s little-endian bit ordering convention, the left-most bit (`a`) is the most significant bit and the right-most bit (`d`) is the least significant bit. ## Supplementary Information ### Tweedledum Tweedledum is a C++-17 header-only library that implements a large set of reversible (and quantum) synthesis, optimization, and mapping algorithms. The classical function compiler relies on it and its dependencies to both represent logic networks and synthesize them into quantum circuits. ### ClassicalFunction data types At the moment, the only type supported by the classical\_function compilers is `qiskit.circuit.classicalfunction.types.Int1`. The classical function function to parse *must* include type hints (just `Int1` for now). The resulting gate will be a gate in the size of the sum of all the parameters and the return. The type `Int1` means the classical function will only operate at bit level. ## ClassicalFunction compiler API <span id="classical-function" /> ### classical\_function Decorator for a classical function that returns a ClassicalFunction object. ### ClassicalFunction | | | | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | [`ClassicalFunction`](qiskit.circuit.classicalfunction.ClassicalFunction "qiskit.circuit.classicalfunction.ClassicalFunction")(source\[, name]) | Represent a classical function and its logic network. | | [`BooleanExpression`](qiskit.circuit.classicalfunction.BooleanExpression "qiskit.circuit.classicalfunction.BooleanExpression")(expression\[, name, var\_order]) | The Boolean Expression gate. | ### Exceptions | | | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | | [`ClassicalFunctionCompilerTypeError`](qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError "qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError")(\*message) | ClassicalFunction compiler type error. | | [`ClassicalFunctionParseError`](qiskit.circuit.classicalfunction.ClassicalFunctionParseError "qiskit.circuit.classicalfunction.ClassicalFunctionParseError")(\*message) | ClassicalFunction compiler parse error. | | [`ClassicalFunctionCompilerTypeError`](qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError "qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError")(\*message) | ClassicalFunction compiler type error. |
repo/docs/api/qiskit/1.0\classicalfunction.mdx
"---\r\ntitle: compiler\r\ndescription: API reference for qiskit.compiler\r\nin_page_toc_min_heading(...TRUNCATED)
repo/docs/api/qiskit/1.0\compiler.mdx
"---\r\ntitle: converters\r\ndescription: API reference for qiskit.converters\r\nin_page_toc_min_hea(...TRUNCATED)
repo/docs/api/qiskit/1.0\converters.mdx
"---\r\ntitle: dagcircuit\r\ndescription: API reference for qiskit.dagcircuit\r\nin_page_toc_min_hea(...TRUNCATED)
repo/docs/api/qiskit/1.0\dagcircuit.mdx
"---\r\ntitle: exceptions\r\ndescription: API reference for qiskit.exceptions\r\nin_page_toc_min_hea(...TRUNCATED)
repo/docs/api/qiskit/1.0\exceptions.mdx
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
-