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')
```

## 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')
```

```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')
```

```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')
```

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:

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')
```

**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')
```

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
|
---
title: compiler
description: API reference for qiskit.compiler
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.compiler
---
<span id="module-qiskit.compiler" />
<span id="qiskit-compiler" />
<span id="compilation-routines-qiskit-compiler" />
# Compilation Routines
<span id="module-qiskit.compiler" />
`qiskit.compiler`
## Circuit and Pulse Compilation Functions
### assemble
<Function id="qiskit.compiler.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/compiler/assembler.py#L42-L220" signature="qiskit.compiler.assemble(experiments, backend=None, qobj_id=None, qobj_header=None, shots=None, memory=False, seed_simulator=None, qubit_lo_freq=None, meas_lo_freq=None, qubit_lo_range=None, meas_lo_range=None, schedule_los=None, meas_level=MeasLevel.CLASSIFIED, meas_return=MeasReturnType.AVERAGE, meas_map=None, memory_slot_size=100, rep_time=None, rep_delay=None, parameter_binds=None, parametric_pulses=None, init_qubits=True, **run_config)">
Assemble a list of circuits or pulse schedules into a `Qobj`.
This function serializes the payloads, which could be either circuits or schedules, to create `Qobj` βexperimentsβ. It further annotates the experiment payload with header and configurations.
NOTE: Backend.options is not used within assemble. The required values (previously given by backend.set\_options) should be manually extracted from options and supplied directly when calling.
**Parameters**
* **experiments** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")*] |* [*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")*] |* [*ScheduleBlock*](qiskit.pulse.ScheduleBlock "qiskit.pulse.schedule.ScheduleBlock") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock "qiskit.pulse.schedule.ScheduleBlock")*]*) β Circuit(s) or pulse schedule(s) to execute
* **backend** ([*Backend*](qiskit.providers.Backend "qiskit.providers.backend.Backend") *| None*) β If set, some runtime options are automatically grabbed from `backend.configuration()` and `backend.defaults()`. If any other option is explicitly set (e.g., `rep_time`), it will override the backendβs. If any other options is set in the run\_config, it will also override the backendβs.
* **qobj\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β String identifier to annotate the `Qobj`
* **qobj\_header** ([*QobjHeader*](qiskit.qobj.QobjHeader "qiskit.qobj.common.QobjHeader") *|*[*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)") *| None*) β User input that will be inserted in `Qobj` header, and will also be copied to the corresponding Result header. Headers do not affect the run.
* **shots** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β Number of repetitions of each circuit, for sampling. Default: 1024 or `max_shots` from the backend configuration, whichever is smaller
* **memory** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)") *| None*) β If `True`, per-shot measurement bitstrings are returned as well (provided the backend supports it). For OpenPulse jobs, only measurement level 2 supports this option.
* **seed\_simulator** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β Random seed to control sampling, for when backend is a simulator
* **qubit\_lo\_freq** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*] | None*) β List of job level qubit drive LO frequencies in Hz. Overridden by `schedule_los` if specified. Must have length `n_qubits.`
* **meas\_lo\_freq** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*] | None*) β List of measurement LO frequencies in Hz. Overridden by `schedule_los` if specified. Must have length `n_qubits.`
* **qubit\_lo\_range** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*] | None*) β List of job level drive LO ranges each of form `[range_min, range_max]` in Hz. Used to validate `qubit_lo_freq`. Must have length `n_qubits.`
* **meas\_lo\_range** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*] | None*) β List of job level measurement LO ranges each of form `[range_min, range_max]` in Hz. Used to validate `meas_lo_freq`. Must have length `n_qubits.`
* **schedule\_los** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")*\[PulseChannel,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*] | LoConfig] |* [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")*\[PulseChannel,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*] | LoConfig | None*) β Experiment level (ie circuit or schedule) LO frequency configurations for qubit drive and measurement channels. These values override the job level values from `default_qubit_los` and `default_meas_los`. Frequencies are in Hz. Settable for OpenQASM 2 and pulse jobs.
* **meas\_level** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| MeasLevel*) β Set the appropriate level of the measurement output for pulse experiments.
* **meas\_return** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| MeasReturnType*) β
Level of measurement data for the backend to return.
**For `meas_level` 0 and 1:**
* `single` returns information from every shot.
* `avg` returns average measurement output (averaged over number of shots).
* **meas\_map** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*Qubit*](qiskit.circuit.Qubit "qiskit.circuit.quantumregister.Qubit")*]] | None*) β List of lists, containing qubits that must be measured together.
* **memory\_slot\_size** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Size of each memory slot if the output is Level 0.
* **rep\_time** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Time per program execution in seconds. Must be from the list provided by the backend (`backend.configuration().rep_times`). Defaults to the first entry.
* **rep\_delay** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Delay between programs in seconds. Only supported on certain backends (if `backend.configuration().dynamic_reprate_enabled=True`). If supported, `rep_delay` will be used instead of `rep_time` and must be from the range supplied by the backend (`backend.configuration().rep_delay_range`). Default is given by `backend.configuration().default_rep_delay`.
* **parameter\_binds** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")*\[*[*Parameter*](qiskit.circuit.Parameter "qiskit.circuit.parameter.Parameter")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*]] | None*) β List of Parameter bindings over which the set of experiments will be executed. Each list element (bind) should be of the form \{Parameter1: value1, Parameter2: value2, β¦}. All binds will be executed across all experiments; e.g., if parameter\_binds is a length-n list, and there are m experiments, a total of m x n experiments will be run (one for each experiment/bind pair).
* **parametric\_pulses** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*] | None*) β
A list of pulse shapes which are supported internally on the backend. Example:
```python
['gaussian', 'constant']
```
* **init\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Whether to reset the qubits to the ground state for each shot. Default: `True`.
* **\*\*run\_config** ([*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")) β Extra arguments used to configure the run (e.g., for Aer configurable backends). Refer to the backend documentation for details on these arguments.
**Returns**
A `Qobj` that can be run on a backend. Depending on the type of input, this will be either a `QasmQobj` or a `PulseQobj`.
**Raises**
[**QiskitError**](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") β if the input cannot be interpreted as either circuits or schedules
**Return type**
[*QasmQobj*](qiskit.qobj.QasmQobj "qiskit.qobj.qasm_qobj.QasmQobj") | [*PulseQobj*](qiskit.qobj.PulseQobj "qiskit.qobj.pulse_qobj.PulseQobj")
</Function>
### schedule
<Function id="qiskit.compiler.schedule" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/compiler/scheduler.py#L38-L107" signature="qiskit.compiler.schedule(circuits, backend=None, inst_map=None, meas_map=None, dt=None, method=None)">
Schedule a circuit to a pulse `Schedule`, using the backend, according to any specified methods. Supported methods are documented in `qiskit.scheduler.schedule_circuit`.
**Parameters**
* **circuits** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")*]*) β The quantum circuit or circuits to translate
* **backend** ([*Backend*](qiskit.providers.Backend "qiskit.providers.backend.Backend") *| None*) β A backend instance, which contains hardware-specific data required for scheduling
* **inst\_map** ([*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap "qiskit.pulse.instruction_schedule_map.InstructionScheduleMap") *| None*) β Mapping of circuit operations to pulse schedules. If `None`, defaults to the `backend`βs `instruction_schedule_map`
* **meas\_map** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]] | None*) β List of sets of qubits that must be measured together. If `None`, defaults to the `backend`βs `meas_map`
* **dt** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *| None*) β The output sample rate of backend control electronics. For scheduled circuits which contain time information, dt is required. If not provided, it will be obtained from the backend configuration
* **method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*] | None*) β Optionally specify a particular scheduling method
**Returns**
A pulse `Schedule` that implements the input circuit
**Raises**
[**QiskitError**](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") β If `inst_map` and `meas_map` are not passed and `backend` is not passed
**Return type**
[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule") | [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")\[[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")]
</Function>
### transpile
<Function id="qiskit.compiler.transpile" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/compiler/transpiler.py#L43-L434" signature="qiskit.compiler.transpile(circuits, backend=None, basis_gates=None, inst_map=None, coupling_map=None, backend_properties=None, initial_layout=None, layout_method=None, routing_method=None, translation_method=None, scheduling_method=None, instruction_durations=None, dt=None, approximation_degree=1.0, timing_constraints=None, seed_transpiler=None, optimization_level=None, callback=None, output_name=None, unitary_synthesis_method='default', unitary_synthesis_plugin_config=None, target=None, hls_config=None, init_method=None, optimization_method=None, ignore_backend_supplied_default_methods=False, num_processes=None)">
Transpile one or more circuits, according to some desired transpilation targets.
Transpilation is potentially done in parallel using multiprocessing when `circuits` is a list with > 1 [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") object depending on the local environment and configuration.
**Parameters**
* **circuits** (*\_CircuitT*) β Circuit(s) to transpile
* **backend** ([*Backend*](qiskit.providers.Backend "qiskit.providers.backend.Backend") *| None*) β If set, the transpiler will compile the input circuit to this target device. If any other option is explicitly set (e.g., `coupling_map`), it will override the backendβs.
* **basis\_gates** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*] | None*) β List of basis gate names to unroll to (e.g: `['u1', 'u2', 'u3', 'cx']`). If `None`, do not unroll.
* **inst\_map** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap "qiskit.pulse.instruction_schedule_map.InstructionScheduleMap")*] | None*) β Mapping of unrolled gates to pulse schedules. If this is not provided, transpiler tries to get from the backend. If any user defined calibration is found in the map and this is used in a circuit, transpiler attaches the custom gate definition to the circuit. This enables one to flexibly override the low-level instruction implementation. This feature is available iff the backend supports the pulse gate experiment.
* **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap "qiskit.transpiler.coupling.CouplingMap") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]] | None*) β
Directed coupling map (perhaps custom) to target in mapping. If the coupling map is symmetric, both directions need to be specified.
Multiple formats are supported:
1. `CouplingMap` instance
2. List, must be given as an adjacency matrix, where each entry specifies all directed two-qubit interactions supported by backend, e.g: `[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]`
* **backend\_properties** ([*BackendProperties*](qiskit.providers.models.BackendProperties "qiskit.providers.models.backendproperties.BackendProperties") *| None*) β properties returned by a backend, including information on gate errors, readout errors, qubit coherence times, etc. Find a backend that provides this information with: `backend.properties()`
* **initial\_layout** ([*Layout*](qiskit.transpiler.Layout "qiskit.transpiler.layout.Layout") *|*[*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)") *| None*) β
Initial position of virtual qubits on physical qubits. If this layout makes the circuit compatible with the coupling\_map constraints, it will be used. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. Multiple formats are supported:
1. `Layout` instance
2. Dict \* virtual to physical:
```python
{qr[0]: 0,
qr[1]: 3,
qr[2]: 5}
```
* physical to virtual:
```python
{0: qr[0],
3: qr[1],
5: qr[2]}
```
3. List
* virtual to physical:
```python
[0, 3, 5] # virtual qubits are ordered (in addition to named)
```
* physical to virtual:
```python
[qr[0], None, None, qr[1], None, qr[2]]
```
* **layout\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name of layout selection pass (βtrivialβ, βdenseβ, βsabreβ). This can also be the external plugin name to use for the `layout` stage. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins "qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins") with `"layout"` for the `stage_name` argument.
* **routing\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name of routing pass (βbasicβ, βlookaheadβ, βstochasticβ, βsabreβ, βnoneβ). Note This can also be the external plugin name to use for the `routing` stage. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins "qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins") with `"routing"` for the `stage_name` argument.
* **translation\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name of translation pass (βunrollerβ, βtranslatorβ, βsynthesisβ) This can also be the external plugin name to use for the `translation` stage. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins "qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins") with `"translation"` for the `stage_name` argument.
* **scheduling\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name of scheduling pass. \* `'as_soon_as_possible'`: Schedule instructions greedily, as early as possible on a qubit resource. (alias: `'asap'`) \* `'as_late_as_possible'`: Schedule instructions late, i.e. keeping qubits in the ground state when possible. (alias: `'alap'`) If `None`, no scheduling will be done. This can also be the external plugin name to use for the `scheduling` stage. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins "qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins") with `"scheduling"` for the `stage_name` argument.
* **instruction\_durations** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*] | None,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*] | None,* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]] |* [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*] | None,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*] | None]] |* [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*] | None,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*,* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]] |* [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*] | None,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*]] |* [*InstructionDurations*](qiskit.transpiler.InstructionDurations "qiskit.transpiler.instruction_durations.InstructionDurations") *| None*) β Durations of instructions. Applicable only if scheduling\_method is specified. The gate lengths defined in `backend.properties` are used as default. They are overwritten if this `instruction_durations` is specified. The format of `instruction_durations` must be as follows. The instruction\_durations must be given as a list of tuples \[(instruction\_name, qubits, duration, unit), β¦]. | \[(βcxβ, \[0, 1], 12.3, βnsβ), (βu3β, \[0], 4.56, βnsβ)] | \[(βcxβ, \[0, 1], 1000), (βu3β, \[0], 300)] If unit is omitted, the default is βdtβ, which is a sample time depending on backend. If the time unit is βdtβ, the duration must be an integer.
* **dt** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *| None*) β Backend sample time (resolution) in seconds. If `None` (default), `backend.configuration().dt` is used.
* **approximation\_degree** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β heuristic dial used for circuit approximation (1.0=no approximation, 0.0=maximal approximation)
* **timing\_constraints** ([*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*,* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*] | None*) β
An optional control hardware restriction on instruction time resolution. A quantum computer backend may report a set of restrictions, namely:
* granularity: An integer value representing minimum pulse gate resolution in units of `dt`. A user-defined pulse gate should have duration of a multiple of this granularity value.
* min\_length: An integer value representing minimum pulse gate length in units of `dt`. A user-defined pulse gate should be longer than this length.
* pulse\_alignment: An integer value representing a time resolution of gate instruction starting time. Gate instruction should start at time which is a multiple of the alignment value.
* acquire\_alignment: An integer value representing a time resolution of measure instruction starting time. Measure instruction should start at time which is a multiple of the alignment value.
This information will be provided by the backend configuration. If the backend doesnβt have any restriction on the instruction time allocation, then `timing_constraints` is None and no adjustment will be performed.
* **seed\_transpiler** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β Sets random seed for the stochastic parts of the transpiler
* **optimization\_level** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β
How much optimization to perform on the circuits. Higher levels generate more optimized circuits, at the expense of longer transpilation time.
* 0: no optimization
* 1: light optimization
* 2: heavy optimization
* 3: even heavier optimization
If `None`, level 1 will be chosen as default.
* **callback** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.12)")*\[\[BasePass,* [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.dagcircuit.DAGCircuit")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*,* [*PropertySet*](qiskit.passmanager.PropertySet "qiskit.passmanager.compilation_status.PropertySet")*,* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*],* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.12)")*] | None*) β
A callback function that will be called after each pass execution. The function will be called with 5 keyword arguments, | `pass_`: the pass being run. | `dag`: the dag output of the pass. | `time`: the time to execute the pass. | `property_set`: the property set. | `count`: the index for the pass execution. The exact arguments passed expose the internals of the pass manager, and are subject to change as the pass manager internals change. If you intend to reuse a callback function over multiple releases, be sure to check that the arguments being passed are the same. To use the callback feature, define a function that will take in kwargs dict and access the variables. For example:
```python
def callback_func(**kwargs):
pass_ = kwargs['pass_']
dag = kwargs['dag']
time = kwargs['time']
property_set = kwargs['property_set']
count = kwargs['count']
...
transpile(circ, callback=callback_func)
```
* **output\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*] | None*) β A list with strings to identify the output circuits. The length of the list should be exactly the length of the `circuits` parameter.
* **unitary\_synthesis\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The name of the unitary synthesis method to use. By default `'default'` is used. You can see a list of installed plugins with [`unitary_synthesis_plugin_names()`](qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names "qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names").
* **unitary\_synthesis\_plugin\_config** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)") *| None*) β An optional configuration dictionary that will be passed directly to the unitary synthesis plugin. By default this setting will have no effect as the default unitary synthesis method does not take custom configuration. This should only be necessary when a unitary synthesis plugin is specified with the `unitary_synthesis_method` argument. As this is custom for each unitary synthesis plugin refer to the plugin documentation for how to use this option.
* **target** ([*Target*](qiskit.transpiler.Target "qiskit.transpiler.target.Target") *| None*) β A backend transpiler target. Normally this is specified as part of the `backend` argument, but if you have manually constructed a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") object you can specify it manually here. This will override the target from `backend`.
* **hls\_config** ([*HLSConfig*](qiskit.transpiler.passes.HLSConfig "qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig") *| None*) β An optional configuration class `HLSConfig` that will be passed directly to `HighLevelSynthesis` transformation pass. This configuration class allows to specify for various high-level objects the lists of synthesis algorithms and their parameters.
* **init\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β The plugin name to use for the `init` stage. By default an external plugin is not used. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins "qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins") with `"init"` for the stage name argument.
* **optimization\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β The plugin name to use for the `optimization` stage. By default an external plugin is not used. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins "qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins") with `"optimization"` for the `stage_name` argument.
* **ignore\_backend\_supplied\_default\_methods** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β If set to `True` any default methods specified by a backend will be ignored. Some backends specify alternative default methods to support custom compilation target-specific passes/plugins which support backend-specific compilation techniques. If youβd prefer that these defaults were not used this option is used to disable those backend-specific defaults.
* **num\_processes** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β The maximum number of parallel processes to launch for this call to transpile if parallel execution is enabled. This argument overrides `num_processes` in the user configuration file, and the `QISKIT_NUM_PROCS` environment variable. If set to `None` the system default or local user configuration will be used.
**Returns**
The transpiled circuit(s).
**Raises**
[**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError "qiskit.transpiler.TranspilerError") β in case of bad inputs to transpiler (like conflicting parameters) or errors in passes
**Return type**
*\_CircuitT*
</Function>
### sequence
<Function id="qiskit.compiler.sequence" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/compiler/sequencer.py#L26-L69" signature="qiskit.compiler.sequence(scheduled_circuits, backend=None, inst_map=None, meas_map=None, dt=None)">
Schedule a scheduled circuit to a pulse `Schedule`, using the backend.
**Parameters**
* **scheduled\_circuits** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")*]*) β Scheduled circuit(s) to be translated
* **backend** ([*Backend*](qiskit.providers.Backend "qiskit.providers.backend.Backend") *| None*) β A backend instance, which contains hardware-specific data required for scheduling
* **inst\_map** ([*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap "qiskit.pulse.instruction_schedule_map.InstructionScheduleMap") *| None*) β Mapping of circuit operations to pulse schedules. If `None`, defaults to the `backend`βs `instruction_schedule_map`
* **meas\_map** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]] | None*) β List of sets of qubits that must be measured together. If `None`, defaults to the `backend`βs `meas_map`
* **dt** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *| None*) β The output sample rate of backend control electronics. For scheduled circuits which contain time information, dt is required. If not provided, it will be obtained from the backend configuration
**Returns**
A pulse `Schedule` that implements the input circuit
**Raises**
[**QiskitError**](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") β If `inst_map` and `meas_map` are not passed and `backend` is not passed
**Return type**
[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule") | [*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")\[[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")]
</Function>
|
repo/docs/api/qiskit/1.0\compiler.mdx
|
---
title: converters
description: API reference for qiskit.converters
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.converters
---
<span id="module-qiskit.converters" />
<span id="qiskit-converters" />
<span id="circuit-converters-qiskit-converters" />
# Circuit Converters
<span id="module-qiskit.converters" />
`qiskit.converters`
### circuit\_to\_dag
<Function id="qiskit.converters.circuit_to_dag" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/converters/circuit_to_dag.py#L19-L96" signature="qiskit.converters.circuit_to_dag(circuit, copy_operations=True, *, qubit_order=None, clbit_order=None)">
Build a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit") object from a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit").
**Parameters**
* **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")) β the input circuit.
* **copy\_operations** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Deep copy the operation objects in the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") for the output [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit"). This should only be set to `False` if the input [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") will not be used anymore as the operations in the output [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit") will be shared instances and modifications to operations in the [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit") will be reflected in the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") (and vice versa).
* **qubit\_order** (*Iterable\[*[*Qubit*](qiskit.circuit.Qubit "qiskit.circuit.Qubit")*] or None*) β the order that the qubits should be indexed in the output DAG. Defaults to the same order as in the circuit.
* **clbit\_order** (*Iterable\[*[*Clbit*](qiskit.circuit.Clbit "qiskit.circuit.Clbit")*] or None*) β the order that the clbits should be indexed in the output DAG. Defaults to the same order as in the circuit.
**Returns**
the DAG representing the input circuit.
**Return type**
[DAGCircuit](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit")
**Raises**
[**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.12)") β if the `qubit_order` or `clbit_order` parameters do not match the bits in the circuit.
**Example**
```python
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
```
</Function>
### dag\_to\_circuit
<Function id="qiskit.converters.dag_to_circuit" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/converters/dag_to_circuit.py#L19-L77" signature="qiskit.converters.dag_to_circuit(dag, copy_operations=True)">
Build a `QuantumCircuit` object from a `DAGCircuit`.
**Parameters**
* **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit")) β the input dag.
* **copy\_operations** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Deep copy the operation objects in the [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit") for the output [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"). This should only be set to `False` if the input [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit") will not be used anymore as the operations in the output [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") will be shared instances and modifications to operations in the [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit") will be reflected in the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") (and vice versa).
**Returns**
the circuit representing the input dag.
**Return type**
[QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")
**Example**
```python
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate
from qiskit.converters import dag_to_circuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
circuit = dag_to_circuit(dag)
circuit.draw('mpl')
```

</Function>
### circuit\_to\_instruction
<Function id="qiskit.converters.circuit_to_instruction" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/converters/circuit_to_instruction.py#L21-L145" signature="qiskit.converters.circuit_to_instruction(circuit, parameter_map=None, equivalence_library=None, label=None)">
Build an [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") object from a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit").
The instruction is anonymous (not tied to a named quantum register), and so can be inserted into another circuit. The instruction will have the same string name as the circuit.
**Parameters**
* **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")) β the input circuit.
* **parameter\_map** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)")) β For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the instruction. If None, existing circuit parameters will also parameterize the instruction.
* **equivalence\_library** ([*EquivalenceLibrary*](qiskit.circuit.EquivalenceLibrary "qiskit.circuit.EquivalenceLibrary")) β Optional equivalence library where the converted instruction will be registered.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Optional instruction label.
**Raises**
[**QiskitError**](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") β if parameter\_map is not compatible with circuit
**Returns**
an instruction equivalent to the action of the input circuit. Upon decomposition, this instruction will yield the components comprising the original circuit.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Example**
```python
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.converters import circuit_to_instruction
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
circuit_to_instruction(circ)
```
</Function>
### circuit\_to\_gate
<Function id="qiskit.converters.circuit_to_gate" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/converters/circuit_to_gate.py#L30-L109" signature="qiskit.converters.circuit_to_gate(circuit, parameter_map=None, equivalence_library=None, label=None)">
Build a [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate") object from a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit").
The gate is anonymous (not tied to a named quantum register), and so can be inserted into another circuit. The gate will have the same string name as the circuit.
**Parameters**
* **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")) β the input circuit.
* **parameter\_map** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)")) β For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the gate. If None, existing circuit parameters will also parameterize the Gate.
* **equivalence\_library** ([*EquivalenceLibrary*](qiskit.circuit.EquivalenceLibrary "qiskit.circuit.EquivalenceLibrary")) β Optional equivalence library where the converted gate will be registered.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Optional gate label.
**Raises**
[**QiskitError**](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") β if circuit is non-unitary or if parameter\_map is not compatible with circuit
**Returns**
a Gate equivalent to the action of the input circuit. Upon decomposition, this gate will yield the components comprising the original circuit.
**Return type**
[Gate](qiskit.circuit.Gate "qiskit.circuit.Gate")
</Function>
### dagdependency\_to\_circuit
<Function id="qiskit.converters.dagdependency_to_circuit" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/converters/dagdependency_to_circuit.py#L17-L42" signature="qiskit.converters.dagdependency_to_circuit(dagdependency)">
Build a `QuantumCircuit` object from a `DAGDependency`.
**Parameters**
**dagdependency** ([*DAGDependency*](qiskit.dagcircuit.DAGDependency "qiskit.dagcircuit.DAGDependency")) β the input dag.
**Returns**
the circuit representing the input dag dependency.
**Return type**
[QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")
</Function>
### circuit\_to\_dagdependency
<Function id="qiskit.converters.circuit_to_dagdependency" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/converters/circuit_to_dagdependency.py#L18-L51" signature="qiskit.converters.circuit_to_dagdependency(circuit, create_preds_and_succs=True)">
Build a `DAGDependency` object from a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit").
**Parameters**
* **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")) β the input circuit.
* **create\_preds\_and\_succs** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β whether to construct lists of predecessors and successors for every node.
**Returns**
the DAG representing the input circuit as a dag dependency.
**Return type**
[DAGDependency](qiskit.dagcircuit.DAGDependency "qiskit.dagcircuit.DAGDependency")
</Function>
### dag\_to\_dagdependency
<Function id="qiskit.converters.dag_to_dagdependency" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/converters/dag_to_dagdependency.py#L17-L55" signature="qiskit.converters.dag_to_dagdependency(dag, create_preds_and_succs=True)">
Build a `DAGDependency` object from a `DAGCircuit`.
**Parameters**
* **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit")) β the input dag.
* **create\_preds\_and\_succs** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β whether to construct lists of predecessors and successors for every node.
**Returns**
the DAG representing the input circuit as a dag dependency.
**Return type**
[DAGDependency](qiskit.dagcircuit.DAGDependency "qiskit.dagcircuit.DAGDependency")
</Function>
### dagdependency\_to\_dag
<Function id="qiskit.converters.dagdependency_to_dag" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/converters/dagdependency_to_dag.py#L17-L49" signature="qiskit.converters.dagdependency_to_dag(dagdependency)">
Build a `DAGCircuit` object from a `DAGDependency`.
**Parameters**
**dependency** (*dag*) β the input dag.
**Returns**
the DAG representing the input circuit.
**Return type**
[DAGCircuit](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit")
</Function>
|
repo/docs/api/qiskit/1.0\converters.mdx
|
---
title: dagcircuit
description: API reference for qiskit.dagcircuit
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.dagcircuit
---
<span id="module-qiskit.dagcircuit" />
<span id="qiskit-dagcircuit" />
<span id="dag-circuits-qiskit-dagcircuit" />
# DAG Circuits
<span id="module-qiskit.dagcircuit" />
`qiskit.dagcircuit`
## Circuits as Directed Acyclic Graphs
| | |
| ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit "qiskit.dagcircuit.DAGCircuit")() | Quantum circuit as a directed acyclic graph. |
| [`DAGNode`](qiskit.dagcircuit.DAGNode "qiskit.dagcircuit.DAGNode")(\[nid]) | Parent class for DAGOpNode, DAGInNode, and DAGOutNode. |
| [`DAGOpNode`](qiskit.dagcircuit.DAGOpNode "qiskit.dagcircuit.DAGOpNode")(op\[,Β qargs,Β cargs,Β dag]) | Object to represent an Instruction at a node in the DAGCircuit. |
| [`DAGInNode`](qiskit.dagcircuit.DAGInNode "qiskit.dagcircuit.DAGInNode")(wire) | Object to represent an incoming wire node in the DAGCircuit. |
| [`DAGOutNode`](qiskit.dagcircuit.DAGOutNode "qiskit.dagcircuit.DAGOutNode")(wire) | Object to represent an outgoing wire node in the DAGCircuit. |
| [`DAGDepNode`](qiskit.dagcircuit.DAGDepNode "qiskit.dagcircuit.DAGDepNode")(\[type,Β op,Β name,Β qargs,Β cargs,Β ...]) | Object to represent the information at a node in the DAGDependency(). |
| [`DAGDependency`](qiskit.dagcircuit.DAGDependency "qiskit.dagcircuit.DAGDependency")() | Object to represent a quantum circuit as a Directed Acyclic Graph (DAG) via operation dependencies (i.e. |
## Exceptions
### DAGCircuitError
<Class id="qiskit.dagcircuit.DAGCircuitError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/dagcircuit/exceptions.py#L19-L29" signature="qiskit.dagcircuit.DAGCircuitError(*msg)" modifiers="exception">
Base class for errors raised by the DAGCircuit object.
Set the error message.
</Class>
### DAGDependencyError
<Class id="qiskit.dagcircuit.DAGDependencyError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/dagcircuit/exceptions.py#L32-L42" signature="qiskit.dagcircuit.DAGDependencyError(*msg)" modifiers="exception">
Base class for errors raised by the DAGDependency object.
Set the error message.
</Class>
|
repo/docs/api/qiskit/1.0\dagcircuit.mdx
|
---
title: exceptions
description: API reference for qiskit.exceptions
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.exceptions
---
<span id="module-qiskit.exceptions" />
<span id="qiskit-exceptions" />
<span id="top-level-exceptions-qiskit-exceptions" />
# Top-level exceptions
<span id="module-qiskit.exceptions" />
`qiskit.exceptions`
## Exceptions
All Qiskit-related exceptions raised by Qiskit are subclasses of the base:
### QiskitError
<Class id="qiskit.exceptions.QiskitError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/exceptions.py#L92-L102" signature="qiskit.exceptions.QiskitError(*message)" modifiers="exception">
Base class for errors raised by Qiskit.
Set the error message.
</Class>
<Admonition title="Note" type="note">
Errors that are just general programming errors, such as incorrect typing, may still raise standard Python errors such as `TypeError`. [`QiskitError`](#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") is generally for errors raised in usage that is particular to Qiskit.
</Admonition>
Many of the Qiskit subpackages define their own more granular error, to help in catching only the subset of errors you care about. For example, [`qiskit.circuit`](circuit#module-qiskit.circuit "qiskit.circuit") almost exclusively uses [`CircuitError`](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError"), while both [`QASM2ExportError`](qasm2#qiskit.qasm2.QASM2ExportError "qiskit.qasm2.QASM2ExportError") and [`QASM2ParseError`](qasm2#qiskit.qasm2.QASM2ParseError "qiskit.qasm2.QASM2ParseError") derive from [`QASM2Error`](qasm2#qiskit.qasm2.QASM2Error "qiskit.qasm2.QASM2Error") in [`qiskit.qasm2`](qasm2#module-qiskit.qasm2 "qiskit.qasm2"), which is in turn a type of [`QiskitError`](#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError").
Qiskit has several optional features that depend on other packages that are not required for a minimal install. You can read more about those, and ways to check for their presence, in [`qiskit.utils.optionals`](utils#module-qiskit.utils.optionals "qiskit.utils.optionals"). Trying to use a feature that requires an optional extra will raise a particular error, which subclasses both [`QiskitError`](#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") and the Python built-in `ImportError`.
### MissingOptionalLibraryError
<Class id="qiskit.exceptions.MissingOptionalLibraryError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/exceptions.py#L111-L135" signature="qiskit.exceptions.MissingOptionalLibraryError(libname, name, pip_install=None, msg=None)" modifiers="exception">
Raised when an optional library is missing.
Set the error message. :param libname: Name of missing library :param name: Name of class, function, module that uses this library :param pip\_install: pip install command, if any :param msg: Descriptive message, if any
</Class>
Two more uncommon errors relate to failures in reading user-configuration files, or specifying a filename that cannot be used:
### QiskitUserConfigError
<Class id="qiskit.exceptions.QiskitUserConfigError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/exceptions.py#L105-L108" signature="qiskit.exceptions.QiskitUserConfigError(*message)" modifiers="exception">
Raised when an error is encountered reading a user config file.
Set the error message.
</Class>
### InvalidFileError
<Class id="qiskit.exceptions.InvalidFileError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/exceptions.py#L138-L139" signature="qiskit.exceptions.InvalidFileError(*message)" modifiers="exception">
Raised when the file provided is not valid for the specific task.
Set the error message.
</Class>
## Warnings
Some particular features of Qiskit may raise custom warnings. In general, Qiskit will use built-in Python warnings (such as [`DeprecationWarning`](https://docs.python.org/3/library/exceptions.html#DeprecationWarning "(in Python v3.12)")) when appropriate, but warnings related to Qiskit-specific functionality will be subtypes of [`QiskitWarning`](#qiskit.exceptions.QiskitWarning "qiskit.exceptions.QiskitWarning").
### QiskitWarning
<Class id="qiskit.exceptions.QiskitWarning" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/exceptions.py#L142-L143" signature="qiskit.exceptions.QiskitWarning" modifiers="exception">
Common subclass of warnings for Qiskit-specific warnings being raised.
</Class>
Related to [`MissingOptionalLibraryError`](#qiskit.exceptions.MissingOptionalLibraryError "qiskit.exceptions.MissingOptionalLibraryError"), in some cases an optional dependency might be found, but fail to import for some other reason. In this case, Qiskit will continue as if the dependency is not present, but will raise [`OptionalDependencyImportWarning`](#qiskit.exceptions.OptionalDependencyImportWarning "qiskit.exceptions.OptionalDependencyImportWarning") to let you know about it.
### OptionalDependencyImportWarning
<Class id="qiskit.exceptions.OptionalDependencyImportWarning" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/exceptions.py#L146-L149" signature="qiskit.exceptions.OptionalDependencyImportWarning" modifiers="exception">
Raised when an optional library raises errors during its import.
</Class>
When experimental features are being used, Qiskit will raise [`ExperimentalWarning`](#qiskit.exceptions.ExperimentalWarning "qiskit.exceptions.ExperimentalWarning").
<Admonition title="Warning" type="caution">
Qiskit experimental features can break at any minor release and their API might change without previous notification. Their use is not recommended in production.
</Admonition>
### ExperimentalWarning
<Class id="qiskit.exceptions.ExperimentalWarning" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/exceptions.py#L152-L153" signature="qiskit.exceptions.ExperimentalWarning" modifiers="exception">
Raised when an experimental feature is being used.
</Class>
### Filtering warnings
Python has built-in mechanisms to filter warnings, described in the documentation of the [`warnings`](https://docs.python.org/3/library/warnings.html#module-warnings "(in Python v3.12)") module. You can use these subclasses in your warning filters from within Python to silence warnings you are not interested in. For example, if you are knowingly using experimental features and are comfortable that they make break in later versions, you can silence [`ExperimentalWarning`](#qiskit.exceptions.ExperimentalWarning "qiskit.exceptions.ExperimentalWarning") like this:
```python
import warnings
from qiskit.exceptions import ExperimentalWarning
warnings.filterwarnings("ignore", category=ExperimentalWarning)
```
|
repo/docs/api/qiskit/1.0\exceptions.mdx
|
---
title: qiskit
description: API reference for qiskit
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit
---
<span id="module-qiskit" />
# API Reference
* [Quantum Circuits (`qiskit.circuit`)](circuit)
* [Circuit Library (`qiskit.circuit.library`)](circuit_library)
* [Classical expressions (`qiskit.circuit.classical`)](circuit_classical)
* [Singleton instructions (`qiskit.circuit.singleton`)](circuit_singleton)
* [Compilation Routines (`qiskit.compiler`)](compiler)
* [Visualizations (`qiskit.visualization`)](visualization)
* [ClassicalFunction compiler (`qiskit.circuit.classicalfunction`)](classicalfunction)
* [Circuit Converters (`qiskit.converters`)](converters)
* [Circuit and Schedule Assembler (`qiskit.assembler`)](assembler)
* [DAG Circuits (`qiskit.dagcircuit`)](dagcircuit)
* [Passmanager (`qiskit.passmanager`)](passmanager)
* [Providers Interface (`qiskit.providers`)](providers)
* [Writing a New Provider](providers#writing-a-new-provider)
* [Migrating between Backend API Versions](providers#migrating-between-backend-api-versions)
* [BasicProvider: Python-based Simulators (`qiskit.providers.basic_provider`)](providers_basic_provider)
* [Fake Provider (`qiskit.providers.fake_provider`)](providers_fake_provider)
* [Backend Objects (`qiskit.providers.models`)](providers_models)
* [Pulse (`qiskit.pulse`)](pulse)
* [Circuit Scheduler (`qiskit.scheduler`)](scheduler)
* [Circuit Synthesis (`qiskit.synthesis`)](synthesis)
* [Primitives (`qiskit.primitives`)](primitives)
* [OpenQASM 2 (`qiskit.qasm2`)](qasm2)
* [OpenQASM 3 (`qiskit.qasm3`)](qasm3)
* [Qobj (`qiskit.qobj`)](qobj)
* [QPY serialization (`qiskit.qpy`)](qpy)
* [Quantum Information (`qiskit.quantum_info`)](quantum_info)
* [Experiment Results (`qiskit.result`)](result)
* [Transpiler (`qiskit.transpiler`)](transpiler)
* [Transpiler Passes (`qiskit.transpiler.passes`)](transpiler_passes)
* [Preset Passmanagers (`qiskit.transpiler.preset_passmanagers`)](transpiler_preset)
* [Transpiler Stage Plugin Interface (`qiskit.transpiler.preset_passmanagers.plugin`)](transpiler_plugins)
* [Synthesis Plugins (`qiskit.transpiler.passes.synthesis.plugin`)](transpiler_synthesis_plugins)
* [Utilities (`qiskit.utils`)](utils)
* [Top-level exceptions (`qiskit.exceptions`)](exceptions)
|
repo/docs/api/qiskit/1.0\index.mdx
|
---
title: passmanager
description: API reference for qiskit.passmanager
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.passmanager
---
<span id="module-qiskit.passmanager" />
<span id="qiskit-passmanager" />
<span id="passmanager-qiskit-passmanager" />
# Passmanager
<span id="module-qiskit.passmanager" />
`qiskit.passmanager`
## Overview
The Qiskit pass manager is somewhat inspired by the [LLVM compiler](https://llvm.org/), but it is designed to take a Python object as an input instead of plain source code.
The pass manager converts the input Python object into an intermediate representation (IR), and it can be optimized and get lowered with a variety of transformations over multiple passes. The pass manager framework may employ multiple IRs with interleaved conversion passes, depending on the context of the optimization.
<Admonition title="Note" type="note">
Currently there is no actual use/design of multiple IRs in the builtin Qiskit pass managers. The implementation of the `passmanager` module is agnostic to actual IR types (i.e. no strict type check is performed), and the pass manager works as long as the IR implements all methods required by subsequent passes. A concrete design for the use of multiple IRs might be provided in the future release.
</Admonition>
The passes may consume the hardware constraints that the Qiskit backend may provide. Finally, the IR is converted back to some Python object. Note that the input type and output type are not necessarily the same.
Compilation in the pass manager is a chain of `Task` executions that take an IR and output a new IR with some optimization or data analysis. An atomic task is a *pass* which is a subclass of [`GenericPass`](qiskit.passmanager.GenericPass "qiskit.passmanager.GenericPass") that implements a `run()` method that performs some work on the received IR. A set of passes may form a *flow controller*, which is a subclass of [`BaseController`](qiskit.passmanager.BaseController "qiskit.passmanager.BaseController"), which can implement arbitrary compilation-state-dependent logic for deciding which pass will get run next. Passes share intermediate data via the [`PropertySet`](qiskit.passmanager.PropertySet "qiskit.passmanager.PropertySet") object which is a free-form dictionary. A pass can populate the property set dictionary during the task execution. A flow controller can also consume the property set to control the pass execution, but this access must be read-only. The property set is portable and handed over from pass to pass at execution. In addition to the property set, tasks also receive a [`WorkflowStatus`](qiskit.passmanager.WorkflowStatus "qiskit.passmanager.WorkflowStatus") data structure. This object is initialized when the pass manager is run and handed over to underlying tasks. The status is updated after every pass is run, and contains information about the pipeline state (number of passes run, failure state, and so on) as opposed to the [`PropertySet`](qiskit.passmanager.PropertySet "qiskit.passmanager.PropertySet"), which contains information about the IR being optimized.
A pass manager is a wrapper of the flow controller, with responsibilities of
* Scheduling optimization tasks,
* Converting an input Python object to a particular Qiskit IR,
* Initializing a property set and workflow status,
* Running scheduled tasks to apply a series of transformations to the IR,
* Converting the IR back to an output Python object.
This indicates that the flow controller itself is type-agnostic, and a developer must implement a subclass of the [`BasePassManager`](qiskit.passmanager.BasePassManager "qiskit.passmanager.BasePassManager") to manage the data conversion steps. This *veil of ignorance* allows us to choose the most efficient data representation for a particular pass manager task, while we can reuse the flow control machinery for different input and output types.
A single flow controller always takes a single IR object, and returns a single IR object. Parallelism for multiple input objects is supported by the [`BasePassManager`](qiskit.passmanager.BasePassManager "qiskit.passmanager.BasePassManager") by broadcasting the flow controller via the [`parallel_map()`](utils#qiskit.utils.parallel_map "qiskit.utils.parallel_map") function.
## Examples
We look into a toy optimization task, namely, preparing a row of numbers and remove a digit if the number is five. Such task might be easily done by converting the input numbers into string. We use the pass manager framework here, putting the efficiency aside for a moment to learn how to build a custom Qiskit compiler.
```python
from qiskit.passmanager import BasePassManager, GenericPass, ConditionalController
class ToyPassManager(BasePassManager):
def _passmanager_frontend(self, input_program: int, **kwargs) -> str:
return str(input_program)
def _passmanager_backend(self, passmanager_ir: str, in_program: int, **kwargs) -> int:
return int(passmanager_ir)
```
This pass manager inputs and outputs an integer number, while performing the optimization tasks on a string data. Hence, input, IR, output type are integer, string, integer, respectively. The `_passmanager_frontend()` method defines the conversion from the input data to IR, and `_passmanager_backend()` defines the conversion from the IR to output data. The pass manager backend is also given an `in_program` parameter that contains the original `input_program` to the front end, for referencing any original metadata of the input program for the final conversion.
Next, we implement a pass that removes a digit when the number is five.
```python
class RemoveFive(GenericPass):
def run(self, passmanager_ir: str):
return passmanager_ir.replace("5", "")
task = RemoveFive()
```
Finally, we instantiate a pass manager and schedule the task with it. Running the pass manager with random row of numbers returns new numbers that donβt contain five.
```python
pm = ToyPassManager()
pm.append(task)
pm.run([123456789, 45654, 36785554])
```
Output:
```python
[12346789, 464, 36784]
```
Now we consider the case of conditional execution. We avoid execution of the βremove fiveβ task when the input number is six digits or less. Such control can be implemented by a flow controller. We start from an analysis pass that provides the flow controller with information about the number of digits.
```python
class CountDigits(GenericPass):
def run(self, passmanager_ir: str):
self.property_set["ndigits"] = len(passmanager_ir)
analysis_task = CountDigits()
```
Then, we wrap the remove five task with the [`ConditionalController`](qiskit.passmanager.ConditionalController "qiskit.passmanager.ConditionalController") that runs the stored tasks only when the condition is met.
```python
def digit_condition(property_set):
# Return True when condition is met.
return property_set["ndigits"] > 6
conditional_task = ConditionalController(
tasks=[RemoveFive()],
condition=digit_condition,
)
```
As before, we schedule these passes with the pass manager and run.
```python
pm = ToyPassManager()
pm.append(analysis_task)
pm.append(conditional_task)
pm.run([123456789, 45654, 36785554])
```
Output:
```python
[12346789, 45654, 36784]
```
The βremove fiveβ task is triggered only for the first and third input values, which have more than six digits.
With the pass manager framework, a developer can flexibly customize the optimization task by combining multiple passes and flow controllers. See details for following class API documentations.
## Interface
### Base classes
| | |
| ---------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
| [`BasePassManager`](qiskit.passmanager.BasePassManager "qiskit.passmanager.BasePassManager")(\[tasks,Β max\_iteration]) | Pass manager base class. |
| [`BaseController`](qiskit.passmanager.BaseController "qiskit.passmanager.BaseController")(\[options]) | Base class of controller. |
| [`GenericPass`](qiskit.passmanager.GenericPass "qiskit.passmanager.GenericPass")() | Base class of a single pass manager task. |
### Flow controllers
| | |
| ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| [`FlowControllerLinear`](qiskit.passmanager.FlowControllerLinear "qiskit.passmanager.FlowControllerLinear")(\[tasks,Β options]) | A standard flow controller that runs tasks one after the other. |
| [`ConditionalController`](qiskit.passmanager.ConditionalController "qiskit.passmanager.ConditionalController")(\[tasks,Β condition,Β ...]) | A flow controller runs the pipeline once if the condition is true, or does nothing if the condition is false. |
| [`DoWhileController`](qiskit.passmanager.DoWhileController "qiskit.passmanager.DoWhileController")(\[tasks,Β do\_while,Β options]) | Run the given tasks in a loop until the `do_while` condition on the property set becomes `False`. |
### Compilation state
| | |
| -------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`PropertySet`](qiskit.passmanager.PropertySet "qiskit.passmanager.PropertySet") | A default dictionary-like object. |
| [`WorkflowStatus`](qiskit.passmanager.WorkflowStatus "qiskit.passmanager.WorkflowStatus")(\[count,Β completed\_passes,Β ...]) | Collection of compilation status of workflow, i.e. pass manager run. |
| [`PassManagerState`](qiskit.passmanager.PassManagerState "qiskit.passmanager.PassManagerState")(workflow\_status,Β property\_set) | A portable container object that pass manager tasks communicate through generator. |
### Exceptions
#### PassManagerError
<Class id="qiskit.passmanager.PassManagerError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/passmanager/exceptions.py#L18-L19" signature="qiskit.passmanager.PassManagerError(*message)" modifiers="exception">
Pass manager error.
Set the error message.
</Class>
|
repo/docs/api/qiskit/1.0\passmanager.mdx
|
---
title: primitives
description: API reference for qiskit.primitives
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.primitives
---
<span id="module-qiskit.primitives" />
<span id="qiskit-primitives" />
<span id="primitives-qiskit-primitives" />
# Primitives
<span id="module-qiskit.primitives" />
`qiskit.primitives`
The primitives are computational building blocks to be used in larger applications whose input units, called primitive unified blocs (PUBs), require quantum resources to efficiently produce outputs for.
Currently there are two types of primitives whose abstractions, in their latest versions, are defined by [`BaseSamplerV2`](qiskit.primitives.BaseSamplerV2 "qiskit.primitives.BaseSamplerV2") and [`BaseEstimatorV2`](qiskit.primitives.BaseEstimatorV2 "qiskit.primitives.BaseEstimatorV2"). Samplers are responsible for accepting quantum circuits (or sweeps of values over parameterized circuits) and sampling from their classical output registers. Estimators accept combinations of circuits and observables (or sweeps thereof) to estimate expectation values of the observables.
Qiskit implements a reference implementation for each of these abstractions, [`StatevectorSampler`](qiskit.primitives.StatevectorSampler "qiskit.primitives.StatevectorSampler") and [`StatevectorEstimator`](qiskit.primitives.StatevectorEstimator "qiskit.primitives.StatevectorEstimator").
## Overview of EstimatorV2
[`BaseEstimatorV2`](qiskit.primitives.BaseEstimatorV2 "qiskit.primitives.BaseEstimatorV2") is a primitive that estimates expectation values for provided quantum circuit and observable combinations.
Following construction, an estimator is used by calling its [`run()`](qiskit.primitives.BaseEstimatorV2#run "qiskit.primitives.BaseEstimatorV2.run") method with a list of pubs (Primitive Unified Blocs). Each pub contains three values that, together, define a computation unit of work for the estimator to complete:
* a single [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"), possibly parametrized, whose final state we define as $\psi(\theta)$,
* one or more observables (specified as any `ObservablesArrayLike`, including [`Pauli`](qiskit.quantum_info.Pauli "qiskit.quantum_info.Pauli"), [`SparsePauliOp`](qiskit.quantum_info.SparsePauliOp "qiskit.quantum_info.SparsePauliOp"), `str`) that specify which expectation values to estimate, denoted $H_j$, and
* a collection parameter value sets to bind the circuit against, $\theta_k$.
Running an estimator returns a [`BasePrimitiveJob`](qiskit.primitives.BasePrimitiveJob "qiskit.primitives.BasePrimitiveJob") object, where calling the method [`result()`](qiskit.primitives.BasePrimitiveJob#result "qiskit.primitives.BasePrimitiveJob.result") results in expectation value estimates and metadata for each pub:
$$
\langle\psi(\theta_k)|H_j|\psi(\theta_k)\rangle
$$
The observables and parameter values portion of a pub can be array-valued with arbitrary dimensions, where standard broadcasting rules are applied, so that, in turn, the estimated result for each pub is in general array-valued as well. For more information, please check [here](https://github.com/Qiskit/RFCs/blob/master/0015-estimator-interface.md#arrays-and-broadcasting-).
Here is an example of how an estimator is used.
```python
from qiskit.primitives import StatevectorEstimator as Estimator
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import SparsePauliOp
psi1 = RealAmplitudes(num_qubits=2, reps=2)
psi2 = RealAmplitudes(num_qubits=2, reps=3)
H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)])
H2 = SparsePauliOp.from_list([("IZ", 1)])
H3 = SparsePauliOp.from_list([("ZI", 1), ("ZZ", 1)])
theta1 = [0, 1, 1, 2, 3, 5]
theta2 = [0, 1, 1, 2, 3, 5, 8, 13]
theta3 = [1, 2, 3, 4, 5, 6]
estimator = Estimator()
# calculate [ <psi1(theta1)|H1|psi1(theta1)> ]
job = estimator.run([(psi1, hamiltonian1, [theta1])])
job_result = job.result() # It will block until the job finishes.
print(f"The primitive-job finished with result {job_result}"))
# calculate [ [<psi1(theta1)|H1|psi1(theta1)>,
# <psi1(theta3)|H3|psi1(theta3)>],
# [<psi2(theta2)|H2|psi2(theta2)>] ]
job2 = estimator.run(
[
(psi1, [hamiltonian1, hamiltonian3], [theta1, theta3]),
(psi2, hamiltonian2, theta2)
],
precision=0.01
)
job_result = job2.result()
print(f"The primitive-job finished with result {job_result}")
```
## Overview of SamplerV2
[`BaseSamplerV2`](qiskit.primitives.BaseSamplerV2 "qiskit.primitives.BaseSamplerV2") is a primitive that samples outputs of quantum circuits.
Following construction, a sampler is used by calling its [`run()`](qiskit.primitives.BaseSamplerV2#run "qiskit.primitives.BaseSamplerV2.run") method with a list of pubs (Primitive Unified Blocs). Each pub contains values that, together, define a computational unit of work for the sampler to complete:
* A single [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"), possibly parameterized.
* A collection parameter value sets to bind the circuit against if it is parametric.
* Optionally, the number of shots to sample, determined in the run method if not set.
Running an estimator returns a [`BasePrimitiveJob`](qiskit.primitives.BasePrimitiveJob "qiskit.primitives.BasePrimitiveJob") object, where calling the method [`result()`](qiskit.primitives.BasePrimitiveJob#result "qiskit.primitives.BasePrimitiveJob.result") results in output samples and metadata for each pub.
Here is an example of how a sampler is used.
```python
from qiskit.primitives import StatevectorSampler as Sampler
from qiskit import QuantumCircuit
from qiskit.circuit.library import RealAmplitudes
# create a Bell circuit
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
# create two parameterized circuits
pqc = RealAmplitudes(num_qubits=2, reps=2)
pqc.measure_all()
pqc2 = RealAmplitudes(num_qubits=2, reps=3)
pqc2.measure_all()
theta1 = [0, 1, 1, 2, 3, 5]
theta2 = [0, 1, 2, 3, 4, 5, 6, 7]
# initialization of the sampler
sampler = Sampler()
# collect 128 shots from the Bell circuit
job = sampler.run([bell], shots=128)
job_result = job.result()
print(f"The primitive-job finished with result {job_result}"))
# run a sampler job on the parameterized circuits
job2 = sampler.run([(pqc, theta1), (pqc2, theta2)]
job_result = job2.result()
print(f"The primitive-job finished with result {job_result}"))
```
## Overview of EstimatorV1
Estimator class estimates expectation values of quantum circuits and observables.
An estimator is initialized with an empty parameter set. The estimator is used to create a [`JobV1`](qiskit.providers.JobV1 "qiskit.providers.JobV1"), via the [`qiskit.primitives.Estimator.run()`](qiskit.primitives.Estimator#run "qiskit.primitives.Estimator.run") method. This method is called with the following parameters
* quantum circuits ($\psi_i(\theta)$): list of (parameterized) quantum circuits (a list of [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") objects).
* observables ($H_j$): a list of [`SparsePauliOp`](qiskit.quantum_info.SparsePauliOp "qiskit.quantum_info.SparsePauliOp") objects.
* parameter values ($\theta_k$): list of sets of values to be bound to the parameters of the quantum circuits (list of list of float).
The method returns a [`JobV1`](qiskit.providers.JobV1 "qiskit.providers.JobV1") object, calling [`qiskit.providers.JobV1.result()`](qiskit.providers.JobV1#result "qiskit.providers.JobV1.result") yields the a list of expectation values plus optional metadata like confidence intervals for the estimation.
$$
\langle\psi_i(\theta_k)|H_j|\psi_i(\theta_k)\rangle
$$
Here is an example of how the estimator is used.
```python
from qiskit.primitives import Estimator
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import SparsePauliOp
psi1 = RealAmplitudes(num_qubits=2, reps=2)
psi2 = RealAmplitudes(num_qubits=2, reps=3)
H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)])
H2 = SparsePauliOp.from_list([("IZ", 1)])
H3 = SparsePauliOp.from_list([("ZI", 1), ("ZZ", 1)])
theta1 = [0, 1, 1, 2, 3, 5]
theta2 = [0, 1, 1, 2, 3, 5, 8, 13]
theta3 = [1, 2, 3, 4, 5, 6]
estimator = Estimator()
# calculate [ <psi1(theta1)|H1|psi1(theta1)> ]
job = estimator.run([psi1], [H1], [theta1])
job_result = job.result() # It will block until the job finishes.
print(f"The primitive-job finished with result {job_result}"))
# calculate [ <psi1(theta1)|H1|psi1(theta1)>,
# <psi2(theta2)|H2|psi2(theta2)>,
# <psi1(theta3)|H3|psi1(theta3)> ]
job2 = estimator.run(
[psi1, psi2, psi1],
[H1, H2, H3],
[theta1, theta2, theta3]
)
job_result = job2.result()
print(f"The primitive-job finished with result {job_result}")
```
## Overview of SamplerV1
Sampler class calculates probabilities or quasi-probabilities of bitstrings from quantum circuits.
A sampler is initialized with an empty parameter set. The sampler is used to create a [`JobV1`](qiskit.providers.JobV1 "qiskit.providers.JobV1"), via the [`qiskit.primitives.Sampler.run()`](qiskit.primitives.Sampler#run "qiskit.primitives.Sampler.run") method. This method is called with the following parameters
* quantum circuits ($\psi_i(\theta)$): list of (parameterized) quantum circuits. (a list of [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") objects)
* parameter values ($\theta_k$): list of sets of parameter values to be bound to the parameters of the quantum circuits. (list of list of float)
The method returns a [`JobV1`](qiskit.providers.JobV1 "qiskit.providers.JobV1") object, calling [`qiskit.providers.JobV1.result()`](qiskit.providers.JobV1#result "qiskit.providers.JobV1.result") yields a [`SamplerResult`](qiskit.primitives.SamplerResult "qiskit.primitives.SamplerResult") object, which contains probabilities or quasi-probabilities of bitstrings, plus optional metadata like error bars in the samples.
Here is an example of how sampler is used.
```python
from qiskit.primitives import Sampler
from qiskit import QuantumCircuit
from qiskit.circuit.library import RealAmplitudes
# a Bell circuit
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
# two parameterized circuits
pqc = RealAmplitudes(num_qubits=2, reps=2)
pqc.measure_all()
pqc2 = RealAmplitudes(num_qubits=2, reps=3)
pqc2.measure_all()
theta1 = [0, 1, 1, 2, 3, 5]
theta2 = [0, 1, 2, 3, 4, 5, 6, 7]
# initialization of the sampler
sampler = Sampler()
# Sampler runs a job on the Bell circuit
job = sampler.run(
circuits=[bell], parameter_values=[[]], parameters=[[]]
)
job_result = job.result()
print([q.binary_probabilities() for q in job_result.quasi_dists])
# Sampler runs a job on the parameterized circuits
job2 = sampler.run(
circuits=[pqc, pqc2],
parameter_values=[theta1, theta2],
parameters=[pqc.parameters, pqc2.parameters])
job_result = job2.result()
print([q.binary_probabilities() for q in job_result.quasi_dists])
```
## Migration from Primitives V1 to V2
The formal distinction between the Primitives V1 and V2 APIs are the base classes from which primitives implementations inherit, which are all listed at the bottom of the page. At a conceptual level, however, here are some notable differences keep in mind when migrating from V1 to V2:
1. The V2 primitives favour vectorized inputs, where single circuits can be grouped with vector-valued (or more generally, array-valued) specifications. Each group is called a primitive unified bloc (pub), and each pub gets its own result. For example, in the estimator, you can compare the following differences:
```python
# Favoured V2 pattern. There is only one pub here, but there could be more.
job = estimator_v2.run([(circuit, [obs1, obs2, obs3, obs4])])
evs = job.result()[0].data.evs
# V1 equivalent, where the same circuit must be provided four times.
job = estimator_v1.run([circuit] * 4, [obs1, obs2, obs3, obs4])
evs = job.result().values
```
Not shown in the above example, for brevity, is that the circuit can be parametric, with arrays of parameter value sets broadcasted against the array of observables. The sampler is similar, but with no observables:
```python
# Favoured V2 pattern. There is only one pub here, but there could be more.
job = sampler_v2.run([(circuit, [vals1, vals2, vals3])])
samples = job.result()[0].data
# V1 equivalent, where the same circuit must be provided three times.
sampler_v1.run([circuit] * 3, [vals1, vals2, vals3])
quasi_dists = job.result().quasi_dists
```
2. The V2 sampler returns samples of classical outcomes, preserving the shot order in which they were measured. This is in contrast to the V1 sampler that outputs quasi-probability distributions which are instead an *estimate of the distribution* over classical outcomes. Moreover, the V2 sampler result objects organize data in terms of their input circuitsβ classical register names, which provides natural compatibility with dynamic circuits.
The closest analog of quasi-probability distributions in the V2 interface is the [`get_counts()`](qiskit.primitives.BitArray#get_counts "qiskit.primitives.BitArray.get_counts") method, shown in the example below. However, we emphasize that for utility scale experiments (100+ qubits), the chances of measuring the same bitstring twice are small, so that binning like counts in a dictionary format will not typically be an efficient data processing strategy.
```python
circuit = QuantumCircuit(QuantumRegister(2, "qreg"), ClassicalRegister(2, "alpha"))
circuit.h(0)
circuit.cx(0, 1)
circuit.measure([0, 1], [0, 1])
# V1 sampler usage
result = sampler_v1.run([circuit]).result()
quasi_dist = result.quasi_dists[0]
# V2 sampler usage
result = sampler_v2.run([circuit]).result()
# these are the bit values from the alpha register, over all shots
bitvals = result[0].data.alpha
# we can use it to generate a Counts mapping, which is similar to a quasi prob distribution
counts = bitvals.get_counts()
# which can in turn be converted to the V1 type through normalization
quasi_dist = QuasiDistribution({outcome: freq / shots for outcome, freq in counts.items()})
```
3. The V2 primitives have brought the concept of sampling overhead, inherent to all quantum systems via their inherent probabilistic nature, out of the options and into the API itself. For the sampler, this means that the `shots` argument is now part of the [`run()`](qiskit.primitives.BaseSamplerV2#run "qiskit.primitives.BaseSamplerV2.run") signature, and moreover that each pub is able to specify its own value for `shots`, which takes precedence over any value given to the method. The sampler has an analogous `precision` argument that specifies the error bars that the primitive implementation should target for expectation values estimates.
This concept is not present in the API of the V1 primitives, though all implementations of the V1 primitives have related settings somewhere in their options.
```python
# Sample two circuits at 128 shots each.
sampler_v2.run([circuit1, circuit2], shots=128)
# Sample two circuits at different amounts of shots. The "None"s are necessary as placeholders
# for the lack of parameter values in this example.
sampler_v2.run([(circuit1, None, 123), (circuit2, None, 456)])
# Estimate expectation values for two pubs, both with 0.05 precision.
estimator_v2.run([(circuit1, obs_array1), (circuit2, obs_array_2)], precision=0.05)
```
## Primitives API
### Primitives V2
| | |
| ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`BaseEstimatorV2`](qiskit.primitives.BaseEstimatorV2 "qiskit.primitives.BaseEstimatorV2")() | Estimator V2 base class. |
| [`StatevectorEstimator`](qiskit.primitives.StatevectorEstimator "qiskit.primitives.StatevectorEstimator")(\*\[,Β default\_precision,Β ...]) | Simple implementation of [`BaseEstimatorV2`](qiskit.primitives.BaseEstimatorV2 "qiskit.primitives.BaseEstimatorV2") with full state vector simulation. |
### Sampler V2
| | |
| -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`BaseSamplerV2`](qiskit.primitives.BaseSamplerV2 "qiskit.primitives.BaseSamplerV2")() | Sampler V2 base class. |
| [`StatevectorSampler`](qiskit.primitives.StatevectorSampler "qiskit.primitives.StatevectorSampler")(\*\[,Β default\_shots,Β seed]) | Simple implementation of [`BaseSamplerV2`](qiskit.primitives.BaseSamplerV2 "qiskit.primitives.BaseSamplerV2") using full state vector simulation. |
### Results V2
| | |
| --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| [`BitArray`](qiskit.primitives.BitArray "qiskit.primitives.BitArray")(array,Β num\_bits) | Stores an array of bit values. |
| [`DataBin`](qiskit.primitives.DataBin "qiskit.primitives.DataBin")() | Base class for data bin containers. |
| [`PrimitiveResult`](qiskit.primitives.PrimitiveResult "qiskit.primitives.PrimitiveResult")(pub\_results\[,Β metadata]) | A container for multiple pub results and global metadata. |
| [`PubResult`](qiskit.primitives.PubResult "qiskit.primitives.PubResult")(data\[,Β metadata]) | Result of Primitive Unified Bloc. |
| [`BasePrimitiveJob`](qiskit.primitives.BasePrimitiveJob "qiskit.primitives.BasePrimitiveJob")(job\_id,Β \*\*kwargs) | Primitive job abstract base class. |
| [`PrimitiveJob`](qiskit.primitives.PrimitiveJob "qiskit.primitives.PrimitiveJob")(function,Β \*args,Β \*\*kwargs) | Primitive job class for the reference implementations of Primitives. |
### Estimator V1
| | |
| ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| [`BaseEstimator`](qiskit.primitives.BaseEstimator "qiskit.primitives.BaseEstimator") | alias of [`BaseEstimatorV1`](qiskit.primitives.BaseEstimatorV1 "qiskit.primitives.base.base_estimator.BaseEstimatorV1") |
| [`BaseEstimatorV1`](qiskit.primitives.BaseEstimatorV1 "qiskit.primitives.BaseEstimatorV1")(\*\[,Β options]) | Estimator V1 base class. |
| [`Estimator`](qiskit.primitives.Estimator "qiskit.primitives.Estimator")(\*\[,Β options]) | Reference implementation of [`BaseEstimator`](qiskit.primitives.BaseEstimator "qiskit.primitives.BaseEstimator"). |
| [`BackendEstimator`](qiskit.primitives.BackendEstimator "qiskit.primitives.BackendEstimator")(backend\[,Β options,Β ...]) | Evaluates expectation value using Pauli rotation gates. |
| [`EstimatorResult`](qiskit.primitives.EstimatorResult "qiskit.primitives.EstimatorResult")(values,Β metadata) | Result of Estimator. |
### Sampler V1
| | |
| ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| [`BaseSampler`](qiskit.primitives.BaseSampler "qiskit.primitives.BaseSampler") | alias of [`BaseSamplerV1`](qiskit.primitives.BaseSamplerV1 "qiskit.primitives.base.base_sampler.BaseSamplerV1") |
| [`BaseSamplerV1`](qiskit.primitives.BaseSamplerV1 "qiskit.primitives.BaseSamplerV1")(\*\[,Β options]) | Sampler V1 base class |
| [`Sampler`](qiskit.primitives.Sampler "qiskit.primitives.Sampler")(\*\[,Β options]) | Sampler class. |
| [`BackendSampler`](qiskit.primitives.BackendSampler "qiskit.primitives.BackendSampler")(backend\[,Β options,Β ...]) | A `BaseSampler` implementation that provides an interface for leveraging the sampler interface from any backend. |
| [`SamplerResult`](qiskit.primitives.SamplerResult "qiskit.primitives.SamplerResult")(quasi\_dists,Β metadata) | Result of Sampler. |
|
repo/docs/api/qiskit/1.0\primitives.mdx
|
---
title: providers
description: API reference for qiskit.providers
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.providers
---
<span id="module-qiskit.providers" />
<span id="qiskit-providers" />
<span id="providers-interface-qiskit-providers" />
# Providers Interface
<span id="module-qiskit.providers" />
`qiskit.providers`
This module contains the classes used to build external providers for Terra. A provider is anything that provides an external service to Terra. The typical example of this is a Backend provider which provides [`Backend`](qiskit.providers.Backend "qiskit.providers.Backend") objects which can be used for executing [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") and/or [`Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule") objects. This module contains the abstract classes which are used to define the interface between a provider and terra.
## Version Support
Each providers interface abstract class is individually versioned. When we need to make a change to an interface a new abstract class will be created to define the new interface. These interface changes are not guaranteed to be backwards compatible between versions.
### Version Changes
Each minor version release of qiskit-terra **may** increment the version of any providers interface a single version number. It will be an aggregate of all the interface changes for that release on that interface.
### Version Support Policy
To enable providers to have time to adjust to changes in this interface Terra will support multiple versions of each class at once. Given the nature of one version per release the version deprecation policy is a bit more conservative than the standard deprecation policy. Terra will support a provider interface version for a minimum of 3 minor releases or the first release after 6 months from the release that introduced a version, whichever is longer, prior to a potential deprecation. After that the standard deprecation policy will apply to that interface version. This will give providers and users sufficient time to adapt to potential breaking changes in the interface. So for example lets say in 0.19.0 `BackendV2` is introduced and in the 3 months after the release of 0.19.0 we release 0.20.0, 0.21.0, and 0.22.0, then 7 months after 0.19.0 we release 0.23.0. In 0.23.0 we can deprecate BackendV2, and it needs to still be supported and canβt be removed until the deprecation policy completes.
Itβs worth pointing out that Terraβs version support policy doesnβt mean providers themselves will have the same support story, they can (and arguably should) update to newer versions as soon as they can, the support window is just for Terraβs supported versions. Part of this lengthy window prior to deprecation is to give providers enough time to do their own deprecation of a potential end user impacting change in a user facing part of the interface prior to bumping their version. For example, letβs say we changed the signature to `Backend.run()` in `BackendV34` in a backwards incompatible way. Before Aer could update its [`AerSimulator`](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html#qiskit_aer.AerSimulator "(in Qiskit Aer v0.14.0)") class to be based on version 34 theyβd need to deprecate the old signature prior to switching over. The changeover for Aer is not guaranteed to be lockstep with Terra so we need to ensure there is a sufficient amount of time for Aer to complete its deprecation cycle prior to removing version 33 (ie making version 34 mandatory/the minimum version).
## Abstract Classes
### Provider
| | |
| --------------------------------------------------------------------------- | ------------------------------------------------------------- |
| [`Provider`](qiskit.providers.Provider "qiskit.providers.Provider")() | Base common type for all versioned Provider abstract classes. |
| [`ProviderV1`](qiskit.providers.ProviderV1 "qiskit.providers.ProviderV1")() | Base class for a Backend Provider. |
### Backend
| | |
| --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`Backend`](qiskit.providers.Backend "qiskit.providers.Backend")() | Base common type for all versioned Backend abstract classes. |
| [`BackendV1`](qiskit.providers.BackendV1 "qiskit.providers.BackendV1")(configuration\[,Β provider]) | Abstract class for Backends |
| [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2")(\[provider,Β name,Β description,Β ...]) | Abstract class for Backends |
| [`QubitProperties`](qiskit.providers.QubitProperties "qiskit.providers.QubitProperties")(\[t1,Β t2,Β frequency]) | A representation of the properties of a qubit on a backend. |
| [`BackendV2Converter`](qiskit.providers.BackendV2Converter "qiskit.providers.BackendV2Converter")(backend\[,Β name\_mapping,Β ...]) | A converter class that takes a [`BackendV1`](qiskit.providers.BackendV1 "qiskit.providers.BackendV1") instance and wraps it in a [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") interface. |
| [`convert_to_target`](qiskit.providers.convert_to_target "qiskit.providers.convert_to_target")(configuration\[,Β ...]) | Decode transpiler target from backend data set. |
### Options
| | |
| ---------------------------------------------------------------------------- | ------------------- |
| [`Options`](qiskit.providers.Options "qiskit.providers.Options")(\*\*kwargs) | Base options object |
### Job
| | |
| ---------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| [`Job`](qiskit.providers.Job "qiskit.providers.Job")() | Base common type for all versioned Job abstract classes. |
| [`JobV1`](qiskit.providers.JobV1 "qiskit.providers.JobV1")(backend,Β job\_id,Β \*\*kwargs) | Class to handle jobs |
### Job Status
| | |
| ----------------------------------------------------------------------------- | ------------------------------------- |
| [`JobStatus`](qiskit.providers.JobStatus "qiskit.providers.JobStatus")(value) | Class for job status enumerated type. |
### Exceptions
#### QiskitBackendNotFoundError
<Class id="qiskit.providers.QiskitBackendNotFoundError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/providers/exceptions.py#L30-L33" signature="qiskit.providers.QiskitBackendNotFoundError(*message)" modifiers="exception">
Base class for errors raised while looking for a backend.
Set the error message.
</Class>
#### BackendPropertyError
<Class id="qiskit.providers.BackendPropertyError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/providers/exceptions.py#L36-L39" signature="qiskit.providers.BackendPropertyError(*message)" modifiers="exception">
Base class for errors raised while looking for a backend property.
Set the error message.
</Class>
#### JobError
<Class id="qiskit.providers.JobError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/providers/exceptions.py#L18-L21" signature="qiskit.providers.JobError(*message)" modifiers="exception">
Base class for errors raised by Jobs.
Set the error message.
</Class>
#### JobTimeoutError
<Class id="qiskit.providers.JobTimeoutError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/providers/exceptions.py#L24-L27" signature="qiskit.providers.JobTimeoutError(*message)" modifiers="exception">
Base class for timeout errors raised by jobs.
Set the error message.
</Class>
#### BackendConfigurationError
<Class id="qiskit.providers.BackendConfigurationError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/providers/exceptions.py#L42-L45" signature="qiskit.providers.BackendConfigurationError(*message)" modifiers="exception">
Base class for errors raised by the BackendConfiguration.
Set the error message.
</Class>
# Writing a New Provider
If you have a quantum device or simulator that you would like to integrate with Qiskit you will need to write a provider. A provider will provide Terra with a method to get available [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") objects. The [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") object provides both information describing a backend and its operation for the [`transpiler`](transpiler#module-qiskit.transpiler "qiskit.transpiler") so that circuits can be compiled to something that is optimized and can execute on the backend. It also provides the [`run()`](qiskit.providers.BackendV2#run "qiskit.providers.BackendV2.run") method which can run the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") objects and/or [`Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule") objects. This enables users and other Qiskit APIs to get results from executing circuits on devices in a standard fashion regardless of how the backend is implemented. At a high level the basic steps for writing a provider are:
> * Implement a [`ProviderV1`](qiskit.providers.ProviderV1 "qiskit.providers.ProviderV1") subclass that handles access to the backend(s).
>
> * Implement a [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") subclass and its [`run()`](qiskit.providers.BackendV2#run "qiskit.providers.BackendV2.run") method.
>
> * Add any custom gates for the backendβs basis to the session [`EquivalenceLibrary`](qiskit.circuit.EquivalenceLibrary "qiskit.circuit.EquivalenceLibrary") instance.
>
> * Implement a [`JobV1`](qiskit.providers.JobV1 "qiskit.providers.JobV1") subclass that handles interacting with a running job.
For a simple example of a provider, see the [qiskit-aqt-provider](https://github.com/Qiskit-Partners/qiskit-aqt-provider)
<span id="id1" />
## Provider
A provider class serves a single purpose: to get backend objects that enable executing circuits on a device or simulator. The expectation is that any required credentials and/or authentication will be handled in the initialization of a provider object. The provider object will then provide a list of backends, and methods to filter and acquire backends (using the provided credentials if required). An example provider class looks like:
```python
from qiskit.providers import ProviderV1 as Provider
from qiskit.providers.providerutils import filter_backends
from .backend import MyBackend
class MyProvider(Provider):
def __init__(self, token=None):
super().__init__()
self.token = token
self.backends = [MyBackend(provider=self)]
def backends(self, name=None, **kwargs):
if name:
backends = [
backend for backend in backends if backend.name() == name]
return filter_backends(backends, filters=filters, **kwargs)
```
Ensure that any necessary information for authentication (if required) are present in the class and that the backends method matches the required interface. The rest is up to the specific provider on how to implement.
<span id="id2" />
## Backend
The backend classes are the core to the provider. These classes are what provide the interface between Qiskit and the hardware or simulator that will execute circuits. This includes providing the necessary information to describe a backend to the compiler so that it can embed and optimize any circuit for the backend. There are 4 required things in every backend object: a [`target`](qiskit.providers.BackendV2#target "qiskit.providers.BackendV2.target") property to define the model of the backend for the compiler, a [`max_circuits`](qiskit.providers.BackendV2#max_circuits "qiskit.providers.BackendV2.max_circuits") property to define a limit on the number of circuits the backend can execute in a single batch job (if there is no limit `None` can be used), a [`run()`](qiskit.providers.BackendV2#run "qiskit.providers.BackendV2.run") method to accept job submissions, and a [`_default_options`](qiskit.providers.BackendV2#_default_options "qiskit.providers.BackendV2._default_options") method to define the user configurable options and their default values. For example, a minimum working example would be something like:
```python
from qiskit.providers import BackendV2 as Backend
from qiskit.transpiler import Target
from qiskit.providers import Options
from qiskit.circuit import Parameter, Measure
from qiskit.circuit.library import PhaseGate, SXGate, UGate, CXGate, IGate
class Mybackend(Backend):
def __init__(self):
super().__init__()
# Create Target
self._target = Target("Target for My Backend")
# Instead of None for this and below instructions you can define
# a qiskit.transpiler.InstructionProperties object to define properties
# for an instruction.
lam = Parameter("Ξ»")
p_props = {(qubit,): None for qubit in range(5)}
self._target.add_instruction(PhaseGate(lam), p_props)
sx_props = {(qubit,): None for qubit in range(5)}
self._target.add_instruction(SXGate(), sx_props)
phi = Parameter("Ο")
theta = Parameter("Ο΄")
u_props = {(qubit,): None for qubit in range(5)}
self._target.add_instruction(UGate(theta, phi, lam), u_props)
cx_props = {edge: None for edge in [(0, 1), (1, 2), (2, 3), (3, 4)]}
self._target.add_instruction(CXGate(), cx_props)
meas_props = {(qubit,): None for qubit in range(5)}
self._target.add_instruction(Measure(), meas_props)
id_props = {(qubit,): None for qubit in range(5)}
self._target.add_instruction(IGate(), id_props)
# Set option validators
self.options.set_validator("shots", (1, 4096))
self.options.set_validator("memory", bool)
@property
def target(self):
return self._target
@property
def max_circuits(self):
return 1024
@classmethod
def _default_options(cls):
return Options(shots=1024, memory=False)
def run(circuits, **kwargs):
# serialize circuits submit to backend and create a job
for kwarg in kwargs:
if not hasattr(kwarg, self.options):
warnings.warn(
"Option %s is not used by this backend" % kwarg,
UserWarning, stacklevel=2)
options = {
'shots': kwargs.get('shots', self.options.shots),
'memory': kwargs.get('memory', self.options.shots),
}
job_json = convert_to_wire_format(circuit, options)
job_handle = submit_to_backend(job_jsonb)
return MyJob(self. job_handle, job_json, circuit)
```
### Transpiler Interface
The key piece of the [`Backend`](qiskit.providers.Backend "qiskit.providers.Backend") object is how it describes itself to the compiler. This is handled with the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") class which defines a model of a backend for the transpiler. A backend object will need to return a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") object from the [`target`](qiskit.providers.BackendV2#target "qiskit.providers.BackendV2.target") attribute which the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function will use as its model of a backend target for compilation.
<span id="id3" />
#### Custom Basis Gates
1. If your backend doesnβt use gates in the Qiskit circuit library ([`qiskit.circuit.library`](circuit_library#module-qiskit.circuit.library "qiskit.circuit.library")) you can integrate support for this into your provider. The basic method for doing this is first to define a [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate") subclass for each custom gate in the basis set. For example:
```python
import numpy as np
from qiskit.circuit import Gate
from qiskit.circuit import QuantumCircuit
class SYGate(Gate):
def __init__(self, label=None):
super().__init__("sy", 1, [], label=label)
def _define(self):
qc = QuantumCircuit(1)
q.ry(np.pi / 2, 0)
self.definition = qc
```
The key thing to ensure is that for any custom gates in your Backendβs basis set your custom gateβs name attribute (the first param on `super().__init__()` in the `__init__` definition above) does not conflict with the name of any other gates. The name attribute is what is used to identify the gate in the basis set for the transpiler. If there is a conflict the transpiler will not know which gate to use.
2. Add the custom gate to the target for your backend. This can be done with the [`Target.add_instruction()`](qiskit.transpiler.Target#add_instruction "qiskit.transpiler.Target.add_instruction") method. Youβll need to add an instance of `SYGate` and its parameters to the target so the transpiler knows it exists. For example, assuming this is part of your [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") implementation for your backend:
```python
from qiskit.transpiler import InstructionProperties
sy_props = {
(0,): InstructionProperties(duration=2.3e-6, error=0.0002)
(1,): InstructionProperties(duration=2.1e-6, error=0.0001)
(2,): InstructionProperties(duration=2.5e-6, error=0.0003)
(3,): InstructionProperties(duration=2.2e-6, error=0.0004)
}
self.target.add_instruction(SYGate(), sy_props)
```
The keys in `sy_props` define the qubits where the backend `SYGate` can be used on, and the values define the properties of `SYGate` on that qubit. For multiqubit gates the tuple keys contain all qubit combinations the gate works on (order is significant, i.e. `(0, 1)` is different from `(1, 0)`).
3. After youβve defined the custom gates to use for the backendβs basis set then you need to add equivalence rules to the standard equivalence library so that the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function and [`transpiler`](transpiler#module-qiskit.transpiler "qiskit.transpiler") module can convert an arbitrary circuit using the custom basis set. This can be done by defining equivalent circuits, in terms of the custom gate, for standard gates. Typically if you can convert from a [`CXGate`](qiskit.circuit.library.CXGate "qiskit.circuit.library.CXGate") (if your basis doesnβt include a standard 2 qubit gate) and some commonly used single qubit rotation gates like the [`HGate`](qiskit.circuit.library.HGate "qiskit.circuit.library.HGate") and [`UGate`](qiskit.circuit.library.UGate "qiskit.circuit.library.UGate") that should be sufficient for the transpiler to translate any circuit into the custom basis gates. But, the more equivalence rules that are defined from standard gates to your basis the more efficient translation from an arbitrary circuit to the target basis will be (although not always, and there is a diminishing margin of return).
For example, if you were to add some rules for the above custom `SYGate` we could define the [`U2Gate`](qiskit.circuit.library.U2Gate "qiskit.circuit.library.U2Gate") and [`HGate`](qiskit.circuit.library.HGate "qiskit.circuit.library.HGate"):
```python
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary
from qiskit.circuit.library import HGate
from qiskit.circuit.library import ZGate
from qiskit.circuit.library import RZGate
from qiskit.circuit.library import U2Gate
# H => Z SY
q = qiskit.QuantumRegister(1, "q")
def_sy_h = qiskit.QuantumCircuit(q)
def_sy_h.append(ZGate(), [q[0]], [])
def_sy_h.append(SYGate(), [q[0]], [])
SessionEquivalenceLibrary.add_equivalence(
HGate(), def_sy_h)
# u2 => Z SY Z
phi = qiskit.circuit.Parameter('phi')
lam = qiskit.circuit.Parameter('lambda')
q = qiskit.QuantumRegister(1, "q")
def_sy_u2 = qiskit.QuantumCircuit(q)
def_sy_u2.append(RZGate(lam), [q[0]], [])
def_sy_u2.append(SYGate(), [q[0]], [])
def_sy_u2.append(RZGate(phi), [q[0]], [])
SessionEquivalenceLibrary.add_equivalence(
U2Gate(phi, lam), def_sy_u2)
```
You will want this to be run on import so that as soon as the providerβs package is imported it will be run. This will ensure that any time the [`BasisTranslator`](qiskit.transpiler.passes.BasisTranslator "qiskit.transpiler.passes.BasisTranslator") pass is run with the custom gates the equivalence rules are defined.
Itβs also worth noting that depending on the basis youβre using, some optimization passes in the transpiler, such as [`Optimize1qGatesDecomposition`](qiskit.transpiler.passes.Optimize1qGatesDecomposition "qiskit.transpiler.passes.Optimize1qGatesDecomposition"), may not be able to operate with your custom basis. For our `SYGate` example, the [`Optimize1qGatesDecomposition`](qiskit.transpiler.passes.Optimize1qGatesDecomposition "qiskit.transpiler.passes.Optimize1qGatesDecomposition") will not be able to simplify runs of single qubit gates into the SY basis. This is because the `OneQubitEulerDecomposer` class does not know how to work in the SY basis. To solve this the `SYGate` class would need to be added to Qiskit and `OneQubitEulerDecomposer` updated to support decomposing to the `SYGate`. Longer term that is likely a better direction for custom basis gates and contributing the definitions and support in the transpiler will ensure that it continues to be well supported by Qiskit moving forward.
<span id="custom-transpiler-backend" />
#### Custom Transpiler Passes
The transpiler supports the ability for backends to provide custom transpiler stage implementations to facilitate hardware specific optimizations and circuit transformations. Currently there are two stages supported, `get_translation_stage_plugin()` and `get_scheduling_stage_plugin()` which allow a backend to specify string plugin names to be used as the default translation and scheduling stages, respectively. These hook points in a [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") class can be used if your backend has requirements for compilation that are not met by the current backend/[`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") interface. Please also consider submitting a Github issue describing your use case as there is interest in improving these interfaces to be able to describe more hardware architectures in greater depth.
To leverage these hook points you just need to add the methods to your [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") implementation and have them return a string plugin name. For example:
```python
class Mybackend(BackendV2):
def get_scheduling_stage_plugin(self):
return "SpecialDD"
def get_translation_stage_plugin(self):
return "BasisTranslatorWithCustom1qOptimization"
```
This snippet of a backend implementation will now have the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function use the `SpecialDD` plugin for the scheduling stage and the `BasisTranslatorWithCustom1qOptimization` plugin for the translation stage by default when the target is set to `Mybackend`. Note that users may override these choices by explicitly selecting a different plugin name. For this interface to work though transpiler stage plugins must be implemented for the returned plugin name. You can refer to [`qiskit.transpiler.preset_passmanagers.plugin`](transpiler_plugins#module-qiskit.transpiler.preset_passmanagers.plugin "qiskit.transpiler.preset_passmanagers.plugin") module documentation for details on how to implement plugins. The typical expectation is that if your backend requires custom passes as part of a compilation stage the provider package will include the transpiler stage plugins that use those passes. However, this is not required and any valid method (from a built-in method or external plugin) can be used.
This way if these two compilation steps are **required** for running or providing efficient output on `Mybackend` the transpiler will be able to perform these custom steps without any manual user input.
### Run Method
Of key importance is the [`run()`](qiskit.providers.BackendV2#run "qiskit.providers.BackendV2.run") method, which is used to actually submit circuits to a device or simulator. The run method handles submitting the circuits to the backend to be executed and returning a [`Job`](qiskit.providers.Job "qiskit.providers.Job") object. Depending on the type of backend this typically involves serializing the circuit object into the API format used by a backend. For example, on IBM backends from the `qiskit-ibm-provider` package this involves converting from a quantum circuit and options into a [`qpy`](qpy#module-qiskit.qpy "qiskit.qpy") payload embedded in JSON and submitting that to the IBM Quantum API. Since every backend interface is different (and in the case of the local simulators serialization may not be needed) it is expected that the backendβs [`run`](qiskit.providers.BackendV2#run "qiskit.providers.BackendV2.run") method will handle this conversion.
An example run method would be something like:
```python
def run(self, circuits. **kwargs):
for kwarg in kwargs:
if not hasattr(kwarg, self.options):
warnings.warn(
"Option %s is not used by this backend" % kwarg,
UserWarning, stacklevel=2)
options = {
'shots': kwargs.get('shots', self.options.shots)
'memory': kwargs.get('memory', self.options.shots),
}
job_json = convert_to_wire_format(circuit, options)
job_handle = submit_to_backend(job_jsonb)
return MyJob(self. job_handle, job_json, circuit)
```
<span id="id4" />
### Options
There are often several options for a backend that control how a circuit is run. The typical example of this is something like the number of `shots` which is how many times the circuit is to be executed. The options available for a backend are defined using an [`Options`](qiskit.providers.Options "qiskit.providers.Options") object. This object is initially created by the [`_default_options`](qiskit.providers.BackendV2#_default_options "qiskit.providers.BackendV2._default_options") method of a Backend class. The default options returns an initialized [`Options`](qiskit.providers.Options "qiskit.providers.Options") object with all the default values for all the options a backend supports. For example, if the backend supports only supports `shots` the [`_default_options`](qiskit.providers.BackendV2#_default_options "qiskit.providers.BackendV2._default_options") method would look like:
```python
@classmethod
def _default_options(cls):
return Options(shots=1024)
```
You can also set validators on an [`Options`](qiskit.providers.Options "qiskit.providers.Options") object to provide limits and validation on user provided values based on whatβs acceptable for your backend. For example, if the `"shots"` option defined above can be set to any value between 1 and 4096 you can set the validator on the options object for you backend with:
```python
self.options.set_validator("shots", (1, 4096))
```
you can refer to the [`set_validator()`](qiskit.providers.Options#set_validator "qiskit.providers.Options.set_validator") documentation for a full list of validation options.
<span id="id5" />
## Job
The output from the [`run`](qiskit.providers.BackendV2#run "qiskit.providers.BackendV2.run") method is a [`JobV1`](qiskit.providers.JobV1 "qiskit.providers.JobV1") object. Each provider is expected to implement a custom job subclass that defines the behavior for the provider. There are 2 types of jobs depending on the backendβs execution method, either a sync or async. By default jobs are considered async and the expectation is that it represents a handle to the async execution of the circuits submitted with `Backend.run()`. An async job object provides users the ability to query the status of the execution, cancel a running job, and block until the execution is finished. The [`result`](qiskit.providers.JobV1#result "qiskit.providers.JobV1.result") is the primary user facing method which will block until the execution is complete and then will return a [`Result`](qiskit.result.Result "qiskit.result.Result") object with results of the job.
For some backends (mainly local simulators) the execution of circuits is a synchronous operation and there is no need to return a handle to a running job elsewhere. For sync jobs its expected that the [`run`](qiskit.providers.BackendV1#run "qiskit.providers.BackendV1.run") method on the backend will block until a [`Result`](qiskit.result.Result "qiskit.result.Result") object is generated and the sync job will return with that inner [`Result`](qiskit.result.Result "qiskit.result.Result") object.
An example job class for an async API based backend would look something like:
```python
from qiskit.providers import JobV1 as Job
from qiskit.providers import JobError
from qiskit.providers import JobTimeoutError
from qiskit.providers.jobstatus import JobStatus
from qiskit.result import Result
class MyJob(Job):
def __init__(self, backend, job_id, job_json, circuits):
super().__init__(backend, job_id)
self._backend = backend
self.job_json = job_json
self.circuits = circuits
def _wait_for_result(self, timeout=None, wait=5):
start_time = time.time()
result = None
while True:
elapsed = time.time() - start_time
if timeout and elapsed >= timeout:
raise JobTimeoutError('Timed out waiting for result')
result = get_job_status(self._job_id)
if result['status'] == 'complete':
break
if result['status'] == 'error':
raise JobError('Job error')
time.sleep(wait)
return result
def result(self, timeout=None, wait=5):
result = self._wait_for_result(timeout, wait)
results = [{'success': True, 'shots': len(result['counts']),
'data': result['counts']}]
return Result.from_dict({
'results': results,
'backend_name': self._backend.configuration().backend_name,
'backend_version': self._backend.configuration().backend_version,
'job_id': self._job_id,
'qobj_id': ', '.join(x.name for x in self.circuits),
'success': True,
})
def status(self):
result = get_job_status(self._job_id)
if result['status'] == 'running':
status = JobStatus.RUNNING
elif result['status'] == 'complete':
status = JobStatus.DONE
else:
status = JobStatus.ERROR
return status
def submit(self):
raise NotImplementedError
```
and for a sync job:
```python
class MySyncJob(Job):
_async = False
def __init__(self, backend, job_id, result):
super().__init__(backend, job_id)
self._result = result
def submit(self):
return
def result(self):
return self._result
def status(self):
return JobStatus.DONE
```
## Primitives
While not directly part of the provider interface, the [`qiskit.primitives`](primitives#module-qiskit.primitives "qiskit.primitives") module is tightly coupled with providers. Specifically the primitive interfaces, such as `BaseSampler` and `BaseEstimator`, are designed to enable provider implementations to provide custom implementations which are optimized for the providerβs backends. This can include customizations like circuit transformations, additional pre- and post-processing, batching, caching, error mitigation, etc. The concept of the [`qiskit.primitives`](primitives#module-qiskit.primitives "qiskit.primitives") module is to explicitly enable this as the primitive objects are higher level abstractions to produce processed higher level outputs (such as probability distributions and expectation values) that abstract away the mechanics of getting the best result efficiently, to concentrate on higher level applications using these outputs.
For example, if your backends were well suited to leverage [mthree](https://github.com/Qiskit-Partners/mthree/) measurement mitigation to improve the quality of the results, you could implement a provider-specific [`Sampler`](qiskit.primitives.Sampler "qiskit.primitives.Sampler") implementation that leverages the `M3Mitigation` class internally to run the circuits and return quasi-probabilities directly from mthree in the result. Doing this would enable algorithms to get the best results with mitigation applied directly from your backends. You can refer to the documentation in [`qiskit.primitives`](primitives#module-qiskit.primitives "qiskit.primitives") on how to write custom implementations. Also the built-in implementations: [`Sampler`](qiskit.primitives.Sampler "qiskit.primitives.Sampler"), [`Estimator`](qiskit.primitives.Estimator "qiskit.primitives.Estimator"), [`BackendSampler`](qiskit.primitives.BackendSampler "qiskit.primitives.BackendSampler"), and [`BackendEstimator`](qiskit.primitives.BackendEstimator "qiskit.primitives.BackendEstimator") can serve as references/models on how to implement these as well.
# Migrating between Backend API Versions
<span id="backendv1-backendv2" />
## BackendV1 -> BackendV2
The [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") class re-defined user access for most properties of a backend to make them work with native Qiskit data structures and have flatter access patterns. However this means when using a provider that upgrades from [`BackendV1`](qiskit.providers.BackendV1 "qiskit.providers.BackendV1") to [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") existing access patterns will need to be adjusted. It is expected for existing providers to deprecate the old access where possible to provide a graceful migration, but eventually users will need to adjust code. The biggest change to adapt to in [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") is that most of the information accessible about a backend is contained in its [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") object and the backendβs attributes often query its [`target`](qiskit.providers.BackendV2#target "qiskit.providers.BackendV2.target") attribute to return information, however in many cases the attributes only provide a subset of information the target can contain. For example, `backend.coupling_map` returns a [`CouplingMap`](qiskit.transpiler.CouplingMap "qiskit.transpiler.CouplingMap") constructed from the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") accessible in the [`target`](qiskit.providers.BackendV2#target "qiskit.providers.BackendV2.target") attribute, however the target may contain instructions that operate on more than two qubits (which canβt be represented in a [`CouplingMap`](qiskit.transpiler.CouplingMap "qiskit.transpiler.CouplingMap")) or has instructions that only operate on a subset of qubits (or two qubit links for a two qubit instruction) which wonβt be detailed in the full coupling map returned by [`coupling_map`](qiskit.providers.BackendV2#coupling_map "qiskit.providers.BackendV2.coupling_map"). So depending on your use case it might be necessary to look deeper than just the equivalent access with [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2").
Below is a table of example access patterns in [`BackendV1`](qiskit.providers.BackendV1 "qiskit.providers.BackendV1") and the new form with [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2"):
| [`BackendV1`](qiskit.providers.BackendV1 "qiskit.providers.BackendV1") | [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") | Notes |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `backend.configuration().n_qubits` | `backend.num_qubits` | |
| `backend.configuration().coupling_map` | `backend.coupling_map` | The return from [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") is a [`CouplingMap`](qiskit.transpiler.CouplingMap "qiskit.transpiler.CouplingMap") object. while in [`BackendV1`](qiskit.providers.BackendV1 "qiskit.providers.BackendV1") it is an edge list. Also this is just a view of the information contained in `backend.target` which may only be a subset of the information contained in [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") object. |
| `backend.configuration().backend_name` | `backend.name` | |
| `backend.configuration().backend_version` | `backend.backend_version` | The [`version`](qiskit.providers.BackendV2#version "qiskit.providers.BackendV2.version") attribute represents the version of the abstract [`Backend`](qiskit.providers.Backend "qiskit.providers.Backend") interface the object implements while [`backend_version`](qiskit.providers.BackendV2#backend_version "qiskit.providers.BackendV2.backend_version") is metadata about the version of the backend itself. |
| `backend.configuration().basis_gates` | `backend.operation_names` | The [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") return is a list of operation names contained in the `backend.target` attribute. The [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") may contain more information that can be expressed by this list of names. For example, that some operations only work on a subset of qubits or that some names implement the same gate with different parameters. |
| `backend.configuration().dt` | `backend.dt` | |
| `backend.configuration().dtm` | `backend.dtm` | |
| `backend.configuration().max_experiments` | `backend.max_circuits` | |
| `backend.configuration().online_date` | `backend.online_date` | |
| `InstructionDurations.from_backend(backend)` | `backend.instruction_durations` | |
| `backend.defaults().instruction_schedule_map` | `backend.instruction_schedule_map` | |
| `backend.properties().t1(0)` | `backend.qubit_properties(0).t1` | |
| `backend.properties().t2(0)` | `backend.qubit_properties(0).t2` | |
| `backend.properties().frequency(0)` | `backend.qubit_properties(0).frequency` | |
| `backend.properties().readout_error(0)` | `backend.target["measure"][(0,)].error` | In [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") the error rate for the [`Measure`](qiskit.circuit.library.Measure "qiskit.circuit.library.Measure") operation on a given qubit is used to model the readout error. However a [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") can implement multiple measurement types and list them separately in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"). |
| `backend.properties().readout_length(0)` | `backend.target["measure"][(0,)].duration` | In [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") the duration for the [`Measure`](qiskit.circuit.library.Measure "qiskit.circuit.library.Measure") operation on a given qubit is used to model the readout length. However, a [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") can implement multiple measurement types and list them separately in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"). |
There is also a [`BackendV2Converter`](qiskit.providers.BackendV2Converter "qiskit.providers.BackendV2Converter") class available that enables you to wrap a [`BackendV1`](qiskit.providers.BackendV1 "qiskit.providers.BackendV1") object with a [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") interface.
|
repo/docs/api/qiskit/1.0\providers.mdx
|
---
title: basic_provider
description: API reference for qiskit.providers.basic_provider
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.providers.basic_provider
---
<span id="module-qiskit.providers.basic_provider" />
<span id="qiskit-providers-basicprovider" />
<span id="basicprovider-python-based-simulators-qiskit-providers-basic-provider" />
# BasicProvider: Python-based Simulators
<span id="module-qiskit.providers.basic_provider" />
`qiskit.providers.basic_provider`
A module of Python-based quantum simulators. Simulators can be accessed via the BasicProvider provider, e.g.:
```python
from qiskit.providers.basic_provider import BasicProvider
backend = BasicProvider().get_backend('basic_simulator')
```
## Simulators
| | |
| ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| [`BasicSimulator`](qiskit.providers.basic_provider.BasicSimulator "qiskit.providers.basic_provider.BasicSimulator")(\[provider,Β target]) | Python implementation of a basic (non-efficient) quantum simulator. |
## Provider
| | |
| ------------------------------------------------------------------------------------------------------------------ | ----------------------------- |
| [`BasicProvider`](qiskit.providers.basic_provider.BasicProvider "qiskit.providers.basic_provider.BasicProvider")() | Provider for test simulators. |
## Job Class
| | |
| --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| [`BasicProviderJob`](qiskit.providers.basic_provider.BasicProviderJob "qiskit.providers.basic_provider.BasicProviderJob")(backend,Β job\_id,Β result) | BasicProviderJob class. |
## Exceptions
| | |
| ------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- |
| [`BasicProviderError`](qiskit.providers.basic_provider.BasicProviderError "qiskit.providers.basic_provider.BasicProviderError")(\*message) | Base class for errors raised by the Basic Provider. |
|
repo/docs/api/qiskit/1.0\providers_basic_provider.mdx
|
---
title: fake_provider
description: API reference for qiskit.providers.fake_provider
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.providers.fake_provider
---
<span id="module-qiskit.providers.fake_provider" />
<span id="qiskit-providers-fakeprovider" />
<span id="fake-provider-qiskit-providers-fake-provider" />
# Fake Provider
<span id="module-qiskit.providers.fake_provider" />
`qiskit.providers.fake_provider`
## Overview
The fake provider module in Qiskit contains fake (simulated) backend classes useful for testing the transpiler and other backend-facing functionality.
## Example Usage
Here is an example of using a simulated backend for transpilation and running.
```python
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.visualization import plot_histogram
# Generate a 5-qubit simulated backend
backend = GenericBackendV2(num_qubits=5)
# Create a simple circuit
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(0,2)
circuit.measure_all()
circuit.draw('mpl')
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(circuit, backend)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
plot_histogram(counts)
```



## V2 Simulated Backends
| | |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| [`GenericBackendV2`](qiskit.providers.fake_provider.GenericBackendV2 "qiskit.providers.fake_provider.GenericBackendV2")(num\_qubits\[,Β basis\_gates,Β ...]) | Generic [`BackendV2`](qiskit.providers.BackendV2 "qiskit.providers.BackendV2") implementation with a configurable constructor. |
## V1 Fake Backends (Legacy interface)
| | |
| ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| [`FakeOpenPulse2Q`](qiskit.providers.fake_provider.FakeOpenPulse2Q "qiskit.providers.fake_provider.FakeOpenPulse2Q")() | A fake 2 qubit backend for pulse test. |
| [`FakeOpenPulse3Q`](qiskit.providers.fake_provider.FakeOpenPulse3Q "qiskit.providers.fake_provider.FakeOpenPulse3Q")() | Trivial extension of the FakeOpenPulse2Q. |
| [`Fake1Q`](qiskit.providers.fake_provider.Fake1Q "qiskit.providers.fake_provider.Fake1Q")() | A fake 1Q backend. |
| [`Fake5QV1`](qiskit.providers.fake_provider.Fake5QV1 "qiskit.providers.fake_provider.Fake5QV1")() | A fake backend with the following characteristics: |
| [`Fake20QV1`](qiskit.providers.fake_provider.Fake20QV1 "qiskit.providers.fake_provider.Fake20QV1")() | A fake backend with the following characteristics: |
| [`Fake7QPulseV1`](qiskit.providers.fake_provider.Fake7QPulseV1 "qiskit.providers.fake_provider.Fake7QPulseV1")() | A fake **pulse** backend with the following characteristics: |
| [`Fake27QPulseV1`](qiskit.providers.fake_provider.Fake27QPulseV1 "qiskit.providers.fake_provider.Fake27QPulseV1")() | A fake **pulse** backend with the following characteristics: |
| [`Fake127QPulseV1`](qiskit.providers.fake_provider.Fake127QPulseV1 "qiskit.providers.fake_provider.Fake127QPulseV1")() | A fake **pulse** backend with the following characteristics: |
## Fake Backend Base Classes
The V1 fake backends are based on a set of base classes:
### FakeBackend
<Class id="qiskit.providers.fake_provider.FakeBackend" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/providers/fake_provider/fake_backend.py#L444-L563" signature="qiskit.providers.fake_provider.FakeBackend(configuration, time_alive=10)" modifiers="class">
This is a dummy backend just for testing purposes.
FakeBackend initializer.
**Parameters**
* **configuration** ([*BackendConfiguration*](qiskit.providers.models.BackendConfiguration "qiskit.providers.models.BackendConfiguration")) β backend configuration
* **time\_alive** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β time to wait before returning result
</Class>
### FakeQasmBackend
<Class id="qiskit.providers.fake_provider.FakeQasmBackend" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/providers/fake_provider/fake_qasm_backend.py#L30-L72" signature="qiskit.providers.fake_provider.FakeQasmBackend" modifiers="class">
A fake OpenQASM backend.
FakeBackend initializer.
**Parameters**
* **configuration** ([*BackendConfiguration*](qiskit.providers.models.BackendConfiguration "qiskit.providers.models.BackendConfiguration")) β backend configuration
* **time\_alive** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β time to wait before returning result
</Class>
### FakePulseBackend
<Class id="qiskit.providers.fake_provider.FakePulseBackend" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/providers/fake_provider/fake_pulse_backend.py#L24-L43" signature="qiskit.providers.fake_provider.FakePulseBackend" modifiers="class">
A fake pulse backend.
FakeBackend initializer.
**Parameters**
* **configuration** ([*BackendConfiguration*](qiskit.providers.models.BackendConfiguration "qiskit.providers.models.BackendConfiguration")) β backend configuration
* **time\_alive** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β time to wait before returning result
</Class>
|
repo/docs/api/qiskit/1.0\providers_fake_provider.mdx
|
---
title: models
description: API reference for qiskit.providers.models
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.providers.models
---
<span id="module-qiskit.providers.models" />
<span id="qiskit-providers-models" />
<span id="backend-objects-qiskit-providers-models" />
# Backend Objects
<span id="module-qiskit.providers.models" />
`qiskit.providers.models`
Qiskit schema-conformant objects used by the backends and providers.
## Backend Objects
| | |
| -------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| [`BackendConfiguration`](qiskit.providers.models.BackendConfiguration "qiskit.providers.models.BackendConfiguration")(backend\_name,Β ...\[,Β ...]) | Backwards compat shim representing an abstract backend configuration. |
| [`BackendProperties`](qiskit.providers.models.BackendProperties "qiskit.providers.models.BackendProperties")(backend\_name,Β ...) | Class representing backend properties |
| [`BackendStatus`](qiskit.providers.models.BackendStatus "qiskit.providers.models.BackendStatus")(backend\_name,Β backend\_version,Β ...) | Class representing Backend Status. |
| [`QasmBackendConfiguration`](qiskit.providers.models.QasmBackendConfiguration "qiskit.providers.models.QasmBackendConfiguration")(backend\_name,Β ...) | Class representing an OpenQASM 2.0 Backend Configuration. |
| [`PulseBackendConfiguration`](qiskit.providers.models.PulseBackendConfiguration "qiskit.providers.models.PulseBackendConfiguration")(backend\_name,Β ...) | Static configuration state for an OpenPulse enabled backend. |
| [`UchannelLO`](qiskit.providers.models.UchannelLO "qiskit.providers.models.UchannelLO")(q,Β scale) | Class representing a U Channel LO |
| [`GateConfig`](qiskit.providers.models.GateConfig "qiskit.providers.models.GateConfig")(name,Β parameters,Β qasm\_def\[,Β ...]) | Class representing a Gate Configuration |
| [`PulseDefaults`](qiskit.providers.models.PulseDefaults "qiskit.providers.models.PulseDefaults")(qubit\_freq\_est,Β meas\_freq\_est,Β ...) | Description of default settings for Pulse systems. |
| [`Command`](qiskit.providers.models.Command "qiskit.providers.models.Command")(name\[,Β qubits,Β sequence]) | Class representing a Command. |
| [`JobStatus`](qiskit.providers.models.JobStatus "qiskit.providers.models.JobStatus")(job\_id,Β status,Β status\_msg,Β \*\*kwargs) | Model for JobStatus. |
| [`GateProperties`](qiskit.providers.models.GateProperties "qiskit.providers.models.GateProperties")(qubits,Β gate,Β parameters,Β ...) | Class representing a gate's properties |
| [`Nduv`](qiskit.providers.models.Nduv "qiskit.providers.models.Nduv")(date,Β name,Β unit,Β value) | Class representing name-date-unit-value |
|
repo/docs/api/qiskit/1.0\providers_models.mdx
|
---
title: pulse
description: API reference for qiskit.pulse
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.pulse
---
<span id="module-qiskit.pulse" />
<span id="qiskit-pulse" />
<span id="pulse-qiskit-pulse" />
# Pulse
<span id="module-qiskit.pulse" />
`qiskit.pulse`
Qiskit-Pulse is a pulse-level quantum programming kit. This lower level of programming offers the user more control than programming with [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")s.
Extracting the greatest performance from quantum hardware requires real-time pulse-level instructions. Pulse answers that need: it enables the quantum physicist *user* to specify the exact time dynamics of an experiment. It is especially powerful for error mitigation techniques.
The input is given as arbitrary, time-ordered signals (see: [Instructions](#pulse-insts)) scheduled in parallel over multiple virtual hardware or simulator resources (see: [Channels](#pulse-channels)). The system also allows the user to recover the time dynamics of the measured output.
This is sufficient to allow the quantum physicist to explore and correct for noise in a quantum system.
<span id="module-qiskit.pulse.instructions" />
<span id="instructions-qiskit-pulse-instructions" />
<span id="pulse-insts" />
## Instructions
<span id="module-qiskit.pulse" />
`qiskit.pulse.instructions`
The `instructions` module holds the various [`Instruction`](#qiskit.pulse.instructions.Instruction "qiskit.pulse.instructions.Instruction")s which are supported by Qiskit Pulse. Instructions have operands, which typically include at least one [`Channel`](#qiskit.pulse.channels.Channel "qiskit.pulse.channels.Channel") specifying where the instruction will be applied.
Every instruction has a duration, whether explicitly included as an operand or implicitly defined. For instance, a [`ShiftPhase`](qiskit.pulse.instructions.ShiftPhase "qiskit.pulse.instructions.ShiftPhase") instruction can be instantiated with operands *phase* and *channel*, for some float `phase` and a [`Channel`](#qiskit.pulse.channels.Channel "qiskit.pulse.channels.Channel") `channel`:
```python
ShiftPhase(phase, channel)
```
The duration of this instruction is implicitly zero. On the other hand, the [`Delay`](qiskit.pulse.instructions.Delay "qiskit.pulse.instructions.Delay") instruction takes an explicit duration:
```python
Delay(duration, channel)
```
An instruction can be added to a [`Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule"), which is a sequence of scheduled Pulse `Instruction` s over many channels. `Instruction` s and `Schedule` s implement the same interface.
| | |
| ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`Acquire`](qiskit.pulse.instructions.Acquire "qiskit.pulse.instructions.Acquire")(duration,Β channel\[,Β mem\_slot,Β ...]) | The Acquire instruction is used to trigger the ADC associated with a particular qubit; e.g. |
| [`Reference`](qiskit.pulse.instructions.Reference "qiskit.pulse.instructions.Reference")(name,Β \*extra\_keys) | Pulse compiler directive that refers to a subroutine. |
| [`Delay`](qiskit.pulse.instructions.Delay "qiskit.pulse.instructions.Delay")(duration,Β channel\[,Β name]) | A blocking instruction with no other effect. |
| [`Play`](qiskit.pulse.instructions.Play "qiskit.pulse.instructions.Play")(pulse,Β channel\[,Β name]) | This instruction is responsible for applying a pulse on a channel. |
| [`RelativeBarrier`](qiskit.pulse.instructions.RelativeBarrier "qiskit.pulse.instructions.RelativeBarrier")(\*channels\[,Β name]) | Pulse `RelativeBarrier` directive. |
| [`SetFrequency`](qiskit.pulse.instructions.SetFrequency "qiskit.pulse.instructions.SetFrequency")(frequency,Β channel\[,Β name]) | Set the channel frequency. |
| [`ShiftFrequency`](qiskit.pulse.instructions.ShiftFrequency "qiskit.pulse.instructions.ShiftFrequency")(frequency,Β channel\[,Β name]) | Shift the channel frequency away from the current frequency. |
| [`SetPhase`](qiskit.pulse.instructions.SetPhase "qiskit.pulse.instructions.SetPhase")(phase,Β channel\[,Β name]) | The set phase instruction sets the phase of the proceeding pulses on that channel to `phase` radians. |
| [`ShiftPhase`](qiskit.pulse.instructions.ShiftPhase "qiskit.pulse.instructions.ShiftPhase")(phase,Β channel\[,Β name]) | The shift phase instruction updates the modulation phase of proceeding pulses played on the same [`Channel`](#qiskit.pulse.channels.Channel "qiskit.pulse.channels.Channel"). |
| [`Snapshot`](qiskit.pulse.instructions.Snapshot "qiskit.pulse.instructions.Snapshot")(label\[,Β snapshot\_type,Β name]) | An instruction targeted for simulators, to capture a moment in the simulation. |
| [`TimeBlockade`](qiskit.pulse.instructions.TimeBlockade "qiskit.pulse.instructions.TimeBlockade")(duration,Β channel\[,Β name]) | Pulse `TimeBlockade` directive. |
These are all instances of the same base class:
### Instruction
<Class id="qiskit.pulse.instructions.Instruction" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/instructions/instruction.py#L36-L269" signature="qiskit.pulse.instructions.Instruction(operands, name=None)" modifiers="class">
The smallest schedulable unit: a single instruction. It has a fixed duration and specified channels.
Instruction initializer.
**Parameters**
* **operands** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.12)")) β The argument list.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Optional display name for this instruction.
</Class>
<span id="module-qiskit.pulse.library" />
<span id="pulse-library-qiskit-pulse-library" />
## Pulse Library
<span id="module-qiskit.pulse" />
`qiskit.pulse.library`
This library provides Pulse users with convenient methods to build Pulse waveforms.
A pulse programmer can choose from one of several [Pulse Models](#pulse-models) such as [`Waveform`](qiskit.pulse.library.Waveform "qiskit.pulse.library.Waveform") and [`SymbolicPulse`](qiskit.pulse.library.SymbolicPulse "qiskit.pulse.library.SymbolicPulse") to create a pulse program. The [`Waveform`](qiskit.pulse.library.Waveform "qiskit.pulse.library.Waveform") model directly stores the waveform data points in each class instance. This model provides the most flexibility to express arbitrary waveforms and allows a rapid prototyping of new control techniques. However, this model is typically memory inefficient and might be hard to scale to large-size quantum processors. A user can directly instantiate the [`Waveform`](qiskit.pulse.library.Waveform "qiskit.pulse.library.Waveform") class with `samples` argument which is usually a complex numpy array or any kind of array-like data.
In contrast, the [`SymbolicPulse`](qiskit.pulse.library.SymbolicPulse "qiskit.pulse.library.SymbolicPulse") model only stores the function and its parameters that generate the waveform in a class instance. It thus provides greater memory efficiency at the price of less flexibility in the waveform. This model also defines a small set of pulse subclasses in [Parametric Pulse Representation](#symbolic-pulses) which are commonly used in superconducting quantum processors. An instance of these subclasses can be serialized in the [QPY Format](qpy#qpy-format) while keeping the memory-efficient parametric representation of waveforms. Note that [`Waveform`](qiskit.pulse.library.Waveform "qiskit.pulse.library.Waveform") object can be generated from an instance of a [`SymbolicPulse`](qiskit.pulse.library.SymbolicPulse "qiskit.pulse.library.SymbolicPulse") which will set values for the parameters and sample the parametric expression to create the [`Waveform`](qiskit.pulse.library.Waveform "qiskit.pulse.library.Waveform").
<span id="id1" />
### Pulse Models
| | |
| ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| [`Waveform`](qiskit.pulse.library.Waveform "qiskit.pulse.library.Waveform")(samples\[,Β name,Β epsilon,Β ...]) | A pulse specified completely by complex-valued samples; each sample is played for the duration of the backend cycle-time, dt. |
| [`SymbolicPulse`](qiskit.pulse.library.SymbolicPulse "qiskit.pulse.library.SymbolicPulse")(pulse\_type,Β duration\[,Β ...]) | The pulse representation model with parameters and symbolic expressions. |
<span id="symbolic-pulses" />
### Parametric Pulse Representation
| | |
| -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`Constant`](qiskit.pulse.library.Constant_class.rst#qiskit.pulse.library.Constant "qiskit.pulse.library.Constant")(duration,Β amp\[,Β angle,Β name,Β ...]) | A simple constant pulse, with an amplitude value and a duration: |
| [`Drag`](qiskit.pulse.library.Drag_class.rst#qiskit.pulse.library.Drag "qiskit.pulse.library.Drag")(duration,Β amp,Β sigma,Β beta\[,Β angle,Β ...]) | The Derivative Removal by Adiabatic Gate (DRAG) pulse is a standard Gaussian pulse with an additional Gaussian derivative component and lifting applied. |
| [`Gaussian`](qiskit.pulse.library.Gaussian_class.rst#qiskit.pulse.library.Gaussian "qiskit.pulse.library.Gaussian")(duration,Β amp,Β sigma\[,Β angle,Β ...]) | A lifted and truncated pulse envelope shaped according to the Gaussian function whose mean is centered at the center of the pulse (duration / 2): |
| [`GaussianSquare`](qiskit.pulse.library.GaussianSquare "qiskit.pulse.library.GaussianSquare")(duration,Β amp,Β sigma\[,Β ...]) | A square pulse with a Gaussian shaped risefall on both sides lifted such that its first sample is zero. |
| [`GaussianSquareDrag`](qiskit.pulse.library.GaussianSquareDrag "qiskit.pulse.library.GaussianSquareDrag")(duration,Β amp,Β sigma,Β beta) | A square pulse with a Drag shaped rise and fall |
| [`gaussian_square_echo`](qiskit.pulse.library.gaussian_square_echo "qiskit.pulse.library.gaussian_square_echo")(duration,Β amp,Β sigma\[,Β ...]) | An echoed Gaussian square pulse with an active tone overlaid on it. |
| [`GaussianDeriv`](qiskit.pulse.library.GaussianDeriv "qiskit.pulse.library.GaussianDeriv")(duration,Β amp,Β sigma\[,Β angle,Β ...]) | An unnormalized Gaussian derivative pulse. |
| [`Sin`](qiskit.pulse.library.Sin_class.rst#qiskit.pulse.library.Sin "qiskit.pulse.library.Sin")(duration,Β amp,Β phase\[,Β freq,Β angle,Β ...]) | A sinusoidal pulse. |
| [`Cos`](qiskit.pulse.library.Cos_class.rst#qiskit.pulse.library.Cos "qiskit.pulse.library.Cos")(duration,Β amp,Β phase\[,Β freq,Β angle,Β ...]) | A cosine pulse. |
| [`Sawtooth`](qiskit.pulse.library.Sawtooth_class.rst#qiskit.pulse.library.Sawtooth "qiskit.pulse.library.Sawtooth")(duration,Β amp,Β phase\[,Β freq,Β ...]) | A sawtooth pulse. |
| [`Triangle`](qiskit.pulse.library.Triangle_class.rst#qiskit.pulse.library.Triangle "qiskit.pulse.library.Triangle")(duration,Β amp,Β phase\[,Β freq,Β ...]) | A triangle wave pulse. |
| [`Square`](qiskit.pulse.library.Square_fun.rst#qiskit.pulse.library.Square "qiskit.pulse.library.Square")(duration,Β amp,Β phase\[,Β freq,Β angle,Β ...]) | A square wave pulse. |
| [`Sech`](qiskit.pulse.library.Sech_fun.rst#qiskit.pulse.library.Sech "qiskit.pulse.library.Sech")(duration,Β amp,Β sigma\[,Β angle,Β name,Β ...]) | An unnormalized sech pulse. |
| [`SechDeriv`](qiskit.pulse.library.SechDeriv "qiskit.pulse.library.SechDeriv")(duration,Β amp,Β sigma\[,Β angle,Β ...]) | An unnormalized sech derivative pulse. |
<span id="module-qiskit.pulse.channels" />
<span id="channels-qiskit-pulse-channels" />
<span id="pulse-channels" />
## Channels
<span id="module-qiskit.pulse" />
`qiskit.pulse.channels`
Pulse is meant to be agnostic to the underlying hardware implementation, while still allowing low-level control. Therefore, our signal channels are *virtual* hardware channels. The backend which executes our programs is responsible for mapping these virtual channels to the proper physical channel within the quantum control hardware.
Channels are characterized by their type and their index. Channels include:
* transmit channels, which should subclass `PulseChannel`
* receive channels, such as [`AcquireChannel`](qiskit.pulse.channels.AcquireChannel "qiskit.pulse.channels.AcquireChannel")
* non-signal βchannelsβ such as [`SnapshotChannel`](qiskit.pulse.channels.SnapshotChannel "qiskit.pulse.channels.SnapshotChannel"), [`MemorySlot`](qiskit.pulse.channels.MemorySlot "qiskit.pulse.channels.MemorySlot") and `RegisterChannel`.
Novel channel types can often utilize the [`ControlChannel`](qiskit.pulse.channels.ControlChannel "qiskit.pulse.channels.ControlChannel"), but if this is not sufficient, new channel types can be created. Then, they must be supported in the PulseQobj schema and the assembler. Channels are characterized by their type and their index. See each channel type below to learn more.
| | |
| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| [`DriveChannel`](qiskit.pulse.channels.DriveChannel "qiskit.pulse.channels.DriveChannel")(\*args,Β \*\*kwargs) | Drive channels transmit signals to qubits which enact gate operations. |
| [`MeasureChannel`](qiskit.pulse.channels.MeasureChannel "qiskit.pulse.channels.MeasureChannel")(\*args,Β \*\*kwargs) | Measure channels transmit measurement stimulus pulses for readout. |
| [`AcquireChannel`](qiskit.pulse.channels.AcquireChannel "qiskit.pulse.channels.AcquireChannel")(\*args,Β \*\*kwargs) | Acquire channels are used to collect data. |
| [`ControlChannel`](qiskit.pulse.channels.ControlChannel "qiskit.pulse.channels.ControlChannel")(\*args,Β \*\*kwargs) | Control channels provide supplementary control over the qubit to the drive channel. |
| [`RegisterSlot`](qiskit.pulse.channels.RegisterSlot "qiskit.pulse.channels.RegisterSlot")(\*args,Β \*\*kwargs) | Classical resister slot channels represent classical registers (low-latency classical memory). |
| [`MemorySlot`](qiskit.pulse.channels.MemorySlot "qiskit.pulse.channels.MemorySlot")(\*args,Β \*\*kwargs) | Memory slot channels represent classical memory storage. |
| [`SnapshotChannel`](qiskit.pulse.channels.SnapshotChannel "qiskit.pulse.channels.SnapshotChannel")(\*args,Β \*\*kwargs) | Snapshot channels are used to specify instructions for simulators. |
All channels are children of the same abstract base class:
### Channel
<Class id="qiskit.pulse.channels.Channel" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/channels.py#L63-L162" signature="qiskit.pulse.channels.Channel(*args, **kwargs)" modifiers="class">
Base class of channels. Channels provide a Qiskit-side label for typical quantum control hardware signal channels. The final label -> physical channel mapping is the responsibility of the hardware backend. For instance, `DriveChannel(0)` holds instructions which the backend should map to the signal line driving gate operations on the qubit labeled (indexed) 0.
When serialized channels are identified by their serialized name `<prefix><index>`. The type of the channel is interpreted from the prefix, and the index often (but not always) maps to the qubit index. All concrete channel classes must have a `prefix` class attribute (and instances of that class have an index attribute). Base classes which have `prefix` set to `None` are prevented from being instantiated.
To implement a new channel inherit from [`Channel`](#qiskit.pulse.channels.Channel "qiskit.pulse.channels.Channel") and provide a unique string identifier for the `prefix` class attribute.
Channel class.
**Parameters**
**index** β Index of channel.
</Class>
<span id="module-qiskit.pulse.schedule" />
## Schedules
Schedules are Pulse programs. They describe instruction sequences for the control hardware. The Schedule is one of the most fundamental objects to this pulse-level programming module. A `Schedule` is a representation of a *program* in Pulse. Each schedule tracks the time of each instruction occuring in parallel over multiple signal *channels*.
| | |
| -------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule")(\*schedules\[,Β name,Β metadata]) | A quantum program *schedule* with exact time constraints for its instructions, operating over all input signal *channels* and supporting special syntaxes for building. |
| [`ScheduleBlock`](qiskit.pulse.ScheduleBlock "qiskit.pulse.ScheduleBlock")(\[name,Β metadata,Β ...]) | Time-ordered sequence of instructions with alignment context. |
<span id="module-qiskit.pulse.transforms" />
<span id="pulse-transforms-qiskit-pulse-transforms" />
## Pulse Transforms
<span id="module-qiskit.pulse" />
`qiskit.pulse.transforms`
The pulse transforms provide transformation routines to reallocate and optimize pulse programs for backends.
<span id="pulse-alignments" />
### Alignments
The alignment transforms define alignment policies of instructions in [`ScheduleBlock`](qiskit.pulse.ScheduleBlock "qiskit.pulse.ScheduleBlock"). These transformations are called to create [`Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule")s from [`ScheduleBlock`](qiskit.pulse.ScheduleBlock "qiskit.pulse.ScheduleBlock")s.
| | |
| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| [`AlignEquispaced`](qiskit.pulse.transforms.AlignEquispaced "qiskit.pulse.transforms.AlignEquispaced")(duration) | Align instructions with equispaced interval within a specified duration. |
| [`AlignFunc`](qiskit.pulse.transforms.AlignFunc "qiskit.pulse.transforms.AlignFunc")(duration,Β func) | Allocate instructions at position specified by callback function. |
| [`AlignLeft`](qiskit.pulse.transforms.AlignLeft "qiskit.pulse.transforms.AlignLeft")() | Align instructions in as-soon-as-possible manner. |
| [`AlignRight`](qiskit.pulse.transforms.AlignRight "qiskit.pulse.transforms.AlignRight")() | Align instructions in as-late-as-possible manner. |
| [`AlignSequential`](qiskit.pulse.transforms.AlignSequential "qiskit.pulse.transforms.AlignSequential")() | Align instructions sequentially. |
These are all subtypes of the abstract base class [`AlignmentKind`](#qiskit.pulse.transforms.AlignmentKind "qiskit.pulse.transforms.AlignmentKind").
#### AlignmentKind
<Class id="qiskit.pulse.transforms.AlignmentKind" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/alignments.py#L25-L87" signature="qiskit.pulse.transforms.AlignmentKind(context_params)" modifiers="class">
An abstract class for schedule alignment.
Create new context.
</Class>
<span id="pulse-canonical-transform" />
### Canonicalization
The canonicalization transforms convert schedules to a form amenable for execution on OpenPulse backends.
#### add\_implicit\_acquires
<Function id="qiskit.pulse.transforms.add_implicit_acquires" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/canonicalization.py#L384-L433" signature="qiskit.pulse.transforms.add_implicit_acquires(schedule, meas_map)">
Return a new schedule with implicit acquires from the measurement mapping replaced by explicit ones.
<Admonition title="Warning" type="caution">
Since new acquires are being added, Memory Slots will be set to match the qubit index. This may overwrite your specification.
</Admonition>
**Parameters**
* **schedule** ([*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule") *|*[*Instruction*](#qiskit.pulse.instructions.Instruction "qiskit.pulse.instructions.instruction.Instruction")) β Schedule to be aligned.
* **meas\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]]*) β List of lists of qubits that are measured together.
**Returns**
A `Schedule` with the additional acquisition instructions.
**Return type**
[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")
</Function>
#### align\_measures
<Function id="qiskit.pulse.transforms.align_measures" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/canonicalization.py#L227-L381" signature="qiskit.pulse.transforms.align_measures(schedules, inst_map=None, cal_gate='u3', max_calibration_duration=None, align_time=None, align_all=True)">
Return new schedules where measurements occur at the same physical time.
This transformation will align the first [`Acquire`](qiskit.pulse.instructions.Acquire "qiskit.pulse.instructions.Acquire") on every channel to occur at the same time.
Minimum measurement wait time (to allow for calibration pulses) is enforced and may be set with `max_calibration_duration`.
By default only instructions containing a [`AcquireChannel`](qiskit.pulse.channels.AcquireChannel "qiskit.pulse.channels.AcquireChannel") or [`MeasureChannel`](qiskit.pulse.channels.MeasureChannel "qiskit.pulse.channels.MeasureChannel") will be shifted. If you wish to keep the relative timing of all instructions in the schedule set `align_all=True`.
This method assumes that `MeasureChannel(i)` and `AcquireChannel(i)` correspond to the same qubit and the acquire/play instructions should be shifted together on these channels.
```python
from qiskit import pulse
from qiskit.pulse import transforms
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
a0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
sched = pulse.Schedule()
sched.append(pulse.Play(pulse.Constant(10, 0.5), d0), inplace=True)
sched.append(pulse.Play(pulse.Constant(10, 1.), m0).shift(sched.duration), inplace=True)
sched.append(pulse.Acquire(20, a0, mem0).shift(sched.duration), inplace=True)
sched_shifted = sched << 20
aligned_sched, aligned_sched_shifted = transforms.align_measures([sched, sched_shifted])
assert aligned_sched == aligned_sched_shifted
```
If it is desired to only shift acquisition and measurement stimulus instructions set the flag `align_all=False`:
```python
aligned_sched, aligned_sched_shifted = transforms.align_measures(
[sched, sched_shifted],
align_all=False,
)
assert aligned_sched != aligned_sched_shifted
```
**Parameters**
* **schedules** (*Iterable\[ScheduleComponent]*) β Collection of schedules to be aligned together
* **inst\_map** ([*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap "qiskit.pulse.InstructionScheduleMap") *| None*) β Mapping of circuit operations to pulse schedules
* **cal\_gate** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The name of the gate to inspect for the calibration time
* **max\_calibration\_duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β If provided, inst\_map and cal\_gate will be ignored
* **align\_time** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β If provided, this will be used as final align time.
* **align\_all** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)") *| None*) β Shift all instructions in the schedule such that they maintain their relative alignment with the shifted acquisition instruction. If `False` only the acquisition and measurement pulse instructions will be shifted.
**Returns**
The input list of schedules transformed to have their measurements aligned.
**Raises**
[**PulseError**](#qiskit.pulse.PulseError "qiskit.pulse.PulseError") β If the provided alignment time is negative.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")\[[Schedule](qiskit.pulse.Schedule "qiskit.pulse.Schedule")]
</Function>
#### block\_to\_schedule
<Function id="qiskit.pulse.transforms.block_to_schedule" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/canonicalization.py#L34-L82" signature="qiskit.pulse.transforms.block_to_schedule(block)">
Convert `ScheduleBlock` to `Schedule`.
**Parameters**
**block** ([*ScheduleBlock*](qiskit.pulse.ScheduleBlock "qiskit.pulse.schedule.ScheduleBlock")) β A `ScheduleBlock` to convert.
**Returns**
Scheduled pulse program.
**Raises**
* [**UnassignedDurationError**](#qiskit.pulse.UnassignedDurationError "qiskit.pulse.UnassignedDurationError") β When any instruction duration is not assigned.
* [**PulseError**](#qiskit.pulse.PulseError "qiskit.pulse.PulseError") β When the alignment context duration is shorter than the schedule duration.
**Return type**
[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")
<Admonition title="Note" type="note">
This transform may insert barriers in between contexts.
</Admonition>
</Function>
#### compress\_pulses
<Function id="qiskit.pulse.transforms.compress_pulses" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/canonicalization.py#L85-L118" signature="qiskit.pulse.transforms.compress_pulses(schedules)">
Optimization pass to replace identical pulses.
**Parameters**
**schedules** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*qiskit.pulse.schedule.Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")*]*) β Schedules to compress.
**Returns**
Compressed schedules.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")\[[qiskit.pulse.schedule.Schedule](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")]
</Function>
#### flatten
<Function id="qiskit.pulse.transforms.flatten" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/canonicalization.py#L121-L139" signature="qiskit.pulse.transforms.flatten(program)">
Flatten (inline) any called nodes into a Schedule tree with no nested children.
**Parameters**
**program** ([*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")) β Pulse program to remove nested structure.
**Returns**
Flatten pulse program.
**Raises**
[**PulseError**](#qiskit.pulse.PulseError "qiskit.pulse.PulseError") β When invalid data format is given.
**Return type**
[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")
</Function>
#### inline\_subroutines
<Function id="qiskit.pulse.transforms.inline_subroutines" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/canonicalization.py#L142-L162" signature="qiskit.pulse.transforms.inline_subroutines(program)">
Recursively remove call instructions and inline the respective subroutine instructions.
Assigned parameter values, which are stored in the parameter table, are also applied. The subroutine is copied before the parameter assignment to avoid mutation problem.
**Parameters**
**program** ([*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.Schedule") *|*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock "qiskit.pulse.ScheduleBlock")) β A program which may contain the subroutine, i.e. `Call` instruction.
**Returns**
A schedule without subroutine.
**Raises**
[**PulseError**](#qiskit.pulse.PulseError "qiskit.pulse.PulseError") β When input program is not valid data format.
**Return type**
[Schedule](qiskit.pulse.Schedule "qiskit.pulse.Schedule") | [ScheduleBlock](qiskit.pulse.ScheduleBlock "qiskit.pulse.ScheduleBlock")
</Function>
#### pad
<Function id="qiskit.pulse.transforms.pad" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/canonicalization.py#L436-L498" signature="qiskit.pulse.transforms.pad(schedule, channels=None, until=None, inplace=False, pad_with=None)">
Pad the input Schedule with `Delay``s on all unoccupied timeslots until ``schedule.duration` or `until` if not `None`.
**Parameters**
* **schedule** ([*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.Schedule")) β Schedule to pad.
* **channels** (*Iterable\[chans.Channel] | None*) β Channels to pad. Defaults to all channels in `schedule` if not provided. If the supplied channel is not a member of `schedule` it will be added.
* **until** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β Time to pad until. Defaults to `schedule.duration` if not provided.
* **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Pad this schedule by mutating rather than returning a new schedule.
* **pad\_with** ([*Type*](circuit_classical#qiskit.circuit.classical.types.Type "qiskit.circuit.classical.types.Type")*\[*[*instructions.Instruction*](#qiskit.pulse.instructions.Instruction "qiskit.pulse.instructions.Instruction")*] | None*) β Pulse `Instruction` subclass to be used for padding. Default to [`Delay`](qiskit.pulse.instructions.Delay "qiskit.pulse.instructions.Delay") instruction.
**Returns**
The padded schedule.
**Raises**
[**PulseError**](#qiskit.pulse.PulseError "qiskit.pulse.PulseError") β When non pulse instruction is set to pad\_with.
**Return type**
[Schedule](qiskit.pulse.Schedule "qiskit.pulse.Schedule")
</Function>
#### remove\_directives
<Function id="qiskit.pulse.transforms.remove_directives" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/canonicalization.py#L199-L208" signature="qiskit.pulse.transforms.remove_directives(schedule)">
Remove directives.
**Parameters**
**schedule** ([*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")) β A schedule to remove compiler directives.
**Returns**
A schedule without directives.
**Return type**
[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")
</Function>
#### remove\_trivial\_barriers
<Function id="qiskit.pulse.transforms.remove_trivial_barriers" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/canonicalization.py#L211-L224" signature="qiskit.pulse.transforms.remove_trivial_barriers(schedule)">
Remove trivial barriers with 0 or 1 channels.
**Parameters**
**schedule** ([*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")) β A schedule to remove trivial barriers.
**Returns**
A schedule without trivial barriers
**Return type**
schedule
</Function>
<span id="pulse-dag" />
### DAG
The DAG transforms create DAG representation of input program. This can be used for optimization of instructions and equality checks.
#### block\_to\_dag
<Function id="qiskit.pulse.transforms.block_to_dag" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/dag.py#L27-L75" signature="qiskit.pulse.transforms.block_to_dag(block)">
Convert schedule block instruction into DAG.
`ScheduleBlock` can be represented as a DAG as needed. For example, equality of two programs are efficiently checked on DAG representation.
```python
with pulse.build() as sched1:
with pulse.align_left():
pulse.play(my_gaussian0, pulse.DriveChannel(0))
pulse.shift_phase(1.57, pulse.DriveChannel(2))
pulse.play(my_gaussian1, pulse.DriveChannel(1))
with pulse.build() as sched2:
with pulse.align_left():
pulse.shift_phase(1.57, pulse.DriveChannel(2))
pulse.play(my_gaussian1, pulse.DriveChannel(1))
pulse.play(my_gaussian0, pulse.DriveChannel(0))
```
Here the `sched1 `` and ``sched2` are different implementations of the same program, but it is difficult to confirm on the list representation.
Another example is instruction optimization.
```python
with pulse.build() as sched:
with pulse.align_left():
pulse.shift_phase(1.57, pulse.DriveChannel(1))
pulse.play(my_gaussian0, pulse.DriveChannel(0))
pulse.shift_phase(-1.57, pulse.DriveChannel(1))
```
In above program two `shift_phase` instructions can be cancelled out because they are consecutive on the same drive channel. This can be easily found on the DAG representation.
**Parameters**
**block** (*"ScheduleBlock"*) β A schedule block to be converted.
**Returns**
Instructions in DAG representation.
**Raises**
[**PulseError**](#qiskit.pulse.PulseError "qiskit.pulse.PulseError") β When the context is invalid subclass.
**Return type**
rx.PyDAG
</Function>
<span id="pulse-transform-chain" />
### Composite transform
A sequence of transformations to generate a target code.
#### target\_qobj\_transform
<Function id="qiskit.pulse.transforms.target_qobj_transform" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/transforms/base_transforms.py#L25-L55" signature="qiskit.pulse.transforms.target_qobj_transform(sched, remove_directives=True)">
A basic pulse program transformation for OpenPulse API execution.
**Parameters**
* **sched** ([*ScheduleBlock*](qiskit.pulse.ScheduleBlock "qiskit.pulse.schedule.ScheduleBlock") *|*[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule") *|*[*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)")*,* [*Instruction*](#qiskit.pulse.instructions.Instruction "qiskit.pulse.instructions.instruction.Instruction")*] |* [*Instruction*](#qiskit.pulse.instructions.Instruction "qiskit.pulse.instructions.instruction.Instruction") *|*[*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*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)")*,* [*Instruction*](#qiskit.pulse.instructions.Instruction "qiskit.pulse.instructions.instruction.Instruction")*] |* [*Instruction*](#qiskit.pulse.instructions.Instruction "qiskit.pulse.instructions.instruction.Instruction")*]*) β Input program to transform.
* **remove\_directives** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Set True to remove compiler directives.
**Returns**
Transformed program for execution.
**Return type**
[*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.schedule.Schedule")
</Function>
<span id="module-qiskit.pulse.builder" />
<span id="id2" />
## Pulse Builder
Use the pulse builder DSL to write pulse programs with an imperative syntax.
<Admonition title="Warning" type="caution">
The pulse builder interface is still in active development. It may have breaking API changes without deprecation warnings in future releases until otherwise indicated.
</Admonition>
The pulse builder provides an imperative API for writing pulse programs with less difficulty than the [`Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule") API. It contextually constructs a pulse schedule and then emits the schedule for execution. For example, to play a series of pulses on channels is as simple as:
```python
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
```

To begin pulse programming we must first initialize our program builder context with [`build()`](#qiskit.pulse.builder.build "qiskit.pulse.builder.build"), after which we can begin adding program statements. For example, below we write a simple program that [`play()`](#qiskit.pulse.builder.play "qiskit.pulse.builder.play")s a pulse:
```python
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
```

The builder initializes a [`pulse.Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule"), `pulse_prog` and then begins to construct the program within the context. The output pulse schedule will survive after the context is exited and can be transpiled and executed like a normal Qiskit schedule using `backend.run(transpile(pulse_prog, backend))`.
Pulse programming has a simple imperative style. This leaves the programmer to worry about the raw experimental physics of pulse programming and not constructing cumbersome data structures.
We can optionally pass a [`Backend`](qiskit.providers.Backend "qiskit.providers.Backend") to [`build()`](#qiskit.pulse.builder.build "qiskit.pulse.builder.build") to enable enhanced functionality. Below, we prepare a Bell state by automatically compiling the required pulses from their gate-level representations, while simultaneously applying a long decoupling pulse to a neighboring qubit. We terminate the experiment with a measurement to observe the state we prepared. This program which mixes circuits and pulses will be automatically lowered to be run as a pulse program:
```python
from math import pi
from qiskit.compiler import schedule
from qiskit.circuit import QuantumCircuit
from qiskit import pulse
from qiskit.providers.fake_provider import GenericBackendV2
backend = GenericBackendV2(num_qubits=5, calibrate_instructions=True)
d2 = pulse.DriveChannel(2)
qc = QuantumCircuit(2)
# Hadamard
qc.rz(pi/2, 0)
qc.sx(0)
qc.rz(pi/2, 0)
qc.cx(0, 1)
bell_sched = schedule(qc, backend)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_sched)
pulse.play(pulse.Constant(bell_sched.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
```

With the pulse builder we are able to blend programming on qubits and channels. While the pulse schedule is based on instructions that operate on channels, the pulse builder automatically handles the mapping from qubits to channels for you.
In the example below we demonstrate some more features of the pulse builder:
```python
import math
from qiskit.compiler import schedule
from qiskit import pulse, QuantumCircuit
from qiskit.pulse import library
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
qc = QuantumCircuit(2, 2)
qc.cx(0, 1)
with pulse.build(backend) as pulse_prog:
# Create a pulse.
gaussian_pulse = library.gaussian(10, 1.0, 2)
# Get the qubit's corresponding drive channel from the backend.
d0 = pulse.drive_channel(0)
d1 = pulse.drive_channel(1)
# Play a pulse at t=0.
pulse.play(gaussian_pulse, d0)
# Play another pulse directly after the previous pulse at t=10.
pulse.play(gaussian_pulse, d0)
# The default scheduling behavior is to schedule pulses in parallel
# across channels. For example, the statement below
# plays the same pulse on a different channel at t=0.
pulse.play(gaussian_pulse, d1)
# We also provide pulse scheduling alignment contexts.
# The default alignment context is align_left.
# The sequential context schedules pulse instructions sequentially in time.
# This context starts at t=10 due to earlier pulses above.
with pulse.align_sequential():
pulse.play(gaussian_pulse, d0)
# Play another pulse after at t=20.
pulse.play(gaussian_pulse, d1)
# We can also nest contexts as each instruction is
# contained in its local scheduling context.
# The output of a child context is a context-schedule
# with the internal instructions timing fixed relative to
# one another. This is schedule is then called in the parent context.
# Context starts at t=30.
with pulse.align_left():
# Start at t=30.
pulse.play(gaussian_pulse, d0)
# Start at t=30.
pulse.play(gaussian_pulse, d1)
# Context ends at t=40.
# Alignment context where all pulse instructions are
# aligned to the right, ie., as late as possible.
with pulse.align_right():
# Shift the phase of a pulse channel.
pulse.shift_phase(math.pi, d1)
# Starts at t=40.
pulse.delay(100, d0)
# Ends at t=140.
# Starts at t=130.
pulse.play(gaussian_pulse, d1)
# Ends at t=140.
# Acquire data for a qubit and store in a memory slot.
pulse.acquire(100, 0, pulse.MemorySlot(0))
# We also support a variety of macros for common operations.
# Measure all qubits.
pulse.measure_all()
# Delay on some qubits.
# This requires knowledge of which channels belong to which qubits.
# delay for 100 cycles on qubits 0 and 1.
pulse.delay_qubits(100, 0, 1)
# Call a schedule for a quantum circuit thereby inserting into
# the pulse schedule.
qc = QuantumCircuit(2, 2)
qc.cx(0, 1)
qc_sched = schedule(qc, backend)
pulse.call(qc_sched)
# It is also be possible to call a preexisting schedule
tmp_sched = pulse.Schedule()
tmp_sched += pulse.Play(gaussian_pulse, d0)
pulse.call(tmp_sched)
# We also support:
# frequency instructions
pulse.set_frequency(5.0e9, d0)
# phase instructions
pulse.shift_phase(0.1, d0)
# offset contexts
with pulse.phase_offset(math.pi, d0):
pulse.play(gaussian_pulse, d0)
```
The above is just a small taste of what is possible with the builder. See the rest of the module documentation for more information on its capabilities.
### build
<Function id="qiskit.pulse.builder.build" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L774-L821" signature="qiskit.pulse.builder.build(backend=None, schedule=None, name=None, default_alignment='left')">
Create a context manager for launching the imperative pulse builder DSL.
To enter a building context and starting building a pulse program:
```python
from qiskit import transpile, pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 0.5), d0)
```
While the output program `pulse_prog` cannot be executed as we are using a mock backend. If a real backend is being used, executing the program is done with:
```python
backend.run(transpile(pulse_prog, backend))
```
**Parameters**
* **backend** ([*Backend*](qiskit.providers.Backend "qiskit.providers.Backend")) β A Qiskit backend. If not supplied certain builder functionality will be unavailable.
* **schedule** ([*ScheduleBlock*](qiskit.pulse.ScheduleBlock "qiskit.pulse.ScheduleBlock") *| None*) β A pulse `ScheduleBlock` in which your pulse program will be built.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name of pulse program to be built.
* **default\_alignment** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*AlignmentKind*](#qiskit.pulse.transforms.AlignmentKind "qiskit.pulse.transforms.AlignmentKind") *| None*) β Default scheduling alignment for builder. One of `left`, `right`, `sequential` or an alignment context.
**Returns**
A new builder context which has the active builder initialized.
**Return type**
ContextManager\[[ScheduleBlock](qiskit.pulse.ScheduleBlock "qiskit.pulse.ScheduleBlock")]
</Function>
### Channels
Methods to return the correct channels for the respective qubit indices.
```python
from qiskit import pulse
from qiskit.providers.fake_provider import GenericBackendV2
backend = GenericBackendV2(num_qubits=2, calibrate_instructions=True)
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
print(d0)
```
```python
DriveChannel(0)
```
#### acquire\_channel
<Function id="qiskit.pulse.builder.acquire_channel" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1425-L1445" signature="qiskit.pulse.builder.acquire_channel(qubit)">
Return `AcquireChannel` for `qubit` on the active builder backend.
Examples:
```python
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.acquire_channel(0) == pulse.AcquireChannel(0)
```
<Admonition title="Note" type="note">
Requires the active builder context to have a backend set.
</Admonition>
**Return type**
[*AcquireChannel*](qiskit.pulse.channels.AcquireChannel "qiskit.pulse.channels.AcquireChannel")
</Function>
#### control\_channels
<Function id="qiskit.pulse.builder.control_channels" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1448-L1478" signature="qiskit.pulse.builder.control_channels(*qubits)">
Return `ControlChannel` for `qubit` on the active builder backend.
Return the secondary drive channel for the given qubit β typically utilized for controlling multi-qubit interactions.
Examples:
```python
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)]
```
<Admonition title="Note" type="note">
Requires the active builder context to have a backend set.
</Admonition>
**Parameters**
**qubits** ([*Iterable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]*) β Tuple or list of ordered qubits of the form (control\_qubit, target\_qubit).
**Returns**
List of control channels associated with the supplied ordered list of qubits.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")\[[qiskit.pulse.channels.ControlChannel](qiskit.pulse.channels.ControlChannel "qiskit.pulse.channels.ControlChannel")]
</Function>
#### drive\_channel
<Function id="qiskit.pulse.builder.drive_channel" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1379-L1399" signature="qiskit.pulse.builder.drive_channel(qubit)">
Return `DriveChannel` for `qubit` on the active builder backend.
Examples:
```python
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.drive_channel(0) == pulse.DriveChannel(0)
```
<Admonition title="Note" type="note">
Requires the active builder context to have a backend set.
</Admonition>
**Return type**
[*DriveChannel*](qiskit.pulse.channels.DriveChannel "qiskit.pulse.channels.DriveChannel")
</Function>
#### measure\_channel
<Function id="qiskit.pulse.builder.measure_channel" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1402-L1422" signature="qiskit.pulse.builder.measure_channel(qubit)">
Return `MeasureChannel` for `qubit` on the active builder backend.
Examples:
```python
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.measure_channel(0) == pulse.MeasureChannel(0)
```
<Admonition title="Note" type="note">
Requires the active builder context to have a backend set.
</Admonition>
**Return type**
[*MeasureChannel*](qiskit.pulse.channels.MeasureChannel "qiskit.pulse.channels.MeasureChannel")
</Function>
### Instructions
Pulse instructions are available within the builder interface. Hereβs an example:
```python
from qiskit import pulse
from qiskit.providers.fake_provider import GenericBackendV2
backend = GenericBackendV2(num_qubits=2, calibrate_instructions=True)
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
drive_sched.draw()
```

#### acquire
<Function id="qiskit.pulse.builder.acquire" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1537-L1587" signature="qiskit.pulse.builder.acquire(duration, qubit_or_channel, register, **metadata)">
Acquire for a `duration` on a `channel` and store the result in a `register`.
Examples:
```python
from qiskit import pulse
acq0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
with pulse.build() as pulse_prog:
pulse.acquire(100, acq0, mem0)
# measurement metadata
kernel = pulse.configuration.Kernel('linear_discriminator')
pulse.acquire(100, acq0, mem0, kernel=kernel)
```
<Admonition title="Note" type="note">
The type of data acquire will depend on the execution `meas_level`.
</Admonition>
**Parameters**
* **duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Duration to acquire data for
* **qubit\_or\_channel** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| chans.AcquireChannel*) β Either the qubit to acquire data for or the specific [`AcquireChannel`](qiskit.pulse.channels.AcquireChannel "qiskit.pulse.channels.AcquireChannel") to acquire on.
* **register** (*StorageLocation*) β Location to store measured result.
* **metadata** (*Unpack\[\_MetaDataType]*) β Additional metadata for measurement. See [`Acquire`](qiskit.pulse.instructions.Acquire "qiskit.pulse.instructions.Acquire") for more information.
**Raises**
[**exceptions.PulseError**](#qiskit.pulse.PulseError "qiskit.pulse.exceptions.PulseError") β If the register type is not supported.
</Function>
#### barrier
<Function id="qiskit.pulse.builder.barrier" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1923-L1992" signature="qiskit.pulse.builder.barrier(*channels_or_qubits, name=None)">
Barrier directive for a set of channels and qubits.
This directive prevents the compiler from moving instructions across the barrier. Consider the case where we want to enforce that one pulse happens after another on separate channels, this can be done with:
```python
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(backend) as barrier_pulse_prog:
pulse.play(pulse.Constant(10, 1.0), d0)
pulse.barrier(d0, d1)
pulse.play(pulse.Constant(10, 1.0), d1)
```
Of course this could have been accomplished with:
```python
from qiskit.pulse import transforms
with pulse.build(backend) as aligned_pulse_prog:
with pulse.align_sequential():
pulse.play(pulse.Constant(10, 1.0), d0)
pulse.play(pulse.Constant(10, 1.0), d1)
barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog)
aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog)
assert barrier_pulse_prog == aligned_pulse_prog
```
The barrier allows the pulse compiler to take care of more advanced scheduling alignment operations across channels. For example in the case where we are calling an outside circuit or schedule and want to align a pulse at the end of one call:
```python
import math
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
with pulse.align_right():
pulse.call(backend.defaults.instruction_schedule_map.get('x', (1,)))
# Barrier qubit 1 and d0.
pulse.barrier(1, d0)
# Due to barrier this will play before the gate on qubit 1.
pulse.play(pulse.Constant(10, 1.0), d0)
# This will end at the same time as the pulse above due to
# the barrier.
pulse.call(backend.defaults.instruction_schedule_map.get('x', (1,)))
```
<Admonition title="Note" type="note">
Requires the active builder context to have a backend set if qubits are barriered on.
</Admonition>
**Parameters**
* **channels\_or\_qubits** (*chans.Channel |* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Channels or qubits to barrier.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name for the barrier
</Function>
#### call
<Function id="qiskit.pulse.builder.call" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1703-L1894" signature="qiskit.pulse.builder.call(target, name=None, value_dict=None, **kw_params)">
Call the subroutine within the currently active builder context with arbitrary parameters which will be assigned to the target program.
<Admonition title="Note" type="note">
If the `target` program is a [`ScheduleBlock`](qiskit.pulse.ScheduleBlock "qiskit.pulse.ScheduleBlock"), then a [`Reference`](qiskit.pulse.instructions.Reference "qiskit.pulse.instructions.Reference") instruction will be created and appended to the current context. The `target` program will be immediately assigned to the current scope as a subroutine. If the `target` program is [`Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule"), it will be wrapped by the `Call` instruction and appended to the current context to avoid a mixed representation of [`ScheduleBlock`](qiskit.pulse.ScheduleBlock "qiskit.pulse.ScheduleBlock") and [`Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule"). If the `target` program is a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") it will be scheduled and the new [`Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule") will be added as a `Call` instruction.
</Admonition>
**Examples**
1. Calling a schedule block (recommended)
```python
from qiskit import circuit, pulse
from qiskit.providers.fake_provider import GenericBackendV2
backend = GenericBackendV2(num_qubits=5, calibrate_instructions=True)
with pulse.build() as x_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
with pulse.build() as pulse_prog:
pulse.call(x_sched)
print(pulse_prog)
```
```python
ScheduleBlock(
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.1+0j), sigma=40),
DriveChannel(0)
),
name="block0",
transform=AlignLeft()
),
name="block1",
transform=AlignLeft()
)
```
The actual program is stored in the reference table attached to the schedule.
```python
print(pulse_prog.references)
```
```python
ReferenceManager:
- ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(...
```
In addition, you can call a parameterized target program with parameter assignment.
```python
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with pulse.build() as pulse_prog:
pulse.call(subroutine, amp=0.1)
pulse.call(subroutine, amp=0.3)
print(pulse_prog)
```
```python
ScheduleBlock(
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.1+0j), sigma=40),
DriveChannel(0)
),
name="block2",
transform=AlignLeft()
),
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.3+0j), sigma=40),
DriveChannel(0)
),
name="block2",
transform=AlignLeft()
),
name="block3",
transform=AlignLeft()
)
```
If there is a name collision between parameters, you can distinguish them by specifying each parameter object in a python dictionary. For example,
```python
amp1 = circuit.Parameter('amp')
amp2 = circuit.Parameter('amp')
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1))
with pulse.build() as pulse_prog:
pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3})
print(pulse_prog)
```
```python
ScheduleBlock(
ScheduleBlock(
Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)),
Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)),
name="block4",
transform=AlignLeft()
),
name="block5",
transform=AlignLeft()
)
```
2. Calling a schedule
```python
x_sched = backend.instruction_schedule_map.get("x", (0,))
with pulse.build(backend) as pulse_prog:
pulse.call(x_sched)
print(pulse_prog)
```
```python
ScheduleBlock(
Call(
Schedule(
(
0,
Play(
Drag(
duration=160,
amp=(0.18989731546729305+0j),
sigma=40,
beta=-1.201258305015517,
name='drag_86a8'
),
DriveChannel(0),
name='drag_86a8'
)
),
name="x"
),
name='x'
),
name="block6",
transform=AlignLeft()
)
```
Currently, the backend calibrated gates are provided in the form of [`Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule"). The parameter assignment mechanism is available also for schedules. However, the called schedule is not treated as a reference.
**Parameters**
* **target** ([*Schedule*](qiskit.pulse.Schedule "qiskit.pulse.Schedule") *|*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock "qiskit.pulse.ScheduleBlock") *| None*) β Target circuit or pulse schedule to call.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Optional. A unique name of subroutine if defined. When the name is explicitly provided, one cannot call different schedule blocks with the same name.
* **value\_dict** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)")*\[ParameterValueType, ParameterValueType] | None*) β Optional. Parameters assigned to the `target` program. If this dictionary is provided, the `target` program is copied and then stored in the main built schedule and its parameters are assigned to the given values. This dictionary is keyed on [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects, allowing parameter name collision to be avoided.
* **kw\_params** (*ParameterValueType*) β Alternative way to provide parameters. Since this is keyed on the string parameter name, the parameters having the same name are all updated together. If you want to avoid name collision, use `value_dict` with [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects instead.
</Function>
#### delay
<Function id="qiskit.pulse.builder.delay" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1482-L1501" signature="qiskit.pulse.builder.delay(duration, channel, name=None)">
Delay on a `channel` for a `duration`.
Examples:
```python
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.delay(10, d0)
```
**Parameters**
* **duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of cycles to delay for on `channel`.
* **channel** (*chans.Channel*) β Channel to delay on.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name of the instruction.
</Function>
#### play
<Function id="qiskit.pulse.builder.play" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1504-L1526" signature="qiskit.pulse.builder.play(pulse, channel, name=None)">
Play a `pulse` on a `channel`.
Examples:
```python
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(10, 1.0), d0)
```
**Parameters**
* **pulse** (*library.Pulse | np.ndarray*) β Pulse to play.
* **channel** (*chans.PulseChannel*) β Channel to play pulse on.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name of the pulse.
</Function>
#### reference
<Function id="qiskit.pulse.builder.reference" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1897-L1919" signature="qiskit.pulse.builder.reference(name, *extra_keys)">
Refer to undefined subroutine by string keys.
A [`Reference`](qiskit.pulse.instructions.Reference "qiskit.pulse.instructions.Reference") instruction is implicitly created and a schedule can be separately registered to the reference at a later stage.
```python
from qiskit import pulse
with pulse.build() as main_prog:
pulse.reference("x_gate", "q0")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
main_prog.assign_references(subroutine_dict={("x_gate", "q0"): subroutine})
```
**Parameters**
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Name of subroutine.
* **extra\_keys** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Helper keys to uniquely specify the subroutine.
</Function>
#### set\_frequency
<Function id="qiskit.pulse.builder.set_frequency" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1590-L1609" signature="qiskit.pulse.builder.set_frequency(frequency, channel, name=None)">
Set the `frequency` of a pulse `channel`.
Examples:
```python
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.set_frequency(1e9, d0)
```
**Parameters**
* **frequency** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Frequency in Hz to set channel to.
* **channel** (*chans.PulseChannel*) β Channel to set frequency of.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name of the instruction.
</Function>
#### set\_phase
<Function id="qiskit.pulse.builder.set_phase" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1635-L1657" signature="qiskit.pulse.builder.set_phase(phase, channel, name=None)">
Set the `phase` of a pulse `channel`.
Examples:
```python
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.set_phase(math.pi, d0)
```
**Parameters**
* **phase** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Phase in radians to set channel carrier signal to.
* **channel** (*chans.PulseChannel*) β Channel to set phase of.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name of the instruction.
</Function>
#### shift\_frequency
<Function id="qiskit.pulse.builder.shift_frequency" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1612-L1632" signature="qiskit.pulse.builder.shift_frequency(frequency, channel, name=None)">
Shift the `frequency` of a pulse `channel`.
Examples:
```python
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.shift_frequency(1e9, d0)
```
**Parameters**
* **frequency** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Frequency in Hz to shift channel frequency by.
* **channel** (*chans.PulseChannel*) β Channel to shift frequency of.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name of the instruction.
</Function>
#### shift\_phase
<Function id="qiskit.pulse.builder.shift_phase" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1660-L1681" signature="qiskit.pulse.builder.shift_phase(phase, channel, name=None)">
Shift the `phase` of a pulse `channel`.
Examples:
```python
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.shift_phase(math.pi, d0)
```
**Parameters**
* **phase** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Phase in radians to shift channel carrier signal by.
* **channel** (*chans.PulseChannel*) β Channel to shift phase of.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Name of the instruction.
</Function>
#### snapshot
<Function id="qiskit.pulse.builder.snapshot" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L1684-L1700" signature="qiskit.pulse.builder.snapshot(label, snapshot_type='statevector')">
Simulator snapshot.
Examples:
```python
from qiskit import pulse
with pulse.build() as pulse_prog:
pulse.snapshot('first', 'statevector')
```
**Parameters**
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Label for snapshot.
* **snapshot\_type** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Type of snapshot.
</Function>
### Contexts
Builder aware contexts that modify the construction of a pulse program. For example an alignment context like [`align_right()`](#qiskit.pulse.builder.align_right "qiskit.pulse.builder.align_right") may be used to align all pulses as late as possible in a pulse program.
```python
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog.draw()
```

#### align\_equispaced
<Function id="qiskit.pulse.builder.align_equispaced" signature="qiskit.pulse.builder.align_equispaced(duration)">
Equispaced alignment pulse scheduling context.
Pulse instructions within this context are scheduled with the same interval spacing such that the total length of the context block is `duration`. If the total free `duration` cannot be evenly divided by the number of instructions within the context, the modulo is split and then prepended and appended to the returned schedule. Delay instructions are automatically inserted in between pulses.
This context is convenient to write a schedule for periodical dynamic decoupling or the Hahn echo sequence.
Examples:
```python
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
with pulse.build() as hahn_echo:
with pulse.align_equispaced(duration=100):
pulse.play(x90, d0)
pulse.play(x180, d0)
pulse.play(x90, d0)
hahn_echo.draw()
```

**Parameters**
**duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")) β Duration of this context. This should be larger than the schedule duration.
**Yields**
None
**Return type**
Generator\[None, None, None]
**Notes**
The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the equispaced context for each channel, you should use the context independently for channels.
</Function>
#### align\_func
<Function id="qiskit.pulse.builder.align_func" signature="qiskit.pulse.builder.align_func(duration, func)">
Callback defined alignment pulse scheduling context.
Pulse instructions within this context are scheduled at the location specified by arbitrary callback function position that takes integer index and returns the associated fractional location within \[0, 1]. Delay instruction is automatically inserted in between pulses.
This context may be convenient to write a schedule of arbitrary dynamical decoupling sequences such as Uhrig dynamical decoupling.
Examples:
```python
import numpy as np
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
def udd10_pos(j):
return np.sin(np.pi*j/(2*10 + 2))**2
with pulse.build() as udd_sched:
pulse.play(x90, d0)
with pulse.align_func(duration=300, func=udd10_pos):
for _ in range(10):
pulse.play(x180, d0)
pulse.play(x90, d0)
udd_sched.draw()
```

**Parameters**
* **duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")) β Duration of context. This should be larger than the schedule duration.
* **func** (*Callable\[\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*],* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*]*) β A function that takes an index of sub-schedule and returns the fractional coordinate of of that sub-schedule. The returned value should be defined within \[0, 1]. The pulse index starts from 1.
**Yields**
None
**Return type**
Generator\[None, None, None]
**Notes**
The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the numerical context for each channel, you need to apply the context independently to channels.
</Function>
#### align\_left
<Function id="qiskit.pulse.builder.align_left" signature="qiskit.pulse.builder.align_left()">
Left alignment pulse scheduling context.
Pulse instructions within this context are scheduled as early as possible by shifting them left to the earliest available time.
Examples:
```python
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_left():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=0
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1)
```
**Yields**
None
**Return type**
[*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator "(in Python v3.12)")\[None, None, None]
</Function>
#### align\_right
<Function id="qiskit.pulse.builder.align_right" signature="qiskit.pulse.builder.align_right()">
Right alignment pulse scheduling context.
Pulse instructions within this context are scheduled as late as possible by shifting them right to the latest available time.
Examples:
```python
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1)
```
**Yields**
None
**Return type**
[*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator "(in Python v3.12)")\[None, None, None]
</Function>
#### align\_sequential
<Function id="qiskit.pulse.builder.align_sequential" signature="qiskit.pulse.builder.align_sequential()">
Sequential alignment pulse scheduling context.
Pulse instructions within this context are scheduled sequentially in time such that no two instructions will be played at the same time.
Examples:
```python
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_sequential():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will also start at t=100
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1)
```
**Yields**
None
**Return type**
[*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator "(in Python v3.12)")\[None, None, None]
</Function>
#### frequency\_offset
<Function id="qiskit.pulse.builder.frequency_offset" signature="qiskit.pulse.builder.frequency_offset(frequency, *channels, compensate_phase=False)">
Shift the frequency of inputs channels on entry into context and undo on exit.
Examples:
```python
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
# shift frequency by 1GHz
with pulse.frequency_offset(1e9, d0):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 3
with pulse.build(backend) as pulse_prog:
# Shift frequency by 1GHz.
# Undo accumulated phase in the shifted frequency frame
# when exiting the context.
with pulse.frequency_offset(1e9, d0, compensate_phase=True):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 4
```
**Parameters**
* **frequency** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Amount of frequency offset in Hz.
* **channels** (*PulseChannel*) β Channels to offset frequency of.
* **compensate\_phase** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Compensate for accumulated phase accumulated with respect to the channelsβ frame at its initial frequency.
**Yields**
None
**Return type**
[*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator "(in Python v3.12)")\[None, None, None]
</Function>
#### phase\_offset
<Function id="qiskit.pulse.builder.phase_offset" signature="qiskit.pulse.builder.phase_offset(phase, *channels)">
Shift the phase of input channels on entry into context and undo on exit.
Examples:
```python
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
with pulse.phase_offset(math.pi, d0):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 3
```
**Parameters**
* **phase** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Amount of phase offset in radians.
* **channels** (*PulseChannel*) β Channels to offset phase of.
**Yields**
None
**Return type**
[*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator "(in Python v3.12)")\[None, None, None]
</Function>
### Macros
Macros help you add more complex functionality to your pulse program.
```python
from qiskit import pulse
from qiskit.providers.fake_provider import GenericBackendV2
backend = GenericBackendV2(num_qubits=2, calibrate_instructions=True)
with pulse.build(backend) as measure_sched:
mem_slot = pulse.measure(0)
print(mem_slot)
```
```python
MemorySlot(0)
```
#### measure
<Function id="qiskit.pulse.builder.measure" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L2052-L2137" signature="qiskit.pulse.builder.measure(qubits, registers=None)">
Measure a qubit within the currently active builder context.
At the pulse level a measurement is composed of both a stimulus pulse and an acquisition instruction which tells the systems measurement unit to acquire data and process it. We provide this measurement macro to automate the process for you, but if desired full control is still available with [`acquire()`](#qiskit.pulse.builder.acquire "qiskit.pulse.builder.acquire") and [`play()`](#qiskit.pulse.builder.play "qiskit.pulse.builder.play").
To use the measurement it is as simple as specifying the qubit you wish to measure:
```python
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
qubit = 0
with pulse.build(backend) as pulse_prog:
# Do something to the qubit.
qubit_drive_chan = pulse.drive_channel(0)
pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan)
# Measure the qubit.
reg = pulse.measure(qubit)
```
For now it is not possible to do much with the handle to `reg` but in the future we will support using this handle to a result register to build up ones program. It is also possible to supply this register:
```python
with pulse.build(backend) as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan)
# Measure the qubit.
mem0 = pulse.MemorySlot(0)
reg = pulse.measure(qubit, mem0)
assert reg == mem0
```
<Admonition title="Note" type="note">
Requires the active builder context to have a backend set.
</Admonition>
**Parameters**
* **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*] |* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Physical qubit to measure.
* **registers** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[StorageLocation] | StorageLocation*) β Register to store result in. If not selected the current behavior is to return the `MemorySlot` with the same index as `qubit`. This register will be returned.
**Returns**
The `register` the qubit measurement result will be stored in.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")\[StorageLocation] | StorageLocation
</Function>
#### measure\_all
<Function id="qiskit.pulse.builder.measure_all" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L2140-L2180" signature="qiskit.pulse.builder.measure_all()">
Measure all qubits within the currently active builder context.
A simple macro function to measure all of the qubits in the device at the same time. This is useful for handling device `meas_map` and single measurement constraints.
Examples:
```python
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
# Measure all qubits and return associated registers.
regs = pulse.measure_all()
```
<Admonition title="Note" type="note">
Requires the active builder context to have a backend set.
</Admonition>
**Returns**
The `register`s the qubit measurement results will be stored in.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")\[[qiskit.pulse.channels.MemorySlot](qiskit.pulse.channels.MemorySlot "qiskit.pulse.channels.MemorySlot")]
</Function>
#### delay\_qubits
<Function id="qiskit.pulse.builder.delay_qubits" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L2183-L2210" signature="qiskit.pulse.builder.delay_qubits(duration, *qubits)">
Insert delays on all the `channels.Channel`s that correspond to the input `qubits` at the same time.
Examples:
```python
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
with pulse.build(backend) as pulse_prog:
# Delay for 100 cycles on qubits 0, 1 and 2.
regs = pulse.delay_qubits(100, 0, 1, 2)
```
<Admonition title="Note" type="note">
Requires the active builder context to have a backend set.
</Admonition>
**Parameters**
* **duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Duration to delay for.
* **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Physical qubits to delay on. Delays will be inserted based on the channels returned by `pulse.qubit_channels()`.
</Function>
### Utilities
The utility functions can be used to gather attributes about the backend and modify how the program is built.
```python
from qiskit import pulse
from qiskit.providers.fake_provider import GenericBackendV2
backend = GenericBackendV2(num_qubits=2, calibrate_instructions=True)
with pulse.build(backend) as u3_sched:
print('Number of qubits in backend: {}'.format(pulse.num_qubits()))
samples = 160
print('There are {} samples in {} seconds'.format(
samples, pulse.samples_to_seconds(160)))
seconds = 1e-6
print('There are {} seconds in {} samples.'.format(
seconds, pulse.seconds_to_samples(1e-6)))
```
```python
Number of qubits in backend: 1
There are 160 samples in 3.5555555555555554e-08 seconds
There are 1e-06 seconds in 4500 samples.
```
#### active\_backend
<Function id="qiskit.pulse.builder.active_backend" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L847-L862" signature="qiskit.pulse.builder.active_backend()">
Get the backend of the currently active builder context.
**Returns**
**The active backend in the currently active**
builder context.
**Return type**
[Backend](qiskit.providers.Backend "qiskit.providers.Backend")
**Raises**
[**exceptions.BackendNotSet**](#qiskit.pulse.BackendNotSet "qiskit.pulse.exceptions.BackendNotSet") β If the builder does not have a backend set.
</Function>
#### num\_qubits
<Function id="qiskit.pulse.builder.num_qubits" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L897-L920" signature="qiskit.pulse.builder.num_qubits()">
Return number of qubits in the currently active backend.
Examples:
```python
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.num_qubits())
```
```python
2
```
<Admonition title="Note" type="note">
Requires the active builder context to have a backend set.
</Admonition>
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Function>
#### qubit\_channels
<Function id="qiskit.pulse.builder.qubit_channels" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L954-L1004" signature="qiskit.pulse.builder.qubit_channels(qubit)">
Returns the set of channels associated with a qubit.
Examples:
```python
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.qubit_channels(0))
```
```python
{MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)}
```
<Admonition title="Note" type="note">
Requires the active builder context to have a backend set.
</Admonition>
<Admonition title="Note" type="note">
A channel may still be associated with another qubit in this list such as in the case where significant crosstalk exists.
</Admonition>
**Return type**
[set](https://docs.python.org/3/library/stdtypes.html#set "(in Python v3.12)")\[[qiskit.pulse.channels.Channel](#qiskit.pulse.channels.Channel "qiskit.pulse.channels.Channel")]
</Function>
#### samples\_to\_seconds
<Function id="qiskit.pulse.builder.samples_to_seconds" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L941-L951" signature="qiskit.pulse.builder.samples_to_seconds(samples)">
Obtain the time in seconds that will elapse for the input number of samples on the active backend.
**Parameters**
**samples** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| np.ndarray*) β Number of samples to convert to time in seconds.
**Returns**
The time that elapses in `samples`.
**Return type**
[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") | np.ndarray
</Function>
#### seconds\_to\_samples
<Function id="qiskit.pulse.builder.seconds_to_samples" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/builder.py#L923-L938" signature="qiskit.pulse.builder.seconds_to_samples(seconds)">
Obtain the number of samples that will elapse in `seconds` on the active backend.
Rounds down.
**Parameters**
**seconds** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *| np.ndarray*) β Time in seconds to convert to samples.
**Returns**
The number of samples for the time to elapse
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") | np.ndarray
</Function>
## Configuration
| | |
| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`InstructionScheduleMap`](qiskit.pulse.InstructionScheduleMap "qiskit.pulse.InstructionScheduleMap")() | Mapping from [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") [`qiskit.circuit.Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") names and qubits to [`Schedule`](qiskit.pulse.Schedule "qiskit.pulse.Schedule") s. In particular, the mapping is formatted as type::. |
## Exceptions
### PulseError
<Class id="qiskit.pulse.PulseError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/exceptions.py#L17-L27" signature="qiskit.pulse.PulseError(*message)" modifiers="exception">
Errors raised by the pulse module.
Set the error message.
</Class>
### BackendNotSet
<Class id="qiskit.pulse.BackendNotSet" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/exceptions.py#L30-L31" signature="qiskit.pulse.BackendNotSet(*message)" modifiers="exception">
Raised if the builder context does not have a backend.
Set the error message.
</Class>
### NoActiveBuilder
<Class id="qiskit.pulse.NoActiveBuilder" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/exceptions.py#L34-L35" signature="qiskit.pulse.NoActiveBuilder(*message)" modifiers="exception">
Raised if no builder context is active.
Set the error message.
</Class>
### UnassignedDurationError
<Class id="qiskit.pulse.UnassignedDurationError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/exceptions.py#L38-L39" signature="qiskit.pulse.UnassignedDurationError(*message)" modifiers="exception">
Raised if instruction duration is unassigned.
Set the error message.
</Class>
### UnassignedReferenceError
<Class id="qiskit.pulse.UnassignedReferenceError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/pulse/exceptions.py#L42-L43" signature="qiskit.pulse.UnassignedReferenceError(*message)" modifiers="exception">
Raised if subroutine is unassigned.
Set the error message.
</Class>
|
repo/docs/api/qiskit/1.0\pulse.mdx
|
---
title: qasm2
description: API reference for qiskit.qasm2
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.qasm2
---
<span id="module-qiskit.qasm2" />
<span id="qiskit-qasm2" />
<span id="openqasm-2-qiskit-qasm2" />
# OpenQASM 2
<span id="module-qiskit.qasm2" />
`qiskit.qasm2`
Qiskit has support for interoperation with OpenQASM 2.0 programs, both [parsing into Qiskit formats](#qasm2-parse) and [exporting back to OpenQASM 2](#qasm2-export).
<Admonition title="Note" type="note">
OpenQASM 2 is a simple language, and not suitable for general serialisation of Qiskit objects. See [some discussion of alternatives below](#qasm2-alternatives), if that is what you are looking for.
</Admonition>
<span id="qasm2-parse" />
## Parsing API
This module contains two public functions, both of which create a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") from an OpenQASM 2 program. [`load()`](#qiskit.qasm2.load "qiskit.qasm2.load") takes a filename, while [`loads()`](#qiskit.qasm2.loads "qiskit.qasm2.loads") takes the program itself as a string. Their internals are very similar, so both offer almost the same API.
### load
<Function id="qiskit.qasm2.load" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm2/__init__.py#L606-L658" signature="qiskit.qasm2.load(filename, *, include_path=('.',), include_input_directory='append', custom_instructions=(), custom_classical=(), strict=False)">
Parse an OpenQASM 2 program from a file into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"). The given path should be ASCII or UTF-8 encoded, and contain the OpenQASM 2 program.
**Parameters**
* **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*PathLike*](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.12)")) β The OpenQASM 2 program in a string.
* **include\_path** ([*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*PathLike*](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.12)")*]*) β order of directories to search when evaluating `include` statements.
* **include\_input\_directory** ([*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.12)")*\['append', 'prepend'] | None*) β Whether to add the directory of the input file to the `include_path`, and if so, whether to *append* it to search last, or *prepend* it to search first. Pass `None` to suppress adding this directory entirely.
* **custom\_instructions** ([*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*CustomInstruction*](#qiskit.qasm2.CustomInstruction "qiskit.qasm2.parse.CustomInstruction")*]*) β any custom constructors that should be used for specific gates or opaque instructions during circuit construction. See [Specifying custom instructions](#qasm2-custom-instructions) for more.
* **custom\_classical** ([*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*CustomClassical*](#qiskit.qasm2.CustomClassical "qiskit.qasm2.CustomClassical")*]*) β any custom classical functions that should be used during the parsing of classical expressions. See [Specifying custom classical functions](#qasm2-custom-classical) for more.
* **strict** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β whether to run in [strict mode](#qasm2-strict-mode).
**Returns**
A circuit object representing the same OpenQASM 2 program.
**Return type**
[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
</Function>
### loads
<Function id="qiskit.qasm2.loads" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm2/__init__.py#L567-L603" signature="qiskit.qasm2.loads(string, *, include_path=('.',), custom_instructions=(), custom_classical=(), strict=False)">
Parse an OpenQASM 2 program from a string into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit").
**Parameters**
* **string** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The OpenQASM 2 program in a string.
* **include\_path** ([*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*PathLike*](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.12)")*]*) β order of directories to search when evaluating `include` statements.
* **custom\_instructions** ([*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*CustomInstruction*](#qiskit.qasm2.CustomInstruction "qiskit.qasm2.parse.CustomInstruction")*]*) β any custom constructors that should be used for specific gates or opaque instructions during circuit construction. See [Specifying custom instructions](#qasm2-custom-instructions) for more.
* **custom\_classical** ([*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")*\[*[*CustomClassical*](#qiskit.qasm2.CustomClassical "qiskit.qasm2.CustomClassical")*]*) β any custom classical functions that should be used during the parsing of classical expressions. See [Specifying custom classical functions](#qasm2-custom-classical) for more.
* **strict** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β whether to run in [strict mode](#qasm2-strict-mode).
**Returns**
A circuit object representing the same OpenQASM 2 program.
**Return type**
[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
</Function>
Both of these loading functions also take an argument `include_path`, which is an iterable of directory names to use when searching for files in `include` statements. The directories are tried from index 0 onwards, and the first match is used. The import `qelib1.inc` is treated specially; it is always found before looking in the include path, and contains exactly the content of the [paper describing the OpenQASM 2 language](https://arxiv.org/abs/1707.03429). The gates in this include file are mapped to circuit-library gate objects defined by Qiskit.
<span id="qasm2-custom-instructions" />
### Specifying custom instructions
You can extend the quantum components of the OpenQASM 2 language by passing an iterable of information on custom instructions as the argument `custom_instructions`. In files that have compatible definitions for these instructions, the given `constructor` will be used in place of whatever other handling [`qiskit.qasm2`](#module-qiskit.qasm2 "qiskit.qasm2") would have done. These instructions may optionally be marked as `builtin`, which causes them to not require an `opaque` or `gate` declaration, but they will silently ignore a compatible declaration. Either way, it is an error to provide a custom instruction that has a different number of parameters or qubits as a defined instruction in a parsed program. Each element of the argument iterable should be a particular data class:
#### CustomInstruction
<Class id="qiskit.qasm2.CustomInstruction" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm2/parse.py#L80-L100" signature="qiskit.qasm2.CustomInstruction(name, num_params, num_qubits, constructor, builtin=False)" modifiers="class">
Information about a custom instruction that should be defined during the parse.
The `name`, `num_params` and `num_qubits` fields are self-explanatory. The `constructor` field should be a callable object with signature `*args -> Instruction`, where each of the `num_params` `args` is a floating-point value. Most of the built-in Qiskit gate classes have this form.
There is a final `builtin` field. This is optional, and if set true will cause the instruction to be defined and available within the parsing, even if there is no definition in any included OpenQASM 2 file.
</Class>
This can be particularly useful when trying to resolve ambiguities in the global-phase conventions of an OpenQASM 2 program. See [OpenQASM 2 Phase Conventions](#qasm2-phase-conventions) for more details.
<span id="qasm2-custom-classical" />
### Specifying custom classical functions
Similar to the quantum extensions above, you can also extend the processing done to classical expressions (arguments to gates) by passing an iterable to the argument `custom_classical` to either loader. This needs the `name` (a valid OpenQASM 2 identifier), the number `num_params` of parameters it takes, and a Python callable that implements the function. The Python callable must be able to accept `num_params` positional floating-point arguments, and must return a float or integer (which will be converted to a float). Builtin functions cannot be overridden.
#### CustomClassical
<Class id="qiskit.qasm2.CustomClassical" signature="qiskit.qasm2.CustomClassical" modifiers="class">
Information about a custom classical function that should be defined in mathematical expressions.
The given callable must be a Python function that takes num\_params floats, and returns a float. The name is the identifier that refers to it in the OpenQASM 2 program. This cannot clash with any defined gates.
</Class>
<span id="qasm2-strict-mode" />
### Strict mode
Both of the loader functions have an optional βstrictβ mode. By default, this parser is a little bit more relaxed than the official specification: it allows trailing commas in parameter lists; unnecessary (empty-statement) semicolons; the `OPENQASM 2.0;` version statement to be omitted; and a couple of other quality-of-life improvements without emitting any errors. You can use the letter-of-the-spec mode with `strict=True`.
<span id="qasm2-export" />
## Exporting API
Similar to other serialisation modules in Python, this module offers two public functions: [`dump()`](#qiskit.qasm2.dump "qiskit.qasm2.dump") and [`dumps()`](#qiskit.qasm2.dumps "qiskit.qasm2.dumps"), which take a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") and write out a representative OpenQASM 2 program to a file-like object or return a string, respectively.
### dump
<Function id="qiskit.qasm2.dump" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm2/export.py#L107-L122" signature="qiskit.qasm2.dump(circuit, filename_or_stream, /)">
Dump a circuit as an OpenQASM 2 program to a file or stream.
**Parameters**
* **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")) β the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") to be exported.
* **filename\_or\_stream** ([*os.PathLike*](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.12)") *|*[*io.TextIOBase*](https://docs.python.org/3/library/io.html#io.TextIOBase "(in Python v3.12)")) β either a path-like object (likely a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") or [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.12)")), or an already opened text-mode stream.
**Raises**
[**QASM2ExportError**](#qiskit.qasm2.QASM2ExportError "qiskit.qasm2.QASM2ExportError") β if the circuit cannot be represented by OpenQASM 2.
</Function>
### dumps
<Function id="qiskit.qasm2.dumps" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm2/export.py#L125-L200" signature="qiskit.qasm2.dumps(circuit, /)">
Export a circuit to an OpenQASM 2 program in a string.
**Parameters**
**circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")) β the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") to be exported.
**Returns**
An OpenQASM 2 string representing the circuit.
**Raises**
[**QASM2ExportError**](#qiskit.qasm2.QASM2ExportError "qiskit.qasm2.QASM2ExportError") β if the circuit cannot be represented by OpenQASM 2.
**Return type**
[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")
</Function>
## Errors
This module defines a generic error type that derives from [`QiskitError`](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") that can be used as a catch when you care about failures emitted by the interoperation layer specifically.
### QASM2Error
<Class id="qiskit.qasm2.QASM2Error" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm2/exceptions.py#L18-L19" signature="qiskit.qasm2.QASM2Error(*message)" modifiers="exception">
A general error raised by the OpenQASM 2 interoperation layer.
Set the error message.
</Class>
In cases where the lexer or parser fails due to an invalid OpenQASM 2 file, the conversion functions will raise a more specific error with a message explaining what the failure is, and where in the file it occurred.
### QASM2ParseError
<Class id="qiskit.qasm2.QASM2ParseError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm2/exceptions.py#L22-L23" signature="qiskit.qasm2.QASM2ParseError(*message)" modifiers="exception">
An error raised because of a failure to parse an OpenQASM 2 file.
Set the error message.
</Class>
When the exporters fail to export a circuit, likely because it has structure that cannot be represented by OpenQASM 2.0, they will also emit a custom error.
### QASM2ExportError
<Class id="qiskit.qasm2.QASM2ExportError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm2/exceptions.py#L26-L27" signature="qiskit.qasm2.QASM2ExportError(*message)" modifiers="exception">
An error raised because of a failure to convert a Qiskit object to an OpenQASM 2 form.
Set the error message.
</Class>
<span id="qasm2-examples" />
## Examples
### Exporting examples
Export a simple [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") to an OpenQASM 2 string:
```python
import qiskit.qasm2
from qiskit.circuit import QuantumCircuit
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
print(qiskit.qasm2.dumps(qc))
```
```python
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0],q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];
```
Write out the same [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") to a given filename:
```python
qiskit.qasm2.dump(qc, "myfile.qasm")
```
Similarly, one can use general [`os.PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.12)") instances as the filename:
```python
import pathlib
qiskit.qasm2.dump(qc, pathlib.Path.home() / "myfile.qasm")
```
One can also dump the text to an already-open stream:
```python
import io
with io.StringIO() as stream:
qiskit.qasm2.dump(qc, stream)
```
### Parsing examples
Use [`loads()`](#qiskit.qasm2.loads "qiskit.qasm2.loads") to import an OpenQASM 2 program in a string into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"):
```python
import qiskit.qasm2
program = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0], q[1];
measure q -> c;
"""
circuit = qiskit.qasm2.loads(program)
circuit.draw()
```
```python
βββββ βββ
q_0: β€ H ββββ βββ€Mββββ
ββββββββ΄ββββ₯ββββ
q_1: ββββββ€ X βββ«ββ€Mβ
βββββ β ββ₯β
c: 2/ββββββββββββ©βββ©β
0 1
```
You can achieve the same thing if the program is stored in a file by using [`load()`](#qiskit.qasm2.load "qiskit.qasm2.load") instead, passing the filename as an argument:
```python
import qiskit.qasm2
circuit = qiskit.qasm2.load("myfile.qasm")
```
OpenQASM 2 files can include other OpenQASM 2 files via the `include` statement. You can influence the search path used for finding these files with the `include_path` argument to both [`load()`](#qiskit.qasm2.load "qiskit.qasm2.load") and [`loads()`](#qiskit.qasm2.loads "qiskit.qasm2.loads"). By default, only the current working directory is searched.
```python
import qiskit.qasm2
program = """
include "other.qasm";
// ... and so on
"""
circuit = qiskit.qasm2.loads(program, include_path=("/path/to/a", "/path/to/b", "."))
```
For [`load()`](#qiskit.qasm2.load "qiskit.qasm2.load") only, there is an extra argument `include_input_directory`, which can be used to either `'append'`, `'prepend'` or ignore (`None`) the directory of the loaded file in the include path. By default, this directory is appended to the search path, so it is tried last, but you can change this.
```python
import qiskit.qasm2
filenames = ["./subdirectory/a.qasm", "/path/to/b.qasm", "~/my.qasm"]
# Search the directory of each file before other parts of the include path.
circuits = [
qiskit.qasm2.load(filename, include_input_directory="prepend") for filename in filenames
]
# Override the include path, and don't search the directory of each file unless it's in the
# absolute path list.
circuits = [
qiskit.qasm2.load(
filename,
include_path=("/usr/include/qasm", "~/qasm/include"),
include_input_directory=None,
)
for filename in filenames
]
```
Sometimes you may want to influence the [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate") objects that the importer emits for given named instructions. Gates that are defined by the statement `include "qelib1.inc";` will automatically be associated with a suitable Qiskit circuit-library gate, but you can extend this:
```python
from qiskit.circuit import Gate
from qiskit.qasm2 import loads, CustomInstruction
class MyGate(Gate):
def __init__(self, theta):
super().__init__("my", 2, [theta])
class Builtin(Gate):
def __init__(self):
super().__init__("builtin", 1, [])
program = """
opaque my(theta) q1, q2;
qreg q[2];
my(0.5) q[0], q[1];
builtin q[0];
"""
customs = [
CustomInstruction(name="my", num_params=1, num_qubits=2, constructor=MyGate),
# Setting 'builtin=True' means the instruction doesn't require a declaration to be usable.
CustomInstruction("builtin", 0, 1, Builtin, builtin=True),
]
circuit = loads(program, custom_instructions=customs)
```
Similarly, you can add new classical functions used during the description of arguments to gates, both in the main body of the program (which come out constant-folded) and within the bodies of defined gates (which are computed on demand). Here we provide a Python version of `atan2(y, x)`, which mathematically is $\arctan(y/x)$ but correctly handling angle quadrants and infinities, and a custom `add_one` function:
```python
import math
from qiskit.qasm2 import loads, CustomClassical
program = """
include "qelib1.inc";
qreg q[2];
rx(atan2(pi, 3 + add_one(0.2))) q[0];
cx q[0], q[1];
"""
def add_one(x):
return x + 1
customs = [
# `atan2` takes two parameters, and `math.atan2` implements it.
CustomClassical("atan2", 2, math.atan2),
# Our `add_one` takes only one parameter.
CustomClassical("add_one", 1, add_one),
]
circuit = loads(program, custom_classical=customs)
```
<span id="qasm2-phase-conventions" />
## OpenQASM 2 Phase Conventions
As a language, OpenQASM 2 does not have a way to specify the global phase of a complete program, nor of particular gate definitions. This means that parsers of the language may interpret particular gates with a different global phase than what you might expect. For example, the *de facto* standard library of OpenQASM 2 `qelib1.inc` contains definitions of `u1` and `rz` as follows:
```python
gate u1(lambda) q {
U(0, 0, lambda) q;
}
gate rz(phi) a {
u1(phi) a;
}
```
In other words, `rz` appears to be a direct alias for `u1`. However, the interpretation of `u1` is specified in [equation (3) of the paper describing the language](https://arxiv.org/abs/1707.03429) as
$$
u_1(\lambda) = \operatorname{diag}\bigl(1, e^{i\lambda}\bigr) \sim R_z(\lambda)
$$
where the $\sim$ symbol denotes equivalence only up to a global phase. When parsing OpenQASM 2, we need to choose how to handle a distinction between such gates; `u1` is defined in the prose to be different by a phase to `rz`, but the language is not designed to represent this.
Qiskitβs default position is to interpret a usage of the standard-library `rz` using [`RZGate`](qiskit.circuit.library.RZGate "qiskit.circuit.library.RZGate"), and a usage of `u1` as using the phase-distinct [`U1Gate`](qiskit.circuit.library.U1Gate "qiskit.circuit.library.U1Gate"). If you wish to use the phase conventions more implied by a direct interpretation of the `gate` statements in the header file, you can use [`CustomInstruction`](#qiskit.qasm2.CustomInstruction "qiskit.qasm2.CustomInstruction") to override how Qiskit builds the circuit.
For the standard `qelib1.inc` include there is only one point of difference, and so the override needed to switch its phase convention is:
```python
from qiskit import qasm2
from qiskit.circuit.library import PhaseGate
from qiskit.quantum_info import Operator
program = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
rz(pi / 2) q[0];
"""
custom = [
qasm2.CustomInstruction("rz", 1, 1, PhaseGate),
]
```
This will use Qiskitβs [`PhaseGate`](qiskit.circuit.library.PhaseGate "qiskit.circuit.library.PhaseGate") class to represent the `rz` instruction, which is equal (including the phase) to [`U1Gate`](qiskit.circuit.library.U1Gate "qiskit.circuit.library.U1Gate"):
```python
Operator(qasm2.loads(program, custom_instructions=custom))
```
```python
Operator([[1.000000e+00+0.j, 0.000000e+00+0.j],
[0.000000e+00+0.j, 6.123234e-17+1.j]],
input_dims=(2,), output_dims=(2,))
```
<span id="qasm2-legacy-compatibility" />
## Legacy Compatibility
[`QuantumCircuit.from_qasm_str()`](qiskit.circuit.QuantumCircuit#from_qasm_str "qiskit.circuit.QuantumCircuit.from_qasm_str") and [`from_qasm_file()`](qiskit.circuit.QuantumCircuit#from_qasm_file "qiskit.circuit.QuantumCircuit.from_qasm_file") used to make a few additions on top of the raw specification. Qiskit originally tried to use OpenQASM 2 as a sort of serialisation format, and expanded its behaviour as Qiskit expanded. The new parser under all its defaults implements the specification more strictly.
In particular, in the legacy importers:
* **the include\_path is effectively:**
1. `<qiskit>/qasm/libs`, where `<qiskit>` is the root of the installed `qiskit` package;
2. the current working directory.
* **there are additional instructions defined in `qelib1.inc`:**
**`csx a, b`**
Controlled $\sqrt X$ gate, corresponding to [`CSXGate`](qiskit.circuit.library.CSXGate "qiskit.circuit.library.CSXGate").
**`cu(theta, phi, lambda, gamma) c, t`**
The four-parameter version of a controlled-$U$, corresponding to [`CUGate`](qiskit.circuit.library.CUGate "qiskit.circuit.library.CUGate").
**`rxx(theta) a, b`**
Two-qubit rotation around the $XX$ axis, corresponding to [`RXXGate`](qiskit.circuit.library.RXXGate "qiskit.circuit.library.RXXGate").
**`rzz(theta) a, b`**
Two-qubit rotation around the $ZZ$ axis, corresponding to [`RZZGate`](qiskit.circuit.library.RZZGate "qiskit.circuit.library.RZZGate").
**`rccx a, b, c`**
The double-controlled $X$ gate, but with relative phase differences over the standard Toffoli gate. This *should* correspond to the Qiskit gate [`RCCXGate`](qiskit.circuit.library.RCCXGate "qiskit.circuit.library.RCCXGate"), but the legacy converter wouldnβt actually output this type.
**`rc3x a, b, c, d`**
The triple-controlled $X$ gate, but with relative phase differences over the standard definition. Corresponds to [`RC3XGate`](qiskit.circuit.library.RC3XGate "qiskit.circuit.library.RC3XGate").
**`c3x a, b, c, d`**
The triple-controlled $X$ gate, corresponding to [`C3XGate`](qiskit.circuit.library.C3XGate "qiskit.circuit.library.C3XGate").
**`c3sqrtx a, b, c, d`**
The triple-controlled $\sqrt X$ gate, corresponding to [`C3SXGate`](qiskit.circuit.library.C3SXGate "qiskit.circuit.library.C3SXGate").
**`c4x a, b, c, d, e`**
The quadruple-controlled $X$ gate., corresponding to [`C4XGate`](qiskit.circuit.library.C4XGate "qiskit.circuit.library.C4XGate").
* if *any* `opaque` or `gate` definition was given for the name `delay`, they attempt to output a [`Delay`](qiskit.circuit.Delay "qiskit.circuit.Delay") instruction at each call. To function, this expects a definition compatible with `opaque delay(t) q;`, where the time `t` is given in units of `dt`. The importer will raise errors on construction if there was not exactly one parameter and one qubit, or if the parameter is not integer-valued.
* the additional scientific-calculator functions `asin`, `acos` and `atan` are available.
* the parsed grammar is effectively the same as [the strict mode of the new importers](#qasm2-strict-mode).
You can emulate this behaviour in [`load()`](#qiskit.qasm2.load "qiskit.qasm2.load") and [`loads()`](#qiskit.qasm2.loads "qiskit.qasm2.loads") by setting include\_path appropriately (try inspecting the variable `qiskit.__file__` to find the installed location), and by passing a list of [`CustomInstruction`](#qiskit.qasm2.CustomInstruction "qiskit.qasm2.CustomInstruction") instances for each of the custom gates you care about. To make things easier we make three tuples available, which each contain one component of a configuration that is equivalent to Qiskitβs legacy converter behaviour.
**qiskit.qasm2.LEGACY\_CUSTOM\_INSTRUCTIONS**
A tuple containing the extra custom\_instructions that Qiskitβs legacy built-in converters used if `qelib1.inc` is included, and there is any definition of a `delay` instruction. The gates in the paper version of `qelib1.inc` and `delay` all require a compatible declaration statement to be present within the OpenQASM 2 program, but Qiskitβs legacy additions are all marked as builtins since they are not actually present in any include file this parser sees.
**qiskit.qasm2.LEGACY\_CUSTOM\_CLASSICAL**
A tuple containing the extra custom\_classical functions that Qiskitβs legacy built-in converters use beyond those specified by the paper. This is the three basic inverse trigonometric functions: $\asin$, $\acos$ and $\atan$.
**qiskit.qasm2.LEGACY\_INCLUDE\_PATH**
A tuple containing the exact include\_path used by the legacy Qiskit converter.
On *all* the gates defined in Qiskitβs legacy version of `qelib1.inc` and the `delay` instruction, it does not matter how the gates are actually defined and used, the legacy importer will always attempt to output its custom objects for them. This can result in errors during the circuit construction, even after a successful parse. There is no way to emulate this buggy behaviour with [`qiskit.qasm2`](#module-qiskit.qasm2 "qiskit.qasm2"); only an `include "qelib1.inc";` statement or the custom\_instructions argument can cause built-in Qiskit instructions to be used, and the signatures of these match each other.
<Admonition title="Note" type="note">
Circuits imported with [`load()`](#qiskit.qasm2.load "qiskit.qasm2.load") and [`loads()`](#qiskit.qasm2.loads "qiskit.qasm2.loads") with the above legacy-compatibility settings should compare equal to those created by Qiskitβs legacy importer, provided no non-`qelib1.inc` user gates are defined. User-defined gates are handled slightly differently in the new importer, and while they should have equivalent [`definition`](qiskit.circuit.Instruction#definition "qiskit.circuit.Instruction.definition") fields on inspection, this module uses a custom class to lazily load the definition when it is requested (like most Qiskit objects), rather than eagerly creating it during the parse. Qiskitβs comparison rules for gates will see these two objects as unequal, although any pass through [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") for a particular backend should produce the same output circuits.
</Admonition>
<span id="qasm2-alternatives" />
## Alternatives
The parser components of this module started off as a separate PyPI package: [qiskit-qasm2](https://pypi.org/project/qiskit-qasm2/). This package at version 0.5.3 was vendored into Qiskit Terra 0.24. Any subsequent changes between the two packages may not necessarily be kept in sync.
There is a newer version of the OpenQASM specification, version 3.0, which is described at [https://openqasm.com](https://openqasm.com). This includes far more facilities for high-level classical programming. Qiskit has some rudimentary support for OpenQASM 3 already; see [`qiskit.qasm3`](qasm3#module-qiskit.qasm3 "qiskit.qasm3") for that.
OpenQASM 2 is not a suitable serialization language for Qiskitβs [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"). This module is provided for interoperability purposes, not as a general serialization format. If that is what you need, consider using [`qiskit.qpy`](qpy#module-qiskit.qpy "qiskit.qpy") instead.
|
repo/docs/api/qiskit/1.0\qasm2.mdx
|
---
title: qasm3
description: API reference for qiskit.qasm3
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.qasm3
---
<span id="module-qiskit.qasm3" />
<span id="qiskit-qasm3" />
<span id="openqasm-3-qiskit-qasm3" />
# OpenQASM 3
<span id="module-qiskit.qasm3" />
`qiskit.qasm3`
Qiskit provides some tools for converting between [OpenQASM 3](https://openqasm.com) representations of quantum programs, and the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") class. These will continue to evolve as Qiskitβs support for the dynamic-circuit capabilities expressed by OpenQASM 3 increases.
## Exporting to OpenQASM 3
The high-level functions are simply [`dump()`](#qiskit.qasm3.dump "qiskit.qasm3.dump") and [`dumps()`](#qiskit.qasm3.dumps "qiskit.qasm3.dumps"), which respectively export to a file (given as a filename) and to a Python string.
### dump
<Function id="qiskit.qasm3.dump" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm3/__init__.py#L249-L259" signature="qiskit.qasm3.dump(circuit, stream, **kwargs)">
Serialize a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") object as an OpenQASM 3 stream to file-like object.
**Parameters**
* **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")) β Circuit to serialize.
* **stream** (*TextIOBase*) β stream-like object to dump the OpenQASM 3 serialization
* **\*\*kwargs** β Arguments for the [`Exporter`](#qiskit.qasm3.Exporter "qiskit.qasm3.Exporter") constructor.
</Function>
### dumps
<Function id="qiskit.qasm3.dumps" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm3/__init__.py#L236-L246" signature="qiskit.qasm3.dumps(circuit, **kwargs)">
Serialize a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") object in an OpenQASM 3 string.
**Parameters**
* **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")) β Circuit to serialize.
* **\*\*kwargs** β Arguments for the [`Exporter`](#qiskit.qasm3.Exporter "qiskit.qasm3.Exporter") constructor.
**Returns**
The OpenQASM 3 serialization
**Return type**
[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")
</Function>
Both of these exporter functions are single-use wrappers around the main [`Exporter`](#qiskit.qasm3.Exporter "qiskit.qasm3.Exporter") class. For more complex exporting needs, including dumping multiple circuits in a single session, it may be more convenient or faster to use the complete interface.
### Exporter
<Class id="qiskit.qasm3.Exporter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm3/exporter.py#L127-L196" signature="qiskit.qasm3.Exporter(includes=('stdgates.inc', ), basis_gates=('U', ), disable_constants=False, alias_classical_registers=None, allow_aliasing=None, indent='Β ', experimental=ExperimentalFeatures.None)" modifiers="class">
QASM3 exporter main class.
**Parameters**
* **includes** ([*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]*) β the filenames that should be emitted as includes. These files will be parsed for gates, and any objects dumped from this exporter will use those definitions where possible.
* **basis\_gates** ([*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]*) β the basic defined gate set of the backend.
* **disable\_constants** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β if `True`, always emit floating-point constants for numeric parameter values. If `False` (the default), then values close to multiples of OpenQASM 3 constants (`pi`, `euler`, and `tau`) will be emitted in terms of those constants instead, potentially improving accuracy in the output.
* **alias\_classical\_registers** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β
If `True`, then bits may be contained in more than one register. If so, the registers will be emitted using βaliasβ definitions, which might not be well supported by consumers of OpenQASM 3.
<Admonition title="See also" type="note">
**Parameter `allow_aliasing`**
A value for `allow_aliasing` overrides any value given here, and supersedes this parameter.
</Admonition>
* **allow\_aliasing** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β
If `True`, then bits may be contained in more than one register. If so, the registers will be emitted using βaliasβ definitions, which might not be well supported by consumers of OpenQASM 3. Defaults to `False` or the value of `alias_classical_registers`.
New in version 0.25.0.
* **indent** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β the indentation string to use for each level within an indented block. Can be set to the empty string to disable indentation.
* **experimental** ([*ExperimentalFeatures*](#qiskit.qasm3.ExperimentalFeatures "qiskit.qasm3.experimental.ExperimentalFeatures")) β any experimental features to enable during the export. See [`ExperimentalFeatures`](#qiskit.qasm3.ExperimentalFeatures "qiskit.qasm3.ExperimentalFeatures") for more details.
#### dump
<Function id="qiskit.qasm3.Exporter.dump" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm3/exporter.py#L184-L196" signature="dump(circuit, stream)">
Convert the circuit to OpenQASM 3, dumping the result to a file or text stream.
</Function>
#### dumps
<Function id="qiskit.qasm3.Exporter.dumps" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm3/exporter.py#L178-L182" signature="dumps(circuit)">
Convert the circuit to OpenQASM 3, returning the result as a string.
</Function>
</Class>
All of these interfaces will raise [`QASM3ExporterError`](#qiskit.qasm3.QASM3ExporterError "qiskit.qasm3.QASM3ExporterError") on failure.
### QASM3ExporterError
<Class id="qiskit.qasm3.QASM3ExporterError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm3/exceptions.py#L22-L23" signature="qiskit.qasm3.QASM3ExporterError(*message)" modifiers="exception">
An error raised during running the OpenQASM 3 exporter.
Set the error message.
</Class>
### Experimental features
The OpenQASM 3 language is still evolving as hardware capabilities improve, so there is no final syntax that Qiskit can reliably target. In order to represent the evolving language, we will sometimes release features before formal standardization, which may need to change as the review process in the OpenQASM 3 design committees progresses. By default, the exporters will only support standardised features of the language. To enable these early-release features, use the `experimental` keyword argument of [`dump()`](#qiskit.qasm3.dump "qiskit.qasm3.dump") and [`dumps()`](#qiskit.qasm3.dumps "qiskit.qasm3.dumps"). The available feature flags are:
#### ExperimentalFeatures
<Class id="qiskit.qasm3.ExperimentalFeatures" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm3/experimental.py#L21-L70" signature="qiskit.qasm3.ExperimentalFeatures(value)" modifiers="class">
Flags for experimental features that the OpenQASM 3 exporter supports.
These are experimental and are more liable to change, because the OpenQASM 3 specification has not formally accepted them yet, so the syntax may not be finalized.
##### SWITCH\_CASE\_V1
<Attribute id="qiskit.qasm3.ExperimentalFeatures.SWITCH_CASE_V1" attributeValue="1">
Support exporting switch-case statements as proposed by [https://github.com/openqasm/openqasm/pull/463](https://github.com/openqasm/openqasm/pull/463) at [commit bfa787aa3078](https://github.com/openqasm/openqasm/pull/463/commits/bfa787aa3078).
These have the output format:
```python
switch (i) {
case 0:
case 1:
x $0;
break;
case 2: {
z $0;
}
break;
default: {
cx $0, $1;
}
break;
}
```
This differs from the syntax of the `switch` statement as stabilized. If this flag is not passed, then the parser will instead output using the stabilized syntax, which would render the same example above as:
```python
switch (i) {
case 0, 1 {
x $0;
}
case 2 {
z $0;
}
default {
cx $0, $1;
}
}
```
</Attribute>
</Class>
If you want to enable multiple experimental features, you should combine the flags using the `|` operator, such as `flag1 | flag2`.
For example, to perform an export using the early semantics of `switch` support:
```python
from qiskit import qasm3, QuantumCircuit, QuantumRegister, ClassicalRegister
# Build the circuit
qreg = QuantumRegister(3)
creg = ClassicalRegister(3)
qc = QuantumCircuit(qreg, creg)
with qc.switch(creg) as case:
with case(0):
qc.x(0)
with case(1, 2):
qc.x(1)
with case(case.DEFAULT):
qc.x(2)
# Export to an OpenQASM 3 string.
qasm_string = qasm3.dumps(qc, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1)
```
<Admonition title="Note" type="note">
All features enabled by the experimental flags are naturally transient. If it becomes necessary to remove flags, they will be subject to [the standard Qiskit deprecation policy](https://github.com/Qiskit/qiskit/blob/main/DEPRECATION.md). We will leave these experimental flags in place for as long as is reasonable.
However, we cannot guarantee any support windows for *consumers* of OpenQASM 3 code generated using these experimental flags, if the OpenQASM 3 language specification changes the proposal that the flag is based on. It is possible that any tool you are using to consume OpenQASM 3 code created using these flags may update or remove their support while Qiskit continues to offer the flag. You should not rely on the resultant experimental OpenQASM 3 code for long-term storage of programs.
</Admonition>
## Importing from OpenQASM 3
Currently only two high-level functions are offered, as Qiskit support for importing from OpenQASM 3 is in its infancy, and the implementation is expected to change significantly. The two functions are [`load()`](#qiskit.qasm3.load "qiskit.qasm3.load") and [`loads()`](#qiskit.qasm3.loads "qiskit.qasm3.loads"), which are direct counterparts of [`dump()`](#qiskit.qasm3.dump "qiskit.qasm3.dump") and [`dumps()`](#qiskit.qasm3.dumps "qiskit.qasm3.dumps"), respectively loading a program indirectly from a named file and directly from a given string.
<Admonition title="Note" type="note">
While we are still in the exploratory release period, to use either function, the package `qiskit_qasm3_import` must be installed. This can be done by installing Qiskit with the `qasm3-import` extra, such as by:
```python
pip install qiskit[qasm3-import]
```
We expect that this functionality will eventually be merged into Qiskit, and no longer require an optional import, but we do not yet have a timeline for this.
</Admonition>
### load
<Function id="qiskit.qasm3.load" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/utils/lazy_tester.py#L262-L284" signature="qiskit.qasm3.load(filename)">
Load an OpenQASM 3 program from the file `filename`.
**Parameters**
**filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β the filename to load the program from.
**Returns**
a circuit representation of the OpenQASM 3 program.
**Return type**
[QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")
**Raises**
[**QASM3ImporterError**](#qiskit.qasm3.QASM3ImporterError "qiskit.qasm3.QASM3ImporterError") β if the OpenQASM 3 file is invalid, or cannot be represented by a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit").
</Function>
### loads
<Function id="qiskit.qasm3.loads" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/utils/lazy_tester.py#L287-L307" signature="qiskit.qasm3.loads(program)">
Load an OpenQASM 3 program from the given string.
**Parameters**
**program** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β the OpenQASM 3 program.
**Returns**
a circuit representation of the OpenQASM 3 program.
**Return type**
[QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")
**Raises**
[**QASM3ImporterError**](#qiskit.qasm3.QASM3ImporterError "qiskit.qasm3.QASM3ImporterError") β if the OpenQASM 3 file is invalid, or cannot be represented by a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit").
</Function>
Both of these two functions raise [`QASM3ImporterError`](#qiskit.qasm3.QASM3ImporterError "qiskit.qasm3.QASM3ImporterError") on failure.
### QASM3ImporterError
<Class id="qiskit.qasm3.QASM3ImporterError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm3/exceptions.py#L26-L27" signature="qiskit.qasm3.QASM3ImporterError(*message)" modifiers="exception">
An error raised during the OpenQASM 3 importer.
Set the error message.
</Class>
For example, we can define a quantum program using OpenQASM 3, and use [`loads()`](#qiskit.qasm3.loads "qiskit.qasm3.loads") to directly convert it into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"):
```python
import qiskit.qasm3
program = """
OPENQASM 3.0;
include "stdgates.inc";
input float[64] a;
qubit[3] q;
bit[2] mid;
bit[3] out;
let aliased = q[0:1];
gate my_gate(a) c, t {
gphase(a / 2);
ry(a) c;
cx c, t;
}
gate my_phase(a) c {
ctrl @ inv @ gphase(a) c;
}
my_gate(a * 2) aliased[0], q[{1, 2}][0];
measure q[0] -> mid[0];
measure q[1] -> mid[1];
while (mid == "00") {
reset q[0];
reset q[1];
my_gate(a) q[0], q[1];
my_phase(a - pi/2) q[1];
mid[0] = measure q[0];
mid[1] = measure q[1];
}
if (mid[0]) {
let inner_alias = q[{0, 1}];
reset inner_alias;
}
out = measure q;
"""
circuit = qiskit.qasm3.loads(program)
circuit.draw("mpl")
```

### Experimental import interface
The import functions given above rely on the ANTLR-based reference parser from the OpenQASM project itself, which is more intended as a language reference than a performant parser. You need to have the extension `qiskit-qasm3-import` installed to use it.
Qiskit is developing a native parser, written in Rust, which is available as part of the core Qiskit package. This parser is still in its early experimental stages, so is missing features and its interface is changing and expanding, but it is typically orders of magnitude more performant for the subset of OpenQASM 3 it currently supports, and its internals produce better error diagnostics on parsing failures.
You can use the experimental interface immediately, with similar functions to the main interface above:
#### load\_experimental
<Function id="qiskit.qasm3.load_experimental" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm3/__init__.py" signature="qiskit.qasm3.load_experimental(pathlike_or_filelike, /, *, custom_gates=None, include_path=None)">
Load an OpenQASM 3 program from a source file into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit").
<Admonition title="Warning" type="caution">
This native version of the OpenQASM 3 importer is currently experimental. It is typically much faster than [`load()`](#qiskit.qasm3.load "qiskit.qasm3.load"), but has a reduced supported feature set, which will expand over time.
</Admonition>
**Parameters**
* **pathlike\_or\_filelike** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*os.PathLike*](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.12)") *|*[*io.TextIOBase*](https://docs.python.org/3/library/io.html#io.TextIOBase "(in Python v3.12)")) β the program source. This can either be given as a filepath, or an open text stream object. If the stream is already opened it is consumed in Python space, whereas filenames are opened and consumed in Rust space; there might be slightly different performance characteristics, depending on your system and how the streams are buffered by default.
* **custom\_gates** (*Iterable\[*[*CustomGate*](#qiskit.qasm3.CustomGate "qiskit.qasm3.CustomGate")*]*) β Python constructors to use for particular named gates. If not supplied, Qiskit will use its own standard-library constructors for gates defined in the OpenQASM 3.0 standard-library file `stdgates.inc`.
* **include\_path** (*Iterable\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]*) β the path to search when resolving `include` statements. If not given, Qiskit will arrange for this to point to a location containing `stdgates.inc` only. Paths are tried in the sequence order.
**Returns**
the constructed circuit object.
**Return type**
[`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")
**Raises**
**.QASM3ImporterError** β if an error occurred during parsing or semantic analysis. In the case of a parsing error, most of the error messages are printed to the terminal and formatted, for better legibility.
</Function>
#### loads\_experimental
<Function id="qiskit.qasm3.loads_experimental" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/qasm3/__init__.py" signature="qiskit.qasm3.loads_experimental(source, /, *, custom_gates=None, include_path=None)">
Load an OpenQASM 3 program from a string into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit").
<Admonition title="Warning" type="caution">
This native version of the OpenQASM 3 importer is currently experimental. It is typically much faster than [`loads()`](#qiskit.qasm3.loads "qiskit.qasm3.loads"), but has a reduced supported feature set, which will expand over time.
</Admonition>
**Parameters**
* **source** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β the program source in a Python string.
* **custom\_gates** (*Iterable\[*[*CustomGate*](#qiskit.qasm3.CustomGate "qiskit.qasm3.CustomGate")*]*) β Python constructors to use for particular named gates. If not supplied, Qiskit will use its own standard-library constructors for gates defined in the OpenQASM 3.0 standard-library file `stdgates.inc`.
* **include\_path** (*Iterable\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]*) β the path to search when resolving `include` statements. If not given, Qiskit will arrange for this to point to a location containing `stdgates.inc` only. Paths are tried in the sequence order.
**Returns**
the constructed circuit object.
**Return type**
[`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")
**Raises**
**.QASM3ImporterError** β if an error occurred during parsing or semantic analysis. In the case of a parsing error, most of the error messages are printed to the terminal and formatted, for better legibility.
</Function>
These two functions are both experimental, meaning they issue an [`ExperimentalWarning`](exceptions#qiskit.exceptions.ExperimentalWarning "qiskit.exceptions.ExperimentalWarning") on usage, and their interfaces may be subject to change within the Qiskit 1.x release series. In particular, the native parser may be promoted to be the default version of [`load()`](#qiskit.qasm3.load "qiskit.qasm3.load") and [`loads()`](#qiskit.qasm3.loads "qiskit.qasm3.loads"). If you are happy to accept the risk of using the experimental interface, you can disable the warning by doing:
```python
import warnings
from qiskit.exceptions import ExperimentalWarning
warnings.filterwarnings("ignore", category=ExperimentalWarning, module="qiskit.qasm3")
```
These two functions allow for specifying include paths as an iterable of paths, and for specifying custom Python constructors to use for particular gates. These custom constructors are specified by using the [`CustomGate`](#qiskit.qasm3.CustomGate "qiskit.qasm3.CustomGate") object:
#### CustomGate
<Class id="qiskit.qasm3.CustomGate" signature="qiskit.qasm3.CustomGate" modifiers="class">
Information received from Python space about how to construct a Python-space object to represent a given gate that might be declared.
</Class>
In `custom_gates` is not given, Qiskit will attempt to use its standard-library gate objects for the gates defined in OpenQASM 3 standard library file `stdgates.inc`. This sequence of gates is available on this module, if you wish to build on top of it:
**qiskit.qasm3.STDGATES\_INC\_GATES**
A tuple of [`CustomGate`](#qiskit.qasm3.CustomGate "qiskit.qasm3.CustomGate") objects specifying the Qiskit constructors to use for the `stdgates.inc` include file.
|
repo/docs/api/qiskit/1.0\qasm3.mdx
|
---
title: RunConfig
description: API reference for qiskit.assembler.RunConfig
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.assembler.RunConfig
---
# RunConfig
<Class id="qiskit.assembler.RunConfig" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/assembler/run_config.py#L18-L77" signature="qiskit.assembler.RunConfig(shots=None, seed_simulator=None, memory=None, parameter_binds=None, **kwargs)" modifiers="class">
Bases: [`SimpleNamespace`](https://docs.python.org/3/library/types.html#types.SimpleNamespace "(in Python v3.12)")
Class for Run Configuration.
### shots
<Attribute id="qiskit.assembler.RunConfig.shots">
the number of shots
**Type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### seed\_simulator
<Attribute id="qiskit.assembler.RunConfig.seed_simulator">
the seed to use in the simulator
**Type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### memory
<Attribute id="qiskit.assembler.RunConfig.memory">
whether to request memory from backend (per-shot readouts)
**Type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Attribute>
### parameter\_binds
<Attribute id="qiskit.assembler.RunConfig.parameter_binds">
List of parameter bindings
**Type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")\[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)")]
</Attribute>
Initialize a RunConfig object
**Parameters**
* **shots** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β the number of shots
* **seed\_simulator** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β the seed to use in the simulator
* **memory** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β whether to request memory from backend (per-shot readouts)
* **parameter\_binds** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)")*]*) β List of parameter bindings
* **\*\*kwargs** β optional fields
## Methods
### from\_dict
<Function id="qiskit.assembler.RunConfig.from_dict" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/assembler/run_config.py#L57-L69" signature="from_dict(data)" modifiers="classmethod">
Create a new RunConfig object from a dictionary.
**Parameters**
**data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)")) β A dictionary representing the RunConfig to create. It will be in the same format as output by [`to_dict()`](#qiskit.assembler.RunConfig.to_dict "qiskit.assembler.RunConfig.to_dict").
**Returns**
The RunConfig from the input dictionary.
**Return type**
[RunConfig](#qiskit.assembler.RunConfig "qiskit.assembler.RunConfig")
</Function>
### to\_dict
<Function id="qiskit.assembler.RunConfig.to_dict" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/assembler/run_config.py#L71-L77" signature="to_dict()">
Return a dictionary format representation of the RunConfig
**Returns**
The dictionary form of the RunConfig.
**Return type**
[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.assembler.RunConfig.mdx
|
---
title: AncillaQubit
description: API reference for qiskit.circuit.AncillaQubit
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.AncillaQubit
---
# AncillaQubit
<Class id="qiskit.circuit.AncillaQubit" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/quantumregister.py#L60-L65" signature="qiskit.circuit.AncillaQubit(register=None, index=None)" modifiers="class">
Bases: [`Qubit`](qiskit.circuit.Qubit "qiskit.circuit.quantumregister.Qubit")
A qubit used as ancillary qubit.
Creates a qubit.
**Parameters**
* **register** ([*QuantumRegister*](qiskit.circuit.QuantumRegister "qiskit.circuit.QuantumRegister")) β Optional. A quantum register containing the bit.
* **index** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Optional. The index of the bit in its containing register.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the provided register is not a valid [`QuantumRegister`](qiskit.circuit.QuantumRegister "qiskit.circuit.QuantumRegister")
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.AncillaQubit.mdx
|
---
title: AncillaRegister
description: API reference for qiskit.circuit.AncillaRegister
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.AncillaRegister
---
# AncillaRegister
<Class id="qiskit.circuit.AncillaRegister" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/quantumregister.py#L68-L75" signature="qiskit.circuit.AncillaRegister(size=None, name=None, bits=None)" modifiers="class">
Bases: [`QuantumRegister`](qiskit.circuit.QuantumRegister "qiskit.circuit.quantumregister.QuantumRegister")
Implement an ancilla register.
Create a new generic register.
Either the `size` or the `bits` argument must be provided. If `size` is not None, the register will be pre-populated with bits of the correct type.
**Parameters**
* **size** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Optional. The number of bits to include in the register.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Optional. The name of the register. If not provided, a unique name will be auto-generated from the register type.
* **bits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*Bit*](qiskit.circuit.Bit "qiskit.circuit.Bit")*]*) β Optional. A list of Bit() instances to be used to populate the register.
**Raises**
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if both the `size` and `bits` arguments are provided, or if neither are.
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if `size` is not valid.
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if `name` is not a valid name according to the OpenQASM spec.
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if `bits` contained duplicated bits.
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if `bits` contained bits of an incorrect type.
## Attributes
### instances\_counter
<Attribute id="qiskit.circuit.AncillaRegister.instances_counter" attributeValue="count(0)" />
### name
<Attribute id="qiskit.circuit.AncillaRegister.name">
Get the register name.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.AncillaRegister.prefix" attributeValue="'a'" />
### size
<Attribute id="qiskit.circuit.AncillaRegister.size">
Get the register size.
</Attribute>
## Methods
### index
<Function id="qiskit.circuit.AncillaRegister.index" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/register.py#L183-L191" signature="index(bit)">
Find the index of the provided bit within this register.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.AncillaRegister.mdx
|
---
title: AnnotatedOperation
description: API reference for qiskit.circuit.AnnotatedOperation
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.AnnotatedOperation
---
# AnnotatedOperation
<Class id="qiskit.circuit.AnnotatedOperation" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/annotated_operation.py#L59-L199" signature="qiskit.circuit.AnnotatedOperation(base_op, modifiers)" modifiers="class">
Bases: [`Operation`](qiskit.circuit.Operation "qiskit.circuit.operation.Operation")
Annotated operation.
Create a new AnnotatedOperation.
An βannotated operationβ allows to add a list of modifiers to the βbaseβ operation. For now, the only supported modifiers are of types [`InverseModifier`](qiskit.circuit.InverseModifier "qiskit.circuit.InverseModifier"), [`ControlModifier`](qiskit.circuit.ControlModifier "qiskit.circuit.ControlModifier") and [`PowerModifier`](qiskit.circuit.PowerModifier "qiskit.circuit.PowerModifier").
An annotated operation can be viewed as an extension of [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate") (which also allows adding control to the base operation). However, an important difference is that the circuit definition of an annotated operation is not constructed when the operation is declared, and instead happens during transpilation, specifically during the [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis "qiskit.transpiler.passes.HighLevelSynthesis") transpiler pass.
An annotated operation can be also viewed as a βhigher-levelβ or βmore abstractβ object that can be added to a quantum circuit. This enables writing transpiler optimization passes that make use of this higher-level representation, for instance removing a gate that is immediately followed by its inverse.
**Parameters**
* **base\_op** ([*Operation*](qiskit.circuit.Operation "qiskit.circuit.Operation")) β base operation being modified
* **modifiers** (*Union\[Modifier, List\[Modifier]]*) β ordered list of modifiers. Supported modifiers include `InverseModifier`, `ControlModifier` and `PowerModifier`.
Examples:
```python
op1 = AnnotatedOperation(SGate(), [InverseModifier(), ControlModifier(2)])
op2_inner = AnnotatedGate(SGate(), InverseModifier())
op2 = AnnotatedGate(op2_inner, ControlModifier(2))
```
Both op1 and op2 are semantically equivalent to an `SGate()` which is first inverted and then controlled by 2 qubits.
## Attributes
### name
<Attribute id="qiskit.circuit.AnnotatedOperation.name">
Unique string identifier for operation type.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.AnnotatedOperation.num_clbits">
Number of classical bits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.AnnotatedOperation.num_qubits">
Number of qubits.
</Attribute>
## Methods
### control
<Function id="qiskit.circuit.AnnotatedOperation.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/annotated_operation.py#L155-L182" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=True)">
Return the controlled version of itself.
Implemented as an annotated operation, see [`AnnotatedOperation`](#qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of controls to add to gate (default: `1`)
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β ignored (used for consistency with other control methods)
* **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β The control state in decimal or as a bitstring (e.g. `'111'`). If `None`, use `2**num_ctrl_qubits-1`.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β ignored (used for consistency with other control methods)
**Returns**
Controlled version of the given operation.
**Return type**
[AnnotatedOperation](#qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation")
</Function>
### copy
<Function id="qiskit.circuit.AnnotatedOperation.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/annotated_operation.py#L130-L132" signature="copy()">
Return a copy of the [`AnnotatedOperation`](#qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Return type**
[*AnnotatedOperation*](#qiskit.circuit.AnnotatedOperation "qiskit.circuit.annotated_operation.AnnotatedOperation")
</Function>
### inverse
<Function id="qiskit.circuit.AnnotatedOperation.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/annotated_operation.py#L184-L199" signature="inverse(annotated=True)">
Return the inverse version of itself.
Implemented as an annotated operation, see [`AnnotatedOperation`](#qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β ignored (used for consistency with other inverse methods)
**Returns**
Inverse version of the given operation.
</Function>
### to\_matrix
<Function id="qiskit.circuit.AnnotatedOperation.to_matrix" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/annotated_operation.py#L134-L153" signature="to_matrix()">
Return a matrix representation (allowing to construct Operator).
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.AnnotatedOperation.mdx
|
---
title: Bit
description: API reference for qiskit.circuit.Bit
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.Bit
---
# Bit
<Class id="qiskit.circuit.Bit" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/bit.py#L21-L95" signature="qiskit.circuit.Bit(register=None, index=None)" modifiers="class">
Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.12)")
Implement a generic bit.
<Admonition title="Note" type="note">
This class should not be instantiated directly. This is just a superclass for [`Clbit`](qiskit.circuit.Clbit "qiskit.circuit.Clbit") and [`Qubit`](qiskit.circuit.Qubit "qiskit.circuit.Qubit").
</Admonition>
Create a new generic bit.
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.Bit.mdx
|
---
title: BreakLoopOp
description: API reference for qiskit.circuit.BreakLoopOp
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.BreakLoopOp
---
# BreakLoopOp
<Class id="qiskit.circuit.BreakLoopOp" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/break_loop.py#L21-L47" signature="qiskit.circuit.BreakLoopOp(num_qubits, num_clbits, label=None)" modifiers="class">
Bases: [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.instruction.Instruction")
A circuit operation which, when encountered, jumps to the end of the nearest enclosing loop.
**Circuit symbol:**
```python
ββββββββββββββββ
q_0: β€0 β
β β
q_1: β€1 β
β break_loop β
q_2: β€2 β
β β
c_0: β‘0 β
ββββββββββββββββ
```
Create a new instruction.
**Parameters**
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β instruction name
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs clbit width
* **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*|*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")*]*) β list of parameters
* **duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *or*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β instructionβs duration. it must be integer if `unit` is βdtβ
* **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β time unit of duration
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *or None*) β An optional label for identifying the instruction.
**Raises**
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β when the register is not in the correct format.
* [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.12)") β when the optional label is provided, but it is not a string.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.BreakLoopOp.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.BreakLoopOp.base_class "qiskit.circuit.BreakLoopOp.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that [`Instruction.name`](qiskit.circuit.Instruction#name "qiskit.circuit.Instruction.name") should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.BreakLoopOp.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.BreakLoopOp.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.BreakLoopOp.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.BreakLoopOp.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.BreakLoopOp.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.BreakLoopOp.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.BreakLoopOp.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.BreakLoopOp.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.BreakLoopOp.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.BreakLoopOp.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.BreakLoopOp.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.BreakLoopOp.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.BreakLoopOp.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.BreakLoopOp.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.BreakLoopOp.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L535-L564" signature="broadcast_arguments(qargs, cargs)">
Validation of the arguments.
**Parameters**
* **qargs** (*List*) β List of quantum bit arguments.
* **cargs** (*List*) β List of classical bit arguments.
**Yields**
*Tuple(List, List)* β A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
</Function>
### c\_if
<Function id="qiskit.circuit.BreakLoopOp.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L479-L497" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### copy
<Function id="qiskit.circuit.BreakLoopOp.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### inverse
<Function id="qiskit.circuit.BreakLoopOp.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L422-L477" signature="inverse(annotated=False)">
Invert this instruction.
If annotated is False, the inverse instruction is implemented as a fresh instruction with the recursively inverted definition.
If annotated is True, the inverse instruction is implemented as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation"), and corresponds to the given instruction annotated with the βinverse modifierβ.
Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) In particular, they can choose how to handle the argument `annotated` which may include ignoring it and always returning a concrete gate class if the inverse is defined as a standard gate.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β if set to True the output inverse gate will be returned as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Returns**
The inverse operation.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the instruction is not composite and an inverse has not been implemented for it.
</Function>
### is\_parameterized
<Function id="qiskit.circuit.BreakLoopOp.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### repeat
<Function id="qiskit.circuit.BreakLoopOp.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### reverse\_ops
<Function id="qiskit.circuit.BreakLoopOp.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### soft\_compare
<Function id="qiskit.circuit.BreakLoopOp.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### to\_mutable
<Function id="qiskit.circuit.BreakLoopOp.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.BreakLoopOp.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L289-L291" signature="validate_parameter(parameter)">
Instruction parameters has no validation or normalization.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.BreakLoopOp.mdx
|
---
title: CircuitInstruction
description: API reference for qiskit.circuit.CircuitInstruction
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.CircuitInstruction
---
# CircuitInstruction
<Class id="qiskit.circuit.CircuitInstruction" isDedicatedPage={true} signature="qiskit.circuit.CircuitInstruction" modifiers="class">
Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.12)")
A single instruction in a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"), comprised of the [`operation`](#qiskit.circuit.CircuitInstruction.operation "qiskit.circuit.CircuitInstruction.operation") and various operands.
<Admonition title="Note" type="note">
There is some possible confusion in the names of this class, [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction"), and [`Operation`](qiskit.circuit.Operation "qiskit.circuit.Operation"), and this classβs attribute [`operation`](#qiskit.circuit.CircuitInstruction.operation "qiskit.circuit.CircuitInstruction.operation"). Our preferred terminology is by analogy to assembly languages, where an βinstructionβ is made up of an βoperationβ and its βoperandsβ.
Historically, [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") came first, and originally contained the qubits it operated on and any parameters, so it was a true βinstructionβ. Over time, [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") became responsible for tracking qubits and clbits, and the class became better described as an βoperationβ. Changing the name of such a core object would be a very unpleasant API break for users, and so we have stuck with it.
This class was created to provide a formal βinstructionβ context object in `QuantumCircuit.data`, which had long been made of ad-hoc tuples. With this, and the advent of the [`Operation`](qiskit.circuit.Operation "qiskit.circuit.Operation") interface for adding more complex objects to circuits, we took the opportunity to correct the historical naming. For the time being, this leads to an awkward case where [`CircuitInstruction.operation`](#qiskit.circuit.CircuitInstruction.operation "qiskit.circuit.CircuitInstruction.operation") is often an [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") instance ([`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") implements the [`Operation`](qiskit.circuit.Operation "qiskit.circuit.Operation") interface), but as the [`Operation`](qiskit.circuit.Operation "qiskit.circuit.Operation") interface gains more use, this confusion will hopefully abate.
</Admonition>
<Admonition title="Warning" type="caution">
This is a lightweight internal class and there is minimal error checking; you must respect the type hints when using it. It is the userβs responsibility to ensure that direct mutations of the object do not invalidate the types, nor the restrictions placed on it by its context. Typically this will mean, for example, that [`qubits`](#qiskit.circuit.CircuitInstruction.qubits "qiskit.circuit.CircuitInstruction.qubits") must be a sequence of distinct items, with no duplicates.
</Admonition>
## Attributes
### clbits
<Attribute id="qiskit.circuit.CircuitInstruction.clbits">
A sequence of the classical bits that this operation reads from or writes to.
</Attribute>
### operation
<Attribute id="qiskit.circuit.CircuitInstruction.operation">
The logical operation that this instruction represents an execution of.
</Attribute>
### qubits
<Attribute id="qiskit.circuit.CircuitInstruction.qubits">
A sequence of the qubits that the operation is applied to.
</Attribute>
## Methods
### copy
<Function id="qiskit.circuit.CircuitInstruction.copy" signature="copy()">
Returns a shallow copy.
**Returns**
The shallow copy.
**Return type**
[CircuitInstruction](#qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")
</Function>
### replace
<Function id="qiskit.circuit.CircuitInstruction.replace" signature="replace(operation=None, qubits=None, clbits=None)">
Creates a shallow copy with the given fields replaced.
**Returns**
A new instance with the given fields replaced.
**Return type**
[CircuitInstruction](#qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.CircuitInstruction.mdx
|
---
title: BooleanExpression
description: API reference for qiskit.circuit.classicalfunction.BooleanExpression
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.classicalfunction.BooleanExpression
---
# BooleanExpression
<Class id="qiskit.circuit.classicalfunction.BooleanExpression" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalfunction/boolean_expression.py#L23-L129" signature="qiskit.circuit.classicalfunction.BooleanExpression(expression, name=None, var_order=None)" modifiers="class">
Bases: `ClassicalElement`
The Boolean Expression gate.
**Parameters**
* **expression** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The logical expression string.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Optional. Instruction gate name. Otherwise part of the expression is going to be used.
* **var\_order** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β A list with the order in which variables will be created. (default: by appearance)
## Attributes
### base\_class
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.classicalfunction.BooleanExpression.base_class "qiskit.circuit.classicalfunction.BooleanExpression.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.classicalfunction.BooleanExpression.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L169-L226" signature="broadcast_arguments(qargs, cargs)">
Validation and handling of the arguments and its relationship.
For example, `cx([q[0],q[1]], q[2])` means `cx(q[0], q[2]); cx(q[1], q[2])`. This method yields the arguments in the right grouping. In the given example:
```python
in: [[q[0],q[1]], q[2]],[]
outs: [q[0], q[2]], []
[q[1], q[2]], []
```
The general broadcasting rules are:
> * If len(qargs) == 1:
>
> ```python
> [q[0], q[1]] -> [q[0]],[q[1]]
> ```
>
> * If len(qargs) == 2:
>
> ```python
> [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]], [q[1], r[1]]
> [[q[0]], [r[0], r[1]]] -> [q[0], r[0]], [q[0], r[1]]
> [[q[0], q[1]], [r[0]]] -> [q[0], r[0]], [q[1], r[0]]
> ```
>
> * If len(qargs) >= 3:
>
> ```python
> [q[0], q[1]], [r[0], r[1]], ...] -> [q[0], r[0], ...], [q[1], r[1], ...]
> ```
**Parameters**
* **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β List of quantum bit arguments.
* **cargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β List of classical bit arguments.
**Returns**
A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
**Return type**
[*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")\[[tuple](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.12)")\[[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)"), [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")]]
</Function>
### c\_if
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L479-L497" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### control
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L89-L126" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False)">
Return the controlled version of itself.
Implemented either as a controlled gate (ref. [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")) or as an annotated operation (ref. [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation")).
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of controls to add to gate (default: `1`)
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β optional gate label. Ignored if implemented as an annotated operation.
* **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β the control state in decimal or as a bitstring (e.g. `'111'`). If `None`, use `2**num_ctrl_qubits-1`.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β indicates whether the controlled gate can be implemented as an annotated gate.
**Returns**
Controlled version of the given operation.
**Raises**
[**QiskitError**](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") β unrecognized mode or invalid ctrl\_state
</Function>
### copy
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### from\_dimacs\_file
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.from_dimacs_file" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalfunction/boolean_expression.py#L101-L129" signature="from_dimacs_file(filename)" modifiers="classmethod">
Create a BooleanExpression from the string in the DIMACS format. :param filename: A file in DIMACS format.
**Returns**
A gate for the input string
**Return type**
[BooleanExpression](#qiskit.circuit.classicalfunction.BooleanExpression "qiskit.circuit.classicalfunction.BooleanExpression")
**Raises**
[**FileNotFoundError**](https://docs.python.org/3/library/exceptions.html#FileNotFoundError "(in Python v3.12)") β If filename is not found.
</Function>
### inverse
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L422-L477" signature="inverse(annotated=False)">
Invert this instruction.
If annotated is False, the inverse instruction is implemented as a fresh instruction with the recursively inverted definition.
If annotated is True, the inverse instruction is implemented as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation"), and corresponds to the given instruction annotated with the βinverse modifierβ.
Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) In particular, they can choose how to handle the argument `annotated` which may include ignoring it and always returning a concrete gate class if the inverse is defined as a standard gate.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β if set to True the output inverse gate will be returned as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Returns**
The inverse operation.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the instruction is not composite and an inverse has not been implemented for it.
</Function>
### is\_parameterized
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### power
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.power" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L65-L81" signature="power(exponent)">
Creates a unitary gate as gate^exponent.
**Parameters**
**exponent** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Gate^exponent
**Returns**
To which to\_matrix is self.to\_matrix^exponent.
**Return type**
.library.UnitaryGate
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If Gate is not unitary
</Function>
### repeat
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### reverse\_ops
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### simulate
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.simulate" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalfunction/boolean_expression.py#L50-L66" signature="simulate(bitstring)">
Evaluate the expression on a bitstring.
This evaluation is done classically.
**Parameters**
**bitstring** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The bitstring for which to evaluate.
**Returns**
result of the evaluation.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### soft\_compare
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### synth
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.synth" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalfunction/boolean_expression.py#L68-L95" signature="synth(registerless=True, synthesizer=None)">
Synthesis the logic network into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit").
**Parameters**
* **registerless** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Default `True`. If `False` uses the parameter names to create registers with those names. Otherwise, creates a circuit with a flat quantum register.
* **synthesizer** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.12)")*\[\[*[*BooleanExpression*](#qiskit.circuit.classicalfunction.BooleanExpression "qiskit.circuit.classicalfunction.boolean_expression.BooleanExpression")*],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")*] | None*) β A callable that takes self and returns a Tweedledum circuit.
**Returns**
A circuit implementing the logic network.
**Return type**
[QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")
</Function>
### to\_matrix
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.to_matrix" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L51-L63" signature="to_matrix()">
Return a Numpy.array for the gate unitary matrix.
**Returns**
if the Gate subclass has a matrix definition.
**Return type**
np.ndarray
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If a Gate subclass does not implement this method an exception will be raised when this base class method is called.
</Function>
### to\_mutable
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.classicalfunction.BooleanExpression.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L228-L242" signature="validate_parameter(parameter)">
Gate parameters should be int, float, or ParameterExpression
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.classicalfunction.BooleanExpression.mdx
|
---
title: ClassicalFunction
description: API reference for qiskit.circuit.classicalfunction.ClassicalFunction
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.classicalfunction.ClassicalFunction
---
# ClassicalFunction
<Class id="qiskit.circuit.classicalfunction.ClassicalFunction" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalfunction/classicalfunction.py#L26-L173" signature="qiskit.circuit.classicalfunction.ClassicalFunction(source, name=None)" modifiers="class">
Bases: `ClassicalElement`
Represent a classical function and its logic network.
Creates a `ClassicalFunction` from Python source code in `source`.
The code should be a single function with types.
**Parameters**
* **source** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Python code with type hints.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Optional. Default: β*classicalfunction*β. ClassicalFunction name.
**Raises**
[**QiskitError**](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") β If source is not a string.
## Attributes
### args
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.args">
Returns the classicalfunction arguments
</Attribute>
### base\_class
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.classicalfunction.ClassicalFunction.base_class "qiskit.circuit.classicalfunction.ClassicalFunction.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.name">
Return the name.
</Attribute>
### network
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.network">
Returns the logical network
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.params">
return instruction params.
</Attribute>
### qregs
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.qregs">
The list of qregs used by the classicalfunction
</Attribute>
### scopes
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.scopes">
Returns the scope dict
</Attribute>
### truth\_table
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.truth_table">
Returns (and computes) the truth table
</Attribute>
### types
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.types">
Dumps a list of scopes with their variables and types.
**Returns**
A list of scopes as dicts, where key is the variable name and value is its type.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")([dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)"))
</Attribute>
### unit
<Attribute id="qiskit.circuit.classicalfunction.ClassicalFunction.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L169-L226" signature="broadcast_arguments(qargs, cargs)">
Validation and handling of the arguments and its relationship.
For example, `cx([q[0],q[1]], q[2])` means `cx(q[0], q[2]); cx(q[1], q[2])`. This method yields the arguments in the right grouping. In the given example:
```python
in: [[q[0],q[1]], q[2]],[]
outs: [q[0], q[2]], []
[q[1], q[2]], []
```
The general broadcasting rules are:
> * If len(qargs) == 1:
>
> ```python
> [q[0], q[1]] -> [q[0]],[q[1]]
> ```
>
> * If len(qargs) == 2:
>
> ```python
> [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]], [q[1], r[1]]
> [[q[0]], [r[0], r[1]]] -> [q[0], r[0]], [q[0], r[1]]
> [[q[0], q[1]], [r[0]]] -> [q[0], r[0]], [q[1], r[0]]
> ```
>
> * If len(qargs) >= 3:
>
> ```python
> [q[0], q[1]], [r[0], r[1]], ...] -> [q[0], r[0], ...], [q[1], r[1], ...]
> ```
**Parameters**
* **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β List of quantum bit arguments.
* **cargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β List of classical bit arguments.
**Returns**
A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
**Return type**
[*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")\[[tuple](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.12)")\[[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)"), [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")]]
</Function>
### c\_if
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L479-L497" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### compile
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.compile" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalfunction/classicalfunction.py#L55-L62" signature="compile()">
Parses and creates the logical circuit
</Function>
### control
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L89-L126" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False)">
Return the controlled version of itself.
Implemented either as a controlled gate (ref. [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")) or as an annotated operation (ref. [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation")).
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of controls to add to gate (default: `1`)
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β optional gate label. Ignored if implemented as an annotated operation.
* **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β the control state in decimal or as a bitstring (e.g. `'111'`). If `None`, use `2**num_ctrl_qubits-1`.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β indicates whether the controlled gate can be implemented as an annotated gate.
**Returns**
Controlled version of the given operation.
**Raises**
[**QiskitError**](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") β unrecognized mode or invalid ctrl\_state
</Function>
### copy
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### inverse
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L422-L477" signature="inverse(annotated=False)">
Invert this instruction.
If annotated is False, the inverse instruction is implemented as a fresh instruction with the recursively inverted definition.
If annotated is True, the inverse instruction is implemented as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation"), and corresponds to the given instruction annotated with the βinverse modifierβ.
Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) In particular, they can choose how to handle the argument `annotated` which may include ignoring it and always returning a concrete gate class if the inverse is defined as a standard gate.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β if set to True the output inverse gate will be returned as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Returns**
The inverse operation.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the instruction is not composite and an inverse has not been implemented for it.
</Function>
### is\_parameterized
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### power
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.power" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L65-L81" signature="power(exponent)">
Creates a unitary gate as gate^exponent.
**Parameters**
**exponent** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Gate^exponent
**Returns**
To which to\_matrix is self.to\_matrix^exponent.
**Return type**
.library.UnitaryGate
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If Gate is not unitary
</Function>
### repeat
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### reverse\_ops
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### simulate
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.simulate" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalfunction/classicalfunction.py#L98-L111" signature="simulate(bitstring)">
Evaluate the expression on a bitstring.
This evaluation is done classically.
**Parameters**
**bitstring** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The bitstring for which to evaluate.
**Returns**
result of the evaluation.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### simulate\_all
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.simulate_all" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalfunction/classicalfunction.py#L113-L125" signature="simulate_all()">
Returns a truth table.
**Returns**
a bitstring with a truth table
**Return type**
[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")
</Function>
### soft\_compare
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### synth
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.synth" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalfunction/classicalfunction.py#L136-L161" signature="synth(registerless=True, synthesizer=None)">
Synthesis the logic network into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit").
**Parameters**
* **registerless** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Default `True`. If `False` uses the parameter names to create
* **Otherwise** (*registers with those names.*) β
* **register.** (*creates a circuit with a flat quantum*) β
* **synthesizer** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.12)")*\[\[ClassicalElement],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")*] | None*) β Optional. If None tweedledumβs pkrm\_synth is used.
**Returns**
A circuit implementing the logic network.
**Return type**
[QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")
</Function>
### to\_matrix
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.to_matrix" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L51-L63" signature="to_matrix()">
Return a Numpy.array for the gate unitary matrix.
**Returns**
if the Gate subclass has a matrix definition.
**Return type**
np.ndarray
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If a Gate subclass does not implement this method an exception will be raised when this base class method is called.
</Function>
### to\_mutable
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.classicalfunction.ClassicalFunction.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L228-L242" signature="validate_parameter(parameter)">
Gate parameters should be int, float, or ParameterExpression
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.classicalfunction.ClassicalFunction.mdx
|
---
title: ClassicalFunctionCompilerTypeError
description: API reference for qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError
in_page_toc_min_heading_level: 1
python_api_type: exception
python_api_name: qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError
---
<span id="qiskit-circuit-classicalfunction-classicalfunctioncompilertypeerror" />
# qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError
<Class id="qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalfunction/exceptions.py#L31-L35" signature="qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError(*message)" modifiers="exception">
ClassicalFunction compiler type error. The classicalfunction function fails at type checking time.
Set the error message.
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError.mdx
|
---
title: ClassicalFunctionParseError
description: API reference for qiskit.circuit.classicalfunction.ClassicalFunctionParseError
in_page_toc_min_heading_level: 1
python_api_type: exception
python_api_name: qiskit.circuit.classicalfunction.ClassicalFunctionParseError
---
<span id="qiskit-circuit-classicalfunction-classicalfunctionparseerror" />
# qiskit.circuit.classicalfunction.ClassicalFunctionParseError
<Class id="qiskit.circuit.classicalfunction.ClassicalFunctionParseError" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalfunction/exceptions.py#L24-L28" signature="qiskit.circuit.classicalfunction.ClassicalFunctionParseError(*message)" modifiers="exception">
ClassicalFunction compiler parse error. The classicalfunction function fails at parsing time.
Set the error message.
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.classicalfunction.ClassicalFunctionParseError.mdx
|
---
title: ClassicalRegister
description: API reference for qiskit.circuit.ClassicalRegister
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.ClassicalRegister
---
# ClassicalRegister
<Class id="qiskit.circuit.ClassicalRegister" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalregister.py#L50-L57" signature="qiskit.circuit.ClassicalRegister(size=None, name=None, bits=None)" modifiers="class">
Bases: [`Register`](qiskit.circuit.Register "qiskit.circuit.register.Register")
Implement a classical register.
Create a new generic register.
Either the `size` or the `bits` argument must be provided. If `size` is not None, the register will be pre-populated with bits of the correct type.
**Parameters**
* **size** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Optional. The number of bits to include in the register.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Optional. The name of the register. If not provided, a unique name will be auto-generated from the register type.
* **bits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*Bit*](qiskit.circuit.Bit "qiskit.circuit.Bit")*]*) β Optional. A list of Bit() instances to be used to populate the register.
**Raises**
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if both the `size` and `bits` arguments are provided, or if neither are.
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if `size` is not valid.
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if `name` is not a valid name according to the OpenQASM spec.
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if `bits` contained duplicated bits.
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if `bits` contained bits of an incorrect type.
## Attributes
### instances\_counter
<Attribute id="qiskit.circuit.ClassicalRegister.instances_counter" attributeValue="count(0)" />
### name
<Attribute id="qiskit.circuit.ClassicalRegister.name">
Get the register name.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.ClassicalRegister.prefix" attributeValue="'c'" />
### size
<Attribute id="qiskit.circuit.ClassicalRegister.size">
Get the register size.
</Attribute>
## Methods
### index
<Function id="qiskit.circuit.ClassicalRegister.index" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/register.py#L183-L191" signature="index(bit)">
Find the index of the provided bit within this register.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.ClassicalRegister.mdx
|
---
title: Clbit
description: API reference for qiskit.circuit.Clbit
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.Clbit
---
# Clbit
<Class id="qiskit.circuit.Clbit" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/classicalregister.py#L26-L47" signature="qiskit.circuit.Clbit(register=None, index=None)" modifiers="class">
Bases: [`Bit`](qiskit.circuit.Bit "qiskit.circuit.bit.Bit")
Implement a classical bit.
Creates a classical bit.
**Parameters**
* **register** ([*ClassicalRegister*](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister")) β Optional. A classical register containing the bit.
* **index** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Optional. The index of the bit in its containing register.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the provided register is not a valid [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister")
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.Clbit.mdx
|
---
title: CommutationChecker
description: API reference for qiskit.circuit.CommutationChecker
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.CommutationChecker
---
# CommutationChecker
<Class id="qiskit.circuit.CommutationChecker" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/commutation_checker.py#L33-L183" signature="qiskit.circuit.CommutationChecker(standard_gate_commutations=None, cache_max_entries=1000000)" modifiers="class">
Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.12)")
This code is essentially copy-pasted from commutative\_analysis.py. This code cleverly hashes commutativity and non-commutativity results between DAG nodes and seems quite efficient for large Clifford circuits. They may be other possible efficiency improvements: using rule-based commutativity analysis, evicting from the cache less useful entries, etc.
## Methods
### check\_commutation\_entries
<Function id="qiskit.circuit.CommutationChecker.check_commutation_entries" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/commutation_checker.py#L141-L183" signature="check_commutation_entries(first_op, first_qargs, second_op, second_qargs)">
Returns stored commutation relation if any
**Parameters**
* **first\_op** ([*Operation*](qiskit.circuit.Operation "qiskit.circuit.operation.Operation")) β first operation.
* **first\_qargs** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")) β first operationβs qubits.
* **second\_op** ([*Operation*](qiskit.circuit.Operation "qiskit.circuit.operation.Operation")) β second operation.
* **second\_qargs** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")) β second operationβs qubits.
**Returns**
True if the gates commute and false if it is not the case.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### clear\_cached\_commutations
<Function id="qiskit.circuit.CommutationChecker.clear_cached_commutations" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/commutation_checker.py#L134-L139" signature="clear_cached_commutations()">
Clears the dictionary holding cached commutations
</Function>
### commute
<Function id="qiskit.circuit.CommutationChecker.commute" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/commutation_checker.py#L56-L128" signature="commute(op1, qargs1, cargs1, op2, qargs2, cargs2, max_num_qubits=3)">
Checks if two Operations commute. The return value of True means that the operations truly commute, and the return value of False means that either the operations do not commute or that the commutation check was skipped (for example, when the operations have conditions or have too many qubits).
**Parameters**
* **op1** ([*Operation*](qiskit.circuit.Operation "qiskit.circuit.operation.Operation")) β first operation.
* **qargs1** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")) β first operationβs qubits.
* **cargs1** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")) β first operationβs clbits.
* **op2** ([*Operation*](qiskit.circuit.Operation "qiskit.circuit.operation.Operation")) β second operation.
* **qargs2** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")) β second operationβs qubits.
* **cargs2** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")) β second operationβs clbits.
* **max\_num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β the maximum number of qubits to consider, the check may be skipped if the number of qubits for either operation exceeds this amount.
**Returns**
whether two operations commute.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### num\_cached\_entries
<Function id="qiskit.circuit.CommutationChecker.num_cached_entries" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/commutation_checker.py#L130-L132" signature="num_cached_entries()">
Returns number of cached entries
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.CommutationChecker.mdx
|
---
title: ContinueLoopOp
description: API reference for qiskit.circuit.ContinueLoopOp
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.ContinueLoopOp
---
# ContinueLoopOp
<Class id="qiskit.circuit.ContinueLoopOp" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/continue_loop.py#L21-L47" signature="qiskit.circuit.ContinueLoopOp(num_qubits, num_clbits, label=None)" modifiers="class">
Bases: [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.instruction.Instruction")
A circuit operation which, when encountered, moves to the next iteration of the nearest enclosing loop.
<Admonition title="Note" type="note">
Can be inserted only within the body of a loop op, and must span the full width of that block.
</Admonition>
**Circuit symbol:**
```python
βββββββββββββββββββ
q_0: β€0 β
β β
q_1: β€1 β
β continue_loop β
q_2: β€2 β
β β
c_0: β‘0 β
βββββββββββββββββββ
```
Create a new instruction.
**Parameters**
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β instruction name
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs clbit width
* **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*|*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")*]*) β list of parameters
* **duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *or*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β instructionβs duration. it must be integer if `unit` is βdtβ
* **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β time unit of duration
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *or None*) β An optional label for identifying the instruction.
**Raises**
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β when the register is not in the correct format.
* [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.12)") β when the optional label is provided, but it is not a string.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.ContinueLoopOp.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.ContinueLoopOp.base_class "qiskit.circuit.ContinueLoopOp.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that [`Instruction.name`](qiskit.circuit.Instruction#name "qiskit.circuit.Instruction.name") should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.ContinueLoopOp.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.ContinueLoopOp.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.ContinueLoopOp.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.ContinueLoopOp.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.ContinueLoopOp.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.ContinueLoopOp.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.ContinueLoopOp.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.ContinueLoopOp.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.ContinueLoopOp.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.ContinueLoopOp.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.ContinueLoopOp.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.ContinueLoopOp.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.ContinueLoopOp.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.ContinueLoopOp.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.ContinueLoopOp.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L535-L564" signature="broadcast_arguments(qargs, cargs)">
Validation of the arguments.
**Parameters**
* **qargs** (*List*) β List of quantum bit arguments.
* **cargs** (*List*) β List of classical bit arguments.
**Yields**
*Tuple(List, List)* β A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
</Function>
### c\_if
<Function id="qiskit.circuit.ContinueLoopOp.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L479-L497" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### copy
<Function id="qiskit.circuit.ContinueLoopOp.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### inverse
<Function id="qiskit.circuit.ContinueLoopOp.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L422-L477" signature="inverse(annotated=False)">
Invert this instruction.
If annotated is False, the inverse instruction is implemented as a fresh instruction with the recursively inverted definition.
If annotated is True, the inverse instruction is implemented as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation"), and corresponds to the given instruction annotated with the βinverse modifierβ.
Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) In particular, they can choose how to handle the argument `annotated` which may include ignoring it and always returning a concrete gate class if the inverse is defined as a standard gate.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β if set to True the output inverse gate will be returned as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Returns**
The inverse operation.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the instruction is not composite and an inverse has not been implemented for it.
</Function>
### is\_parameterized
<Function id="qiskit.circuit.ContinueLoopOp.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### repeat
<Function id="qiskit.circuit.ContinueLoopOp.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### reverse\_ops
<Function id="qiskit.circuit.ContinueLoopOp.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### soft\_compare
<Function id="qiskit.circuit.ContinueLoopOp.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### to\_mutable
<Function id="qiskit.circuit.ContinueLoopOp.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.ContinueLoopOp.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L289-L291" signature="validate_parameter(parameter)">
Instruction parameters has no validation or normalization.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.ContinueLoopOp.mdx
|
---
title: ControlFlowOp
description: API reference for qiskit.circuit.ControlFlowOp
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.ControlFlowOp
---
# ControlFlowOp
<Class id="qiskit.circuit.ControlFlowOp" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/control_flow.py#L26-L45" signature="qiskit.circuit.ControlFlowOp(name, num_qubits, num_clbits, params, duration=None, unit='dt', label=None)" modifiers="class">
Bases: [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.instruction.Instruction"), [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC "(in Python v3.12)")
Abstract class to encapsulate all control flow operations.
Create a new instruction.
**Parameters**
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β instruction name
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs clbit width
* **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*|*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")*]*) β list of parameters
* **duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *or*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β instructionβs duration. it must be integer if `unit` is βdtβ
* **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β time unit of duration
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *or None*) β An optional label for identifying the instruction.
**Raises**
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β when the register is not in the correct format.
* [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.12)") β when the optional label is provided, but it is not a string.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.ControlFlowOp.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.ControlFlowOp.base_class "qiskit.circuit.ControlFlowOp.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that [`Instruction.name`](qiskit.circuit.Instruction#name "qiskit.circuit.Instruction.name") should be a more suitable discriminator in most situations.
</Attribute>
### blocks
<Attribute id="qiskit.circuit.ControlFlowOp.blocks">
Tuple of QuantumCircuits which may be executed as part of the execution of this ControlFlowOp. May be parameterized by a loop parameter to be resolved at run time.
</Attribute>
### condition
<Attribute id="qiskit.circuit.ControlFlowOp.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.ControlFlowOp.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.ControlFlowOp.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.ControlFlowOp.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.ControlFlowOp.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.ControlFlowOp.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.ControlFlowOp.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.ControlFlowOp.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.ControlFlowOp.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.ControlFlowOp.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.ControlFlowOp.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.ControlFlowOp.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.ControlFlowOp.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.ControlFlowOp.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.ControlFlowOp.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L535-L564" signature="broadcast_arguments(qargs, cargs)">
Validation of the arguments.
**Parameters**
* **qargs** (*List*) β List of quantum bit arguments.
* **cargs** (*List*) β List of classical bit arguments.
**Yields**
*Tuple(List, List)* β A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
</Function>
### c\_if
<Function id="qiskit.circuit.ControlFlowOp.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L479-L497" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### copy
<Function id="qiskit.circuit.ControlFlowOp.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### inverse
<Function id="qiskit.circuit.ControlFlowOp.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L422-L477" signature="inverse(annotated=False)">
Invert this instruction.
If annotated is False, the inverse instruction is implemented as a fresh instruction with the recursively inverted definition.
If annotated is True, the inverse instruction is implemented as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation"), and corresponds to the given instruction annotated with the βinverse modifierβ.
Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) In particular, they can choose how to handle the argument `annotated` which may include ignoring it and always returning a concrete gate class if the inverse is defined as a standard gate.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β if set to True the output inverse gate will be returned as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Returns**
The inverse operation.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the instruction is not composite and an inverse has not been implemented for it.
</Function>
### is\_parameterized
<Function id="qiskit.circuit.ControlFlowOp.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### repeat
<Function id="qiskit.circuit.ControlFlowOp.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### replace\_blocks
<Function id="qiskit.circuit.ControlFlowOp.replace_blocks" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/control_flow.py#L37-L45" signature="replace_blocks(blocks)" modifiers="abstract">
Replace blocks and return new instruction. :param blocks: Tuple of QuantumCircuits to replace in instruction.
**Returns**
New ControlFlowOp with replaced blocks.
**Return type**
[ControlFlowOp](#qiskit.circuit.ControlFlowOp "qiskit.circuit.ControlFlowOp")
</Function>
### reverse\_ops
<Function id="qiskit.circuit.ControlFlowOp.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### soft\_compare
<Function id="qiskit.circuit.ControlFlowOp.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### to\_mutable
<Function id="qiskit.circuit.ControlFlowOp.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.ControlFlowOp.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L289-L291" signature="validate_parameter(parameter)">
Instruction parameters has no validation or normalization.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.ControlFlowOp.mdx
|
---
title: ControlledGate
description: API reference for qiskit.circuit.ControlledGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.ControlledGate
---
# ControlledGate
<Class id="qiskit.circuit.ControlledGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlledgate.py#L28-L274" signature="qiskit.circuit.ControlledGate(name, num_qubits, params, label=None, num_ctrl_qubits=1, definition=None, ctrl_state=None, base_gate=None, duration=None, unit=None, *, _base_label=None)" modifiers="class">
Bases: [`Gate`](qiskit.circuit.Gate "qiskit.circuit.gate.Gate")
Controlled unitary gate.
Create a new ControlledGate. In the new gate the first `num_ctrl_qubits` of the gate are the controls.
**Parameters**
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The name of the gate.
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β The number of qubits the gate acts on.
* **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β A list of parameters for the gate.
* **label** (*Optional\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]*) β An optional label for the gate.
* **num\_ctrl\_qubits** (*Optional\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]*) β Number of control qubits.
* **definition** (*Optional\['QuantumCircuit']*) β A list of gate rules for implementing this gate. The elements of the list are tuples of ([`Gate()`](qiskit.circuit.Gate "qiskit.circuit.Gate"), \[qubit\_list], \[clbit\_list]).
* **ctrl\_state** (*Optional\[Union\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*,* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]]*) β The control state in decimal or as a bitstring (e.g. β111β). If specified as a bitstring the length must equal num\_ctrl\_qubits, MSB on left. If None, use 2\*\*num\_ctrl\_qubits-1.
* **base\_gate** (*Optional\[*[*Gate*](qiskit.circuit.Gate "qiskit.circuit.Gate")*]*) β Gate object to be controlled.
**Raises**
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If `num_ctrl_qubits` >= `num_qubits`.
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β ctrl\_state \< 0 or ctrl\_state > 2\*\*num\_ctrl\_qubits.
Examples:
Create a controlled standard gate and apply it to a circuit.
```python
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
c3h_gate = HGate().control(2)
qc.append(c3h_gate, qr)
qc.draw('mpl')
```

Create a controlled custom gate and apply it to a circuit.
```python
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
```

## Attributes
### base\_class
<Attribute id="qiskit.circuit.ControlledGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.ControlledGate.base_class "qiskit.circuit.ControlledGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that [`Instruction.name`](qiskit.circuit.Instruction#name "qiskit.circuit.Instruction.name") should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.ControlledGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.ControlledGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.ControlledGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.ControlledGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.ControlledGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.ControlledGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.ControlledGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.ControlledGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.ControlledGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.ControlledGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.ControlledGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.ControlledGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.ControlledGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.ControlledGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.ControlledGate.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.ControlledGate.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.ControlledGate.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L169-L226" signature="broadcast_arguments(qargs, cargs)">
Validation and handling of the arguments and its relationship.
For example, `cx([q[0],q[1]], q[2])` means `cx(q[0], q[2]); cx(q[1], q[2])`. This method yields the arguments in the right grouping. In the given example:
```python
in: [[q[0],q[1]], q[2]],[]
outs: [q[0], q[2]], []
[q[1], q[2]], []
```
The general broadcasting rules are:
> * If len(qargs) == 1:
>
> ```python
> [q[0], q[1]] -> [q[0]],[q[1]]
> ```
>
> * If len(qargs) == 2:
>
> ```python
> [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]], [q[1], r[1]]
> [[q[0]], [r[0], r[1]]] -> [q[0], r[0]], [q[0], r[1]]
> [[q[0], q[1]], [r[0]]] -> [q[0], r[0]], [q[1], r[0]]
> ```
>
> * If len(qargs) >= 3:
>
> ```python
> [q[0], q[1]], [r[0], r[1]], ...] -> [q[0], r[0], ...], [q[1], r[1], ...]
> ```
**Parameters**
* **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β List of quantum bit arguments.
* **cargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β List of classical bit arguments.
**Returns**
A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
**Return type**
[*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")\[[tuple](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.12)")\[[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)"), [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")]]
</Function>
### c\_if
<Function id="qiskit.circuit.ControlledGate.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L479-L497" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### control
<Function id="qiskit.circuit.ControlledGate.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L89-L126" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False)">
Return the controlled version of itself.
Implemented either as a controlled gate (ref. [`ControlledGate`](#qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")) or as an annotated operation (ref. [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation")).
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of controls to add to gate (default: `1`)
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β optional gate label. Ignored if implemented as an annotated operation.
* **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β the control state in decimal or as a bitstring (e.g. `'111'`). If `None`, use `2**num_ctrl_qubits-1`.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β indicates whether the controlled gate can be implemented as an annotated gate.
**Returns**
Controlled version of the given operation.
**Raises**
[**QiskitError**](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") β unrecognized mode or invalid ctrl\_state
</Function>
### copy
<Function id="qiskit.circuit.ControlledGate.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### inverse
<Function id="qiskit.circuit.ControlledGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlledgate.py#L266-L274" signature="inverse(annotated=False)">
Invert this gate by calling inverse on the base gate.
**Return type**
ControlledGateβ | βAnnotatedOperation
</Function>
### is\_parameterized
<Function id="qiskit.circuit.ControlledGate.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### power
<Function id="qiskit.circuit.ControlledGate.power" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L65-L81" signature="power(exponent)">
Creates a unitary gate as gate^exponent.
**Parameters**
**exponent** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Gate^exponent
**Returns**
To which to\_matrix is self.to\_matrix^exponent.
**Return type**
.library.UnitaryGate
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If Gate is not unitary
</Function>
### repeat
<Function id="qiskit.circuit.ControlledGate.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### reverse\_ops
<Function id="qiskit.circuit.ControlledGate.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### soft\_compare
<Function id="qiskit.circuit.ControlledGate.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### to\_matrix
<Function id="qiskit.circuit.ControlledGate.to_matrix" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L51-L63" signature="to_matrix()">
Return a Numpy.array for the gate unitary matrix.
**Returns**
if the Gate subclass has a matrix definition.
**Return type**
np.ndarray
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If a Gate subclass does not implement this method an exception will be raised when this base class method is called.
</Function>
### to\_mutable
<Function id="qiskit.circuit.ControlledGate.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.ControlledGate.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L228-L242" signature="validate_parameter(parameter)">
Gate parameters should be int, float, or ParameterExpression
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.ControlledGate.mdx
|
---
title: ControlModifier
description: API reference for qiskit.circuit.ControlModifier
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.ControlModifier
---
# ControlModifier
<Class id="qiskit.circuit.ControlModifier" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/annotated_operation.py#L39-L49" signature="qiskit.circuit.ControlModifier(num_ctrl_qubits=0, ctrl_state=None)" modifiers="class">
Bases: `Modifier`
Control modifier: specifies that the operation is controlled by `num_ctrl_qubits` and has control state `ctrl_state`.
## Attributes
### ctrl\_state
<Attribute id="qiskit.circuit.ControlModifier.ctrl_state" attributeTypeHint="int | str | None" attributeValue="None" />
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.ControlModifier.num_ctrl_qubits" attributeTypeHint="int" attributeValue="0" />
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.ControlModifier.mdx
|
---
title: Delay
description: API reference for qiskit.circuit.Delay
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.Delay
---
# Delay
<Class id="qiskit.circuit.Delay" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/delay.py#L23-L104" signature="qiskit.circuit.Delay(duration, unit='dt')" modifiers="class">
Bases: [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.instruction.Instruction")
Do nothing and just delay/wait/idle for a specified duration.
Create new delay instruction.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.Delay.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.Delay.base_class "qiskit.circuit.Delay.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that [`Instruction.name`](qiskit.circuit.Instruction#name "qiskit.circuit.Instruction.name") should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.Delay.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.Delay.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.Delay.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.Delay.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.Delay.duration">
Get the duration of this delay.
</Attribute>
### label
<Attribute id="qiskit.circuit.Delay.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.Delay.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.Delay.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.Delay.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.Delay.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.Delay.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.Delay.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.Delay.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.Delay.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.Delay.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L169-L226" signature="broadcast_arguments(qargs, cargs)">
Validation and handling of the arguments and its relationship.
For example, `cx([q[0],q[1]], q[2])` means `cx(q[0], q[2]); cx(q[1], q[2])`. This method yields the arguments in the right grouping. In the given example:
```python
in: [[q[0],q[1]], q[2]],[]
outs: [q[0], q[2]], []
[q[1], q[2]], []
```
The general broadcasting rules are:
> * If len(qargs) == 1:
>
> ```python
> [q[0], q[1]] -> [q[0]],[q[1]]
> ```
>
> * If len(qargs) == 2:
>
> ```python
> [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]], [q[1], r[1]]
> [[q[0]], [r[0], r[1]]] -> [q[0], r[0]], [q[0], r[1]]
> [[q[0], q[1]], [r[0]]] -> [q[0], r[0]], [q[1], r[0]]
> ```
>
> * If len(qargs) >= 3:
>
> ```python
> [q[0], q[1]], [r[0], r[1]], ...] -> [q[0], r[0], ...], [q[1], r[1], ...]
> ```
**Parameters**
* **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β List of quantum bit arguments.
* **cargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β List of classical bit arguments.
**Returns**
A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
**Return type**
[*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")\[[tuple](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.12)")\[[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)"), [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")]]
</Function>
### c\_if
<Function id="qiskit.circuit.Delay.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/delay.py#L39-L40" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### copy
<Function id="qiskit.circuit.Delay.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### inverse
<Function id="qiskit.circuit.Delay.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/delay.py#L35-L37" signature="inverse(annotated=False)">
Special case. Return self.
</Function>
### is\_parameterized
<Function id="qiskit.circuit.Delay.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### repeat
<Function id="qiskit.circuit.Delay.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### reverse\_ops
<Function id="qiskit.circuit.Delay.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### soft\_compare
<Function id="qiskit.circuit.Delay.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### to\_matrix
<Function id="qiskit.circuit.Delay.to_matrix" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/delay.py#L56-L63" signature="to_matrix()">
Return a Numpy.array for the unitary matrix. This has been added to enable simulation without making delay a full Gate type.
**Returns**
matrix representation.
**Return type**
np.ndarray
</Function>
### to\_mutable
<Function id="qiskit.circuit.Delay.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.Delay.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/delay.py#L69-L104" signature="validate_parameter(parameter)">
Delay parameter (i.e. duration) must be int, float or ParameterExpression.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.Delay.mdx
|
---
title: EquivalenceLibrary
description: API reference for qiskit.circuit.EquivalenceLibrary
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.EquivalenceLibrary
---
# EquivalenceLibrary
<Class id="qiskit.circuit.EquivalenceLibrary" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/equivalence.py#L32-L267" signature="qiskit.circuit.EquivalenceLibrary(*, base=None)" modifiers="class">
Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.12)")
A library providing a one-way mapping of Gates to their equivalent implementations as QuantumCircuits.
Create a new equivalence library.
**Parameters**
**base** (*Optional\[*[*EquivalenceLibrary*](#qiskit.circuit.EquivalenceLibrary "qiskit.circuit.EquivalenceLibrary")*]*) β Base equivalence library to be referenced if an entry is not found in this library.
## Attributes
### graph
<Attribute id="qiskit.circuit.EquivalenceLibrary.graph">
Return graph representing the equivalence library data.
This property should be treated as read-only as it provides a reference to the internal state of the [`EquivalenceLibrary`](#qiskit.circuit.EquivalenceLibrary "qiskit.circuit.EquivalenceLibrary") object. If the graph returned by this property is mutated it could corrupt the the contents of the object. If you need to modify the output `PyDiGraph` be sure to make a copy prior to any modification.
**Returns**
A graph object with equivalence data in each node.
**Return type**
PyDiGraph
</Attribute>
## Methods
### add\_equivalence
<Function id="qiskit.circuit.EquivalenceLibrary.add_equivalence" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/equivalence.py#L76-L113" signature="add_equivalence(gate, equivalent_circuit)">
Add a new equivalence to the library. Future queries for the Gate will include the given circuit, in addition to all existing equivalences (including those from base).
Parameterized Gates (those including qiskit.circuit.Parameters in their Gate.params) can be marked equivalent to parameterized circuits, provided the parameters match.
**Parameters**
* **gate** ([*Gate*](qiskit.circuit.Gate "qiskit.circuit.Gate")) β A Gate instance.
* **equivalent\_circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")) β A circuit equivalently implementing the given Gate.
</Function>
### draw
<Function id="qiskit.circuit.EquivalenceLibrary.draw" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/equivalence.py#L199-L224" signature="draw(filename=None)">
Draws the equivalence relations available in the library.
**Parameters**
**filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β An optional path to write the output image to if specified this method will return None.
**Returns**
**Drawn equivalence library as an**
IPython SVG if in a jupyter notebook, or as a PIL.Image otherwise.
**Return type**
PIL.Image or IPython.display.SVG
**Raises**
[**InvalidFileError**](exceptions#qiskit.exceptions.InvalidFileError "qiskit.exceptions.InvalidFileError") β if filename is not valid.
</Function>
### get\_entry
<Function id="qiskit.circuit.EquivalenceLibrary.get_entry" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/equivalence.py#L156-L178" signature="get_entry(gate)">
Gets the set of QuantumCircuits circuits from the library which equivalently implement the given Gate.
Parameterized circuits will have their parameters replaced with the corresponding entries from Gate.params.
**Parameters**
**gate** ([*Gate*](qiskit.circuit.Gate "qiskit.circuit.Gate")) β A Gate instance.
**Returns**
**A list of equivalent QuantumCircuits. If empty,**
library contains no known decompositions of Gate.
Returned circuits will be ordered according to their insertion in the library, from earliest to latest, from top to base. The ordering of the StandardEquivalenceLibrary will not generally be consistent across Qiskit versions.
**Return type**
List\[[QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")]
</Function>
### has\_entry
<Function id="qiskit.circuit.EquivalenceLibrary.has_entry" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/equivalence.py#L115-L127" signature="has_entry(gate)">
Check if a library contains any decompositions for gate.
**Parameters**
**gate** ([*Gate*](qiskit.circuit.Gate "qiskit.circuit.Gate")) β A Gate instance.
**Returns**
**True if gate has a known decomposition in the library.**
False otherwise.
**Return type**
[Bool](circuit_classical#qiskit.circuit.classical.types.Bool "qiskit.circuit.classical.types.Bool")
</Function>
### keys
<Function id="qiskit.circuit.EquivalenceLibrary.keys" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/equivalence.py#L180-L186" signature="keys()">
Return list of keys to key to node index map.
**Returns**
Keys to the key to node index map.
**Return type**
List
</Function>
### node\_index
<Function id="qiskit.circuit.EquivalenceLibrary.node_index" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/equivalence.py#L188-L197" signature="node_index(key)">
Return node index for a given key.
**Parameters**
**key** (*Key*) β Key to an equivalence.
**Returns**
Index to the node in the graph for the given key.
**Return type**
Int
</Function>
### set\_entry
<Function id="qiskit.circuit.EquivalenceLibrary.set_entry" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/equivalence.py#L129-L154" signature="set_entry(gate, entry)">
Set the equivalence record for a Gate. Future queries for the Gate will return only the circuits provided.
Parameterized Gates (those including qiskit.circuit.Parameters in their Gate.params) can be marked equivalent to parameterized circuits, provided the parameters match.
**Parameters**
* **gate** ([*Gate*](qiskit.circuit.Gate "qiskit.circuit.Gate")) β A Gate instance.
* **entry** (*List\['QuantumCircuit']*) β A list of QuantumCircuits, each equivalently implementing the given Gate.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.EquivalenceLibrary.mdx
|
---
title: ForLoopOp
description: API reference for qiskit.circuit.ForLoopOp
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.ForLoopOp
---
# ForLoopOp
<Class id="qiskit.circuit.ForLoopOp" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/for_loop.py#L28-L129" signature="qiskit.circuit.ForLoopOp(indexset, loop_parameter, body, label=None)" modifiers="class">
Bases: [`ControlFlowOp`](qiskit.circuit.ControlFlowOp "qiskit.circuit.controlflow.control_flow.ControlFlowOp")
A circuit operation which repeatedly executes a subcircuit (`body`) parameterized by a parameter `loop_parameter` through the set of integer values provided in `indexset`.
**Parameters**
* **indexset** (*Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]*) β A collection of integers to loop over.
* **loop\_parameter** (*Union\[*[*Parameter*](qiskit.circuit.Parameter "qiskit.circuit.Parameter")*, None]*) β The placeholder parameterizing `body` to which the values from `indexset` will be assigned.
* **body** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")) β The loop body to be repeatedly executed.
* **label** (*Optional\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]*) β An optional label for identifying the instruction.
**Circuit symbol:**
```python
βββββββββββββ
q_0: β€0 β
β β
q_1: β€1 β
β for_loop β
q_2: β€2 β
β β
c_0: β‘0 β
βββββββββββββ
```
Create a new instruction.
**Parameters**
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β instruction name
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs clbit width
* **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*|*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")*]*) β list of parameters
* **duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *or*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β instructionβs duration. it must be integer if `unit` is βdtβ
* **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β time unit of duration
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *or None*) β An optional label for identifying the instruction.
**Raises**
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β when the register is not in the correct format.
* [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.12)") β when the optional label is provided, but it is not a string.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.ForLoopOp.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.ForLoopOp.base_class "qiskit.circuit.ForLoopOp.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that [`Instruction.name`](qiskit.circuit.Instruction#name "qiskit.circuit.Instruction.name") should be a more suitable discriminator in most situations.
</Attribute>
### blocks
<Attribute id="qiskit.circuit.ForLoopOp.blocks" />
### condition
<Attribute id="qiskit.circuit.ForLoopOp.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.ForLoopOp.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.ForLoopOp.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.ForLoopOp.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.ForLoopOp.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.ForLoopOp.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.ForLoopOp.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.ForLoopOp.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.ForLoopOp.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.ForLoopOp.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.ForLoopOp.params" />
### unit
<Attribute id="qiskit.circuit.ForLoopOp.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.ForLoopOp.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.ForLoopOp.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.ForLoopOp.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L535-L564" signature="broadcast_arguments(qargs, cargs)">
Validation of the arguments.
**Parameters**
* **qargs** (*List*) β List of quantum bit arguments.
* **cargs** (*List*) β List of classical bit arguments.
**Yields**
*Tuple(List, List)* β A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
</Function>
### c\_if
<Function id="qiskit.circuit.ForLoopOp.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L479-L497" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### copy
<Function id="qiskit.circuit.ForLoopOp.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### inverse
<Function id="qiskit.circuit.ForLoopOp.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L422-L477" signature="inverse(annotated=False)">
Invert this instruction.
If annotated is False, the inverse instruction is implemented as a fresh instruction with the recursively inverted definition.
If annotated is True, the inverse instruction is implemented as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation"), and corresponds to the given instruction annotated with the βinverse modifierβ.
Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) In particular, they can choose how to handle the argument `annotated` which may include ignoring it and always returning a concrete gate class if the inverse is defined as a standard gate.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β if set to True the output inverse gate will be returned as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Returns**
The inverse operation.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the instruction is not composite and an inverse has not been implemented for it.
</Function>
### is\_parameterized
<Function id="qiskit.circuit.ForLoopOp.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### repeat
<Function id="qiskit.circuit.ForLoopOp.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### replace\_blocks
<Function id="qiskit.circuit.ForLoopOp.replace_blocks" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/for_loop.py#L127-L129" signature="replace_blocks(blocks)">
Replace blocks and return new instruction. :param blocks: Tuple of QuantumCircuits to replace in instruction.
**Returns**
New ControlFlowOp with replaced blocks.
</Function>
### reverse\_ops
<Function id="qiskit.circuit.ForLoopOp.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### soft\_compare
<Function id="qiskit.circuit.ForLoopOp.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### to\_mutable
<Function id="qiskit.circuit.ForLoopOp.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.ForLoopOp.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L289-L291" signature="validate_parameter(parameter)">
Instruction parameters has no validation or normalization.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.ForLoopOp.mdx
|
---
title: Gate
description: API reference for qiskit.circuit.Gate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.Gate
---
# Gate
<Class id="qiskit.circuit.Gate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L25-L242" signature="qiskit.circuit.Gate(name, num_qubits, params, label=None, duration=None, unit='dt')" modifiers="class">
Bases: [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.instruction.Instruction")
Unitary gate.
Create a new gate.
**Parameters**
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The Qobj name of the gate.
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β The number of qubits the gate acts on.
* **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β A list of parameters.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β An optional label for the gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.Gate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.Gate.base_class "qiskit.circuit.Gate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that [`Instruction.name`](qiskit.circuit.Instruction#name "qiskit.circuit.Instruction.name") should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.Gate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.Gate.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.Gate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.Gate.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.Gate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.Gate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.Gate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.Gate.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.Gate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.Gate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.Gate.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.Gate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.Gate.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.Gate.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.Gate.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L169-L226" signature="broadcast_arguments(qargs, cargs)">
Validation and handling of the arguments and its relationship.
For example, `cx([q[0],q[1]], q[2])` means `cx(q[0], q[2]); cx(q[1], q[2])`. This method yields the arguments in the right grouping. In the given example:
```python
in: [[q[0],q[1]], q[2]],[]
outs: [q[0], q[2]], []
[q[1], q[2]], []
```
The general broadcasting rules are:
> * If len(qargs) == 1:
>
> ```python
> [q[0], q[1]] -> [q[0]],[q[1]]
> ```
>
> * If len(qargs) == 2:
>
> ```python
> [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]], [q[1], r[1]]
> [[q[0]], [r[0], r[1]]] -> [q[0], r[0]], [q[0], r[1]]
> [[q[0], q[1]], [r[0]]] -> [q[0], r[0]], [q[1], r[0]]
> ```
>
> * If len(qargs) >= 3:
>
> ```python
> [q[0], q[1]], [r[0], r[1]], ...] -> [q[0], r[0], ...], [q[1], r[1], ...]
> ```
**Parameters**
* **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β List of quantum bit arguments.
* **cargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")) β List of classical bit arguments.
**Returns**
A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
**Return type**
[*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.12)")\[[tuple](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.12)")\[[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)"), [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")]]
</Function>
### c\_if
<Function id="qiskit.circuit.Gate.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L479-L497" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### control
<Function id="qiskit.circuit.Gate.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L89-L126" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False)">
Return the controlled version of itself.
Implemented either as a controlled gate (ref. [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")) or as an annotated operation (ref. [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation")).
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of controls to add to gate (default: `1`)
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β optional gate label. Ignored if implemented as an annotated operation.
* **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β the control state in decimal or as a bitstring (e.g. `'111'`). If `None`, use `2**num_ctrl_qubits-1`.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β indicates whether the controlled gate can be implemented as an annotated gate.
**Returns**
Controlled version of the given operation.
**Raises**
[**QiskitError**](exceptions#qiskit.exceptions.QiskitError "qiskit.exceptions.QiskitError") β unrecognized mode or invalid ctrl\_state
</Function>
### copy
<Function id="qiskit.circuit.Gate.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### inverse
<Function id="qiskit.circuit.Gate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L422-L477" signature="inverse(annotated=False)">
Invert this instruction.
If annotated is False, the inverse instruction is implemented as a fresh instruction with the recursively inverted definition.
If annotated is True, the inverse instruction is implemented as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation"), and corresponds to the given instruction annotated with the βinverse modifierβ.
Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) In particular, they can choose how to handle the argument `annotated` which may include ignoring it and always returning a concrete gate class if the inverse is defined as a standard gate.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β if set to True the output inverse gate will be returned as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Returns**
The inverse operation.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the instruction is not composite and an inverse has not been implemented for it.
</Function>
### is\_parameterized
<Function id="qiskit.circuit.Gate.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### power
<Function id="qiskit.circuit.Gate.power" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L65-L81" signature="power(exponent)">
Creates a unitary gate as gate^exponent.
**Parameters**
**exponent** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Gate^exponent
**Returns**
To which to\_matrix is self.to\_matrix^exponent.
**Return type**
.library.UnitaryGate
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If Gate is not unitary
</Function>
### repeat
<Function id="qiskit.circuit.Gate.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### reverse\_ops
<Function id="qiskit.circuit.Gate.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### soft\_compare
<Function id="qiskit.circuit.Gate.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### to\_matrix
<Function id="qiskit.circuit.Gate.to_matrix" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L51-L63" signature="to_matrix()">
Return a Numpy.array for the gate unitary matrix.
**Returns**
if the Gate subclass has a matrix definition.
**Return type**
np.ndarray
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If a Gate subclass does not implement this method an exception will be raised when this base class method is called.
</Function>
### to\_mutable
<Function id="qiskit.circuit.Gate.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.Gate.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/gate.py#L228-L242" signature="validate_parameter(parameter)">
Gate parameters should be int, float, or ParameterExpression
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.Gate.mdx
|
---
title: IfElseOp
description: API reference for qiskit.circuit.IfElseOp
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.IfElseOp
---
# IfElseOp
<Class id="qiskit.circuit.IfElseOp" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/if_else.py#L42-L175" signature="qiskit.circuit.IfElseOp(condition, true_body, false_body=None, label=None)" modifiers="class">
Bases: [`ControlFlowOp`](qiskit.circuit.ControlFlowOp "qiskit.circuit.controlflow.control_flow.ControlFlowOp")
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.
**Parameters**
* **condition** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.12)")*\[*[*ClassicalRegister*](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister")*,* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*] |* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.12)")*\[*[*Clbit*](qiskit.circuit.Clbit "qiskit.circuit.Clbit")*,* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*] |* [*expr.Expr*](circuit_classical#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.Expr")) β A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of `true_body`. Can be specified as either a tuple of a `ClassicalRegister` to be tested for equality with a given `int`, or as a tuple of a `Clbit` to be compared to either a `bool` or an `int`.
* **true\_body** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")) β A program to be executed if `condition` evaluates to true.
* **false\_body** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") *| None*) β A optional program to be executed if `condition` evaluates to false.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β An optional label for identifying the instruction.
If provided, `false_body` must be of the same `num_qubits` and `num_clbits` as `true_body`.
The classical bits used in `condition` must be a subset of those attached to the circuit on which this `IfElseOp` will be appended.
**Circuit symbol:**
```python
βββββββββββββ
q_0: β€0 β
β β
q_1: β€1 β
β if_else β
q_2: β€2 β
β β
c_0: β‘0 β
βββββββββββββ
```
Create a new instruction.
**Parameters**
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β instruction name
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs clbit width
* **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*|*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")*]*) β list of parameters
* **duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *or*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β instructionβs duration. it must be integer if `unit` is βdtβ
* **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β time unit of duration
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *or None*) β An optional label for identifying the instruction.
**Raises**
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β when the register is not in the correct format.
* [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.12)") β when the optional label is provided, but it is not a string.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.IfElseOp.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.IfElseOp.base_class "qiskit.circuit.IfElseOp.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that [`Instruction.name`](qiskit.circuit.Instruction#name "qiskit.circuit.Instruction.name") should be a more suitable discriminator in most situations.
</Attribute>
### blocks
<Attribute id="qiskit.circuit.IfElseOp.blocks" />
### condition
<Attribute id="qiskit.circuit.IfElseOp.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.IfElseOp.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.IfElseOp.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.IfElseOp.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.IfElseOp.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.IfElseOp.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.IfElseOp.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.IfElseOp.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.IfElseOp.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.IfElseOp.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.IfElseOp.params" />
### unit
<Attribute id="qiskit.circuit.IfElseOp.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.IfElseOp.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.IfElseOp.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.IfElseOp.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L535-L564" signature="broadcast_arguments(qargs, cargs)">
Validation of the arguments.
**Parameters**
* **qargs** (*List*) β List of quantum bit arguments.
* **cargs** (*List*) β List of classical bit arguments.
**Yields**
*Tuple(List, List)* β A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
</Function>
### c\_if
<Function id="qiskit.circuit.IfElseOp.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/if_else.py#L171-L175" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### copy
<Function id="qiskit.circuit.IfElseOp.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### inverse
<Function id="qiskit.circuit.IfElseOp.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L422-L477" signature="inverse(annotated=False)">
Invert this instruction.
If annotated is False, the inverse instruction is implemented as a fresh instruction with the recursively inverted definition.
If annotated is True, the inverse instruction is implemented as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation"), and corresponds to the given instruction annotated with the βinverse modifierβ.
Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) In particular, they can choose how to handle the argument `annotated` which may include ignoring it and always returning a concrete gate class if the inverse is defined as a standard gate.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β if set to True the output inverse gate will be returned as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Returns**
The inverse operation.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the instruction is not composite and an inverse has not been implemented for it.
</Function>
### is\_parameterized
<Function id="qiskit.circuit.IfElseOp.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### repeat
<Function id="qiskit.circuit.IfElseOp.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### replace\_blocks
<Function id="qiskit.circuit.IfElseOp.replace_blocks" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/if_else.py#L155-L169" signature="replace_blocks(blocks)">
Replace blocks and return new instruction.
**Parameters**
**blocks** (*Iterable\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")*]*) β Iterable of circuits for βifβ and βelseβ condition. If there is no βelseβ circuit it may be set to None or omitted.
**Returns**
New IfElseOp with replaced blocks.
**Return type**
[IfElseOp](#qiskit.circuit.IfElseOp "qiskit.circuit.IfElseOp")
</Function>
### reverse\_ops
<Function id="qiskit.circuit.IfElseOp.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### soft\_compare
<Function id="qiskit.circuit.IfElseOp.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### to\_mutable
<Function id="qiskit.circuit.IfElseOp.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.IfElseOp.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L289-L291" signature="validate_parameter(parameter)">
Instruction parameters has no validation or normalization.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.IfElseOp.mdx
|
---
title: Instruction
description: API reference for qiskit.circuit.Instruction
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.Instruction
---
# Instruction
<Class id="qiskit.circuit.Instruction" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L56-L657" signature="qiskit.circuit.Instruction(name, num_qubits, num_clbits, params, duration=None, unit='dt', label=None)" modifiers="class">
Bases: [`Operation`](qiskit.circuit.Operation "qiskit.circuit.operation.Operation")
Generic quantum instruction.
Create a new instruction.
**Parameters**
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β instruction name
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β instructionβs clbit width
* **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*|*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")*]*) β list of parameters
* **duration** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *or*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β instructionβs duration. it must be integer if `unit` is βdtβ
* **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β time unit of duration
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *or None*) β An optional label for identifying the instruction.
**Raises**
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β when the register is not in the correct format.
* [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.12)") β when the optional label is provided, but it is not a string.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.Instruction.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.Instruction.base_class "qiskit.circuit.Instruction.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that [`Instruction.name`](#qiskit.circuit.Instruction.name "qiskit.circuit.Instruction.name") should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.Instruction.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.Instruction.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.Instruction.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.Instruction.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.Instruction.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.Instruction.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.Instruction.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.Instruction.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.Instruction.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.Instruction.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.Instruction.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.Instruction.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.Instruction.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.Instruction.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.Instruction.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L535-L564" signature="broadcast_arguments(qargs, cargs)">
Validation of the arguments.
**Parameters**
* **qargs** (*List*) β List of quantum bit arguments.
* **cargs** (*List*) β List of classical bit arguments.
**Yields**
*Tuple(List, List)* β A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
</Function>
### c\_if
<Function id="qiskit.circuit.Instruction.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L479-L497" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### copy
<Function id="qiskit.circuit.Instruction.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](#qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### inverse
<Function id="qiskit.circuit.Instruction.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L422-L477" signature="inverse(annotated=False)">
Invert this instruction.
If annotated is False, the inverse instruction is implemented as a fresh instruction with the recursively inverted definition.
If annotated is True, the inverse instruction is implemented as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation"), and corresponds to the given instruction annotated with the βinverse modifierβ.
Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) In particular, they can choose how to handle the argument `annotated` which may include ignoring it and always returning a concrete gate class if the inverse is defined as a standard gate.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β if set to True the output inverse gate will be returned as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Returns**
The inverse operation.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the instruction is not composite and an inverse has not been implemented for it.
</Function>
### is\_parameterized
<Function id="qiskit.circuit.Instruction.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### repeat
<Function id="qiskit.circuit.Instruction.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](#qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### reverse\_ops
<Function id="qiskit.circuit.Instruction.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](#qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### soft\_compare
<Function id="qiskit.circuit.Instruction.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### to\_mutable
<Function id="qiskit.circuit.Instruction.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.Instruction.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L289-L291" signature="validate_parameter(parameter)">
Instruction parameters has no validation or normalization.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.Instruction.mdx
|
---
title: InstructionSet
description: API reference for qiskit.circuit.InstructionSet
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.InstructionSet
---
# InstructionSet
<Class id="qiskit.circuit.InstructionSet" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instructionset.py#L28-L193" signature="qiskit.circuit.InstructionSet(*, resource_requester=None)" modifiers="class">
Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.12)")
Instruction collection, and their contexts.
New collection of instructions.
The context (`qargs` and `cargs` that each instruction is attached to) is also stored separately for each instruction.
**Parameters**
**resource\_requester** (*Callable\[...,* [*ClassicalRegister*](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister") *|*[*Clbit*](qiskit.circuit.Clbit "qiskit.circuit.Clbit")*] | None*) β
A callable that takes in the classical resource used in the condition, verifies that it is present in the attached circuit, resolves any indices into concrete [`Clbit`](qiskit.circuit.Clbit "qiskit.circuit.Clbit") instances, and returns the concrete resource. If this is not given, specifying a condition with an index is forbidden, and all concrete [`Clbit`](qiskit.circuit.Clbit "qiskit.circuit.Clbit") and [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister") resources will be assumed to be valid.
<Admonition title="Note" type="note">
The callback `resource_requester` is called once for each call to [`c_if()`](#qiskit.circuit.InstructionSet.c_if "qiskit.circuit.InstructionSet.c_if"), and assumes that a call implies that the resource will now be used. It may throw an error if the resource is not valid for usage.
</Admonition>
## Attributes
### cargs
<Attribute id="qiskit.circuit.InstructionSet.cargs">
Legacy getter for the cargs components of an instruction set. This does not support mutation.
</Attribute>
### instructions
<Attribute id="qiskit.circuit.InstructionSet.instructions">
Legacy getter for the instruction components of an instruction set. This does not support mutation.
</Attribute>
### qargs
<Attribute id="qiskit.circuit.InstructionSet.qargs">
Legacy getter for the qargs components of an instruction set. This does not support mutation.
</Attribute>
## Methods
### add
<Function id="qiskit.circuit.InstructionSet.add" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instructionset.py#L74-L82" signature="add(instruction, qargs=None, cargs=None)">
Add an instruction and its context (where it is attached).
</Function>
### c\_if
<Function id="qiskit.circuit.InstructionSet.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instructionset.py#L104-L169" signature="c_if(classical, val)">
Set a classical equality condition on all the instructions in this set between the [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister") or [`Clbit`](qiskit.circuit.Clbit "qiskit.circuit.Clbit") `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition on any of the contained instructions; it does not stack.
</Admonition>
**Parameters**
* **classical** ([*Clbit*](qiskit.circuit.Clbit "qiskit.circuit.Clbit") *|*[*ClassicalRegister*](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister") *|*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β the classical resource the equality condition should be on. If this is given as an integer, it will be resolved into a [`Clbit`](qiskit.circuit.Clbit "qiskit.circuit.Clbit") using the same conventions as the circuit these instructions are attached to.
* **val** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β the value the classical resource should be equal to.
**Returns**
This same instance of [`InstructionSet`](#qiskit.circuit.InstructionSet "qiskit.circuit.InstructionSet"), but now mutated to have the given equality condition.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the passed classical resource is invalid, or otherwise not resolvable to a concrete resource that these instructions are permitted to access.
**Return type**
[InstructionSet](#qiskit.circuit.InstructionSet "qiskit.circuit.InstructionSet")
**Example**
```python
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
```

</Function>
### inverse
<Function id="qiskit.circuit.InstructionSet.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instructionset.py#L89-L102" signature="inverse(annotated=False)">
Invert all instructions.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.InstructionSet.mdx
|
---
title: InverseModifier
description: API reference for qiskit.circuit.InverseModifier
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.InverseModifier
---
# InverseModifier
<Class id="qiskit.circuit.InverseModifier" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/annotated_operation.py#L32-L36" signature="qiskit.circuit.InverseModifier" modifiers="class">
Bases: `Modifier`
Inverse modifier: specifies that the operation is inverted.
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.InverseModifier.mdx
|
---
title: AND
description: API reference for qiskit.circuit.library.AND
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.AND
---
# AND
<Class id="qiskit.circuit.library.AND" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/boolean_logic/quantum_and.py#L21-L97" signature="qiskit.circuit.library.AND(num_variable_qubits, flags=None, mcx_mode='noancilla')" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
A circuit implementing the logical AND operation on a number of qubits.
For the AND operation the state $|1\rangle$ is interpreted as `True`. The result qubit is flipped, if the state of all variable qubits is `True`. In this format, the AND operation equals a multi-controlled X gate, which is controlled on all variable qubits. Using a list of flags however, qubits can be skipped or negated. Practically, the flags allow to skip controls or to apply pre- and post-X gates to the negated qubits.
The AND gate without special flags equals the multi-controlled-X gate:

Using flags we can negate qubits or skip them. For instance, if we have 5 qubits and want to return `True` if the first qubit is `False` and the last two are `True` we use the flags `[-1, 0, 0, 1, 1]`.

Create a new logical AND circuit.
**Parameters**
* **num\_variable\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β The qubits of which the OR is computed. The result will be written into an additional result qubit.
* **flags** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*] | None*) β A list of +1/0/-1 marking negations or omissions of qubits.
* **mcx\_mode** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The mode to be used to implement the multi-controlled X gate.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.AND.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.AND.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.AND.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.AND.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.AND.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.AND.instances" attributeValue="161" />
### layout
<Attribute id="qiskit.circuit.library.AND.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.AND.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.AND.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.AND.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.AND.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.AND.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.AND.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.AND.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.AND.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.AND.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.AND.mdx
|
---
title: Barrier
description: API reference for qiskit.circuit.library.Barrier
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.Barrier
---
# Barrier
<Class id="qiskit.circuit.library.Barrier" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/barrier.py#L23-L51" signature="qiskit.circuit.library.Barrier(num_qubits, label=None)" modifiers="class">
Bases: [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.instruction.Instruction")
Barrier instruction.
A barrier is a visual indicator of the grouping of a circuit section. It also acts as a directive for circuit compilation to separate pieces of a circuit so that any optimizations or re-writes are constrained to only act between barriers.
Create new barrier instruction.
**Parameters**
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β the number of qubits for the barrier type \[Default: 0].
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β the barrier label
**Raises**
[**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.12)") β if barrier label is invalid.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.Barrier.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.Barrier.base_class "qiskit.circuit.library.Barrier.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.Barrier.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.Barrier.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.Barrier.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.Barrier.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.Barrier.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.Barrier.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.Barrier.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.Barrier.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.Barrier.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.Barrier.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.Barrier.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.Barrier.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.library.Barrier.add_decomposition" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L327-L332" signature="add_decomposition(decomposition)">
Add a decomposition of the instruction to the SessionEquivalenceLibrary.
</Function>
### assemble
<Function id="qiskit.circuit.library.Barrier.assemble" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L354-L374" signature="assemble()">
Assemble a QasmQobjInstruction
</Function>
### broadcast\_arguments
<Function id="qiskit.circuit.library.Barrier.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L535-L564" signature="broadcast_arguments(qargs, cargs)">
Validation of the arguments.
**Parameters**
* **qargs** (*List*) β List of quantum bit arguments.
* **cargs** (*List*) β List of classical bit arguments.
**Yields**
*Tuple(List, List)* β A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
</Function>
### c\_if
<Function id="qiskit.circuit.library.Barrier.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/barrier.py#L50-L51" signature="c_if(classical, val)">
Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`.
<Admonition title="Note" type="note">
This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack.
</Admonition>
</Function>
### copy
<Function id="qiskit.circuit.library.Barrier.copy" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L499-L514" signature="copy(name=None)">
Copy of the instruction.
**Parameters**
**name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β name to be given to the copied circuit, if `None` then the name stays the same.
**Returns**
a copy of the current instruction, with the name updated if it was provided
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### inverse
<Function id="qiskit.circuit.library.Barrier.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/barrier.py#L46-L48" signature="inverse(annotated=False)">
Special case. Return self.
</Function>
### is\_parameterized
<Function id="qiskit.circuit.library.Barrier.is_parameterized" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L293-L297" signature="is_parameterized()">
Return True .IFF. instruction is parameterized else False
</Function>
### repeat
<Function id="qiskit.circuit.library.Barrier.repeat" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L574-L608" signature="repeat(n)">
Creates an instruction with gate repeated n amount of times.
**Parameters**
**n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of times to repeat the instruction
**Returns**
Containing the definition.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If n \< 1.
</Function>
### reverse\_ops
<Function id="qiskit.circuit.library.Barrier.reverse_ops" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L396-L420" signature="reverse_ops()">
For a composite instruction, reverse the order of sub-instructions.
This is done by recursively reversing all sub-instructions. It does not invert any gate.
**Returns**
**a new instruction with**
sub-instructions reversed.
**Return type**
[qiskit.circuit.Instruction](qiskit.circuit.Instruction "qiskit.circuit.Instruction")
</Function>
### soft\_compare
<Function id="qiskit.circuit.library.Barrier.soft_compare" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L229-L269" signature="soft_compare(other)">
Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.
**Parameters**
**other** (*instruction*) β other instruction.
**Returns**
are self and other equal up to parameter expressions.
**Return type**
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")
</Function>
### to\_mutable
<Function id="qiskit.circuit.library.Barrier.to_mutable" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L151-L159" signature="to_mutable()">
Return a mutable copy of this gate.
This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.library.Barrier.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/instruction.py#L289-L291" signature="validate_parameter(parameter)">
Instruction parameters has no validation or normalization.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.Barrier.mdx
|
---
title: C3SXGate
description: API reference for qiskit.circuit.library.C3SXGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.C3SXGate
---
# C3SXGate
<Class id="qiskit.circuit.library.C3SXGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L565-L668" signature="qiskit.circuit.library.C3SXGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
The 3-qubit controlled sqrt-X gate.
This implementation is based on Page 17 of \[1].
**References**
\[1] Barenco et al., 1995. [https://arxiv.org/pdf/quant-ph/9503016.pdf](https://arxiv.org/pdf/quant-ph/9503016.pdf)
Create a new 3-qubit controlled sqrt-X gate.
**Parameters**
* **label** β An optional label for the gate \[Default: `None`]
* **ctrl\_state** β control state expressed as integer, string (e.g.\`\`β110β`), or ``None`. If `None`, use all 1s.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.C3SXGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.C3SXGate.base_class "qiskit.circuit.library.C3SXGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.C3SXGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.C3SXGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.C3SXGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.C3SXGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.C3SXGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.C3SXGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.C3SXGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.C3SXGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.C3SXGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.C3SXGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.C3SXGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.C3SXGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.C3SXGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.C3SXGate.unit">
Get the time unit of duration.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.C3SXGate.mdx
|
---
title: C3XGate
description: API reference for qiskit.circuit.library.C3XGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.C3XGate
---
# C3XGate
<Class id="qiskit.circuit.library.C3XGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L671-L828" signature="qiskit.circuit.library.C3XGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
The X gate controlled on 3 qubits.
This implementation uses $\sqrt{T}$ and 14 CNOT gates.
Create a new 3-qubit controlled X gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.C3XGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.C3XGate.base_class "qiskit.circuit.library.C3XGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.C3XGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.C3XGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.C3XGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.C3XGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.C3XGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.C3XGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.C3XGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.C3XGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.C3XGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.C3XGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.C3XGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.C3XGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.C3XGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.C3XGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### control
<Function id="qiskit.circuit.library.C3XGate.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L775-L811" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False)">
Controlled version of this gate.
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of control qubits.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β An optional label for the gate \[Default: `None`]
* **ctrl\_state** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β control state expressed as integer, string (e.g.\`\`β110β`), or ``None`. If `None`, use all 1s.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β indicates whether the controlled gate can be implemented as an annotated gate.
**Returns**
controlled version of this gate.
**Return type**
[ControlledGate](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")
</Function>
### inverse
<Function id="qiskit.circuit.library.C3XGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L813-L825" signature="inverse(annotated=False)">
Invert this gate. The C3X is its own inverse.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as this gate is self-inverse.
**Returns**
inverse gate (self-inverse).
**Return type**
[C3XGate](#qiskit.circuit.library.C3XGate "qiskit.circuit.library.C3XGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.C3XGate.mdx
|
---
title: C4XGate
description: API reference for qiskit.circuit.library.C4XGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.C4XGate
---
# C4XGate
<Class id="qiskit.circuit.library.C4XGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L930-L1072" signature="qiskit.circuit.library.C4XGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
The 4-qubit controlled X gate.
This implementation is based on Page 21, Lemma 7.5, of \[1], with the use of the relative phase version of c3x, the rc3x \[2].
**References**
\[1] Barenco et al., 1995. [https://arxiv.org/pdf/quant-ph/9503016.pdf](https://arxiv.org/pdf/quant-ph/9503016.pdf) \[2] Maslov, 2015. [https://arxiv.org/abs/1508.03273](https://arxiv.org/abs/1508.03273)
Create a new 4-qubit controlled X gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.C4XGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.C4XGate.base_class "qiskit.circuit.library.C4XGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.C4XGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.C4XGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.C4XGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.C4XGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.C4XGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.C4XGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.C4XGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.C4XGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.C4XGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.C4XGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.C4XGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.C4XGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.C4XGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.C4XGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### control
<Function id="qiskit.circuit.library.C4XGate.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L1019-L1055" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False)">
Controlled version of this gate.
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of control qubits.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β An optional label for the gate \[Default: `None`]
* **ctrl\_state** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β control state expressed as integer, string (e.g.\`\`β110β`), or ``None`. If `None`, use all 1s.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β indicates whether the controlled gate can be implemented as an annotated gate.
**Returns**
controlled version of this gate.
**Return type**
[ControlledGate](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")
</Function>
### inverse
<Function id="qiskit.circuit.library.C4XGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L1057-L1069" signature="inverse(annotated=False)">
Invert this gate. The C4X is its own inverse.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as this gate is self-inverse.
**Returns**
inverse gate (self-inverse).
**Return type**
[C4XGate](#qiskit.circuit.library.C4XGate "qiskit.circuit.library.C4XGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.C4XGate.mdx
|
---
title: CCXGate
description: API reference for qiskit.circuit.library.CCXGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CCXGate
---
# CCXGate
<Class id="qiskit.circuit.library.CCXGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L296-L487" signature="qiskit.circuit.library.CCXGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
CCX gate, also known as Toffoli gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`ccx()`](qiskit.circuit.QuantumCircuit#ccx "qiskit.circuit.QuantumCircuit.ccx") and `toffoli()` methods.
**Circuit symbol:**
```python
q_0: βββ ββ
β
q_1: βββ ββ
βββ΄ββ
q_2: β€ X β
βββββ
```
**Matrix representation:**
$$
CCX q_0, q_1, q_2 =
I \otimes I \otimes |0 \rangle \langle 0| + CX \otimes |1 \rangle \langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1\\
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 1 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0\\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_2 and q\_1. Thus a textbook matrix for this gate will be:
```python
βββββ
q_0: β€ X β
βββ¬ββ
q_1: βββ ββ
β
q_2: βββ ββ
```
$$
CCX\ q_2, q_1, q_0 =
|0 \rangle \langle 0| \otimes I \otimes I + |1 \rangle \langle 1| \otimes CX =
\begin{pmatrix}
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 1 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1\\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0
\end{pmatrix}
$$
</Admonition>
Create new CCX gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CCXGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CCXGate.base_class "qiskit.circuit.library.CCXGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CCXGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CCXGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CCXGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CCXGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CCXGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CCXGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CCXGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CCXGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CCXGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CCXGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CCXGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CCXGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CCXGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CCXGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### control
<Function id="qiskit.circuit.library.CCXGate.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L434-L470" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False)">
Controlled version of this gate.
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of control qubits.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β An optional label for the gate \[Default: `None`]
* **ctrl\_state** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β control state expressed as integer, string (e.g.\`\`β110β`), or ``None`. If `None`, use all 1s.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β indicates whether the controlled gate can be implemented as an annotated gate.
**Returns**
controlled version of this gate.
**Return type**
[ControlledGate](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")
</Function>
### inverse
<Function id="qiskit.circuit.library.CCXGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L472-L484" signature="inverse(annotated=False)">
Return an inverted CCX gate (also a CCX).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as this gate is self-inverse.
**Returns**
inverse gate (self-inverse).
**Return type**
[CCXGate](#qiskit.circuit.library.CCXGate "qiskit.circuit.library.CCXGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CCXGate.mdx
|
---
title: CCZGate
description: API reference for qiskit.circuit.library.CCZGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CCZGate
---
# CCZGate
<Class id="qiskit.circuit.library.CCZGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/z.py#L245-L342" signature="qiskit.circuit.library.CCZGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
CCZ gate.
This is a symmetric gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`ccz()`](qiskit.circuit.QuantumCircuit#ccz "qiskit.circuit.QuantumCircuit.ccz") method.
**Circuit symbol:**
```python
q_0: ββ β
β
q_1: ββ β
β
q_2: ββ β
```
**Matrix representation:**
$$
CCZ\ q_0, q_1, q_2 =
I \otimes I \otimes |0\rangle\langle 0| + CZ \otimes |1\rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & -1
\end{pmatrix}
$$
In the computational basis, this gate flips the phase of the target qubit if the control qubits are in the $|11\rangle$ state.
Create new CCZ gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CCZGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CCZGate.base_class "qiskit.circuit.library.CCZGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CCZGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CCZGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CCZGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CCZGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CCZGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CCZGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CCZGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CCZGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CCZGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CCZGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CCZGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CCZGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CCZGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CCZGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CCZGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/z.py#L327-L339" signature="inverse(annotated=False)">
Return inverted CCZ gate (itself).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as this gate is self-inverse.
**Returns**
inverse gate (self-inverse).
**Return type**
[CCZGate](#qiskit.circuit.library.CCZGate "qiskit.circuit.library.CCZGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CCZGate.mdx
|
---
title: CDKMRippleCarryAdder
description: API reference for qiskit.circuit.library.CDKMRippleCarryAdder
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CDKMRippleCarryAdder
---
# CDKMRippleCarryAdder
<Class id="qiskit.circuit.library.CDKMRippleCarryAdder" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/arithmetic/adders/cdkm_ripple_carry_adder.py#L20-L159" signature="qiskit.circuit.library.CDKMRippleCarryAdder(num_state_qubits, kind='full', name='CDKMRippleCarryAdder')" modifiers="class">
Bases: `Adder`
A ripple-carry circuit to perform in-place addition on two qubit registers.
As an example, a ripple-carry adder circuit that performs addition on two 3-qubit sized registers with a carry-in bit (`kind="full"`) is as follows:
```python
ββββββββ ββββββββ
cin_0: β€2 βββββββββββββββββββββββββββββββββββββββ€2 β
β βββββββββ βββββββββ β
a_0: β€0 ββ€2 βββββββββββββββββββββββ€2 ββ€0 β
β ββ βββββββββ βββββββββ ββ β
a_1: β€ MAJ ββ€0 ββ€2 βββββββ€2 ββ€0 ββ€ UMA β
β ββ ββ β β ββ ββ β
a_2: β€ ββ€ MAJ ββ€0 ββββ βββ€0 ββ€ UMA ββ€ β
β ββ ββ β β β ββ ββ β
b_0: β€1 ββ€ ββ€ MAJ ββββΌβββ€ UMA ββ€ ββ€1 β
βββββββββ ββ β β β ββ βββββββββ
b_1: βββββββββ€1 ββ€ ββββΌβββ€ ββ€1 βββββββββ
βββββββββ β β β βββββββββ
b_2: βββββββββββββββββ€1 ββββΌβββ€1 βββββββββββββββββ
βββββββββββ΄ββββββββββ
cout_0: βββββββββββββββββββββββββ€ X βββββββββββββββββββββββββ
βββββ
```
Here *MAJ* and *UMA* gates correspond to the gates introduced in \[1]. Note that in this implementation the input register qubits are ordered as all qubits from the first input register, followed by all qubits from the second input register.
Two different kinds of adders are supported. By setting the `kind` argument, you can also choose a half-adder, which doesnβt have a carry-in, and a fixed-sized-adder, which has neither carry-in nor carry-out, and thus acts on fixed register sizes. Unlike the full-adder, these circuits need one additional helper qubit.
The circuit diagram for the fixed-point adder (`kind="fixed"`) on 3-qubit sized inputs is
```python
ββββββββββββββββ ββββββββββββββββ
a_0: β€0 ββ€2 ββββββββββββββββββ€2 ββ€0 β
β ββ ββββββββββββββββββ ββ β
a_1: β€ ββ€0 ββ€2 ββ€2 ββ€0 ββ€ β
β ββ ββ ββ ββ ββ β
a_2: β€ ββ€ MAJ ββ€0 ββ€0 ββ€ UMA ββ€ β
β ββ ββ ββ ββ ββ β
b_0: β€1 MAJ ββ€ ββ€ MAJ ββ€ UMA ββ€ ββ€1 UMA β
β ββ ββ ββ ββ ββ β
b_1: β€ ββ€1 ββ€ ββ€ ββ€1 ββ€ β
β ββββββββββ ββ ββββββββββ β
b_2: β€ ββββββββββ€1 ββ€1 ββββββββββ€ β
β β ββββββββββββββββ β β
help_0: β€2 ββββββββββββββββββββββββββββββββββ€2 β
ββββββββ ββββββββ
```
It has one less qubit than the full-adder since it doesnβt have the carry-out, but uses a helper qubit instead of the carry-in, so it only has one less qubit, not two.
**References:**
\[1] Cuccaro et al., A new quantum ripple-carry addition circuit, 2004. [arXiv:quant-ph/0410184](https://arxiv.org/pdf/quant-ph/0410184.pdf)
\[2] Vedral et al., Quantum Networks for Elementary Arithmetic Operations, 1995. [arXiv:quant-ph/9511018](https://arxiv.org/pdf/quant-ph/9511018.pdf)
**Parameters**
* **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β The number of qubits in either input register for state $|a\rangle$ or $|b\rangle$. The two input registers must have the same number of qubits.
* **kind** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The kind of adder, can be `'full'` for a full adder, `'half'` for a half adder, or `'fixed'` for a fixed-sized adder. A full adder includes both carry-in and carry-out, a half only carry-out, and a fixed-sized adder neither carry-in nor carry-out.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The name of the circuit object.
**Raises**
[**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.12)") β If `num_state_qubits` is lower than 1.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.instances" attributeValue="166" />
### layout
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.num_qubits">
Return number of qubits.
</Attribute>
### num\_state\_qubits
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.num_state_qubits">
The number of state qubits, i.e. the number of bits in each input register.
**Returns**
The number of state qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.CDKMRippleCarryAdder.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CDKMRippleCarryAdder.mdx
|
---
title: CHGate
description: API reference for qiskit.circuit.library.CHGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CHGate
---
# CHGate
<Class id="qiskit.circuit.library.CHGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/h.py#L127-L249" signature="qiskit.circuit.library.CHGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
Controlled-Hadamard gate.
Applies a Hadamard on the target qubit if the control is in the $|1\rangle$ state.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`ch()`](qiskit.circuit.QuantumCircuit#ch "qiskit.circuit.QuantumCircuit.ch") method.
**Circuit symbol:**
```python
q_0: βββ ββ
βββ΄ββ
q_1: β€ H β
βββββ
```
**Matrix Representation:**
$$
CH\ q_0, q_1 =
I \otimes |0\rangle\langle 0| + H \otimes |1\rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & \frac{1}{\sqrt{2}} & 0 & \frac{1}{\sqrt{2}} \\
0 & 0 & 1 & 0 \\
0 & \frac{1}{\sqrt{2}} & 0 & -\frac{1}{\sqrt{2}}
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be:
```python
βββββ
q_0: β€ H β
βββ¬ββ
q_1: βββ ββ
```
$$
CH\ q_1, q_0 =
|0\rangle\langle 0| \otimes I + |1\rangle\langle 1| \otimes H =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\
0 & 0 & \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}}
\end{pmatrix}
$$
</Admonition>
Create new CH gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CHGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CHGate.base_class "qiskit.circuit.library.CHGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CHGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CHGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CHGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CHGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CHGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CHGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CHGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CHGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CHGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CHGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CHGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CHGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CHGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CHGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CHGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/h.py#L244-L246" signature="inverse(annotated=False)">
Return inverted CH gate (itself).
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CHGate.mdx
|
---
title: CPhaseGate
description: API reference for qiskit.circuit.library.CPhaseGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CPhaseGate
---
# CPhaseGate
<Class id="qiskit.circuit.library.CPhaseGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/p.py#L159-L300" signature="qiskit.circuit.library.CPhaseGate(theta, label=None, ctrl_state=None, *, duration=None, unit='dt', _base_label=None)" modifiers="class">
Bases: [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.controlledgate.ControlledGate")
Controlled-Phase gate.
This is a diagonal and symmetric gate that induces a phase on the state of the target qubit, depending on the control state.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`cp()`](qiskit.circuit.QuantumCircuit#cp "qiskit.circuit.QuantumCircuit.cp") method.
**Circuit symbol:**
```python
q_0: ββ ββ
βΞ»
q_1: ββ ββ
```
**Matrix representation:**
$$
CPhase =
I \otimes |0\rangle\langle 0| + P \otimes |1\rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & e^{i\lambda}
\end{pmatrix}
$$
<Admonition title="See also" type="note">
`CRZGate`: Due to the global phase difference in the matrix definitions of Phase and RZ, CPhase and CRZ are different gates with a relative phase difference.
</Admonition>
Create new CPhase gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CPhaseGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CPhaseGate.base_class "qiskit.circuit.library.CPhaseGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CPhaseGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CPhaseGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CPhaseGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CPhaseGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CPhaseGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CPhaseGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CPhaseGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CPhaseGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CPhaseGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CPhaseGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CPhaseGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CPhaseGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CPhaseGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CPhaseGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### control
<Function id="qiskit.circuit.library.CPhaseGate.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/p.py#L247-L277" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False)">
Controlled version of this gate.
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of control qubits.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β An optional label for the gate \[Default: `None`]
* **ctrl\_state** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β control state expressed as integer, string (e.g.\`\`β110β`), or ``None`. If `None`, use all 1s.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β indicates whether the controlled gate can be implemented as an annotated gate.
**Returns**
controlled version of this gate.
**Return type**
[ControlledGate](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")
</Function>
### inverse
<Function id="qiskit.circuit.library.CPhaseGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/p.py#L279-L281" signature="inverse(annotated=False)">
Return inverted CPhase gate ($CPhase(\lambda)^{\dagger} = CPhase(-\lambda)$)
</Function>
### power
<Function id="qiskit.circuit.library.CPhaseGate.power" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/p.py#L292-L295" signature="power(exponent)">
Raise gate to a power.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CPhaseGate.mdx
|
---
title: CRXGate
description: API reference for qiskit.circuit.library.CRXGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CRXGate
---
# CRXGate
<Class id="qiskit.circuit.library.CRXGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/rx.py#L140-L284" signature="qiskit.circuit.library.CRXGate(theta, label=None, ctrl_state=None, *, duration=None, unit='dt', _base_label=None)" modifiers="class">
Bases: [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.controlledgate.ControlledGate")
Controlled-RX gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`crx()`](qiskit.circuit.QuantumCircuit#crx "qiskit.circuit.QuantumCircuit.crx") method.
**Circuit symbol:**
```python
q_0: βββββ ββββ
βββββ΄ββββ
q_1: β€ Rx(Ο΄) β
βββββββββ
```
**Matrix representation:**
$$
\newcommand{\rotationangle}{\frac{\theta}{2}}
CRX(\theta)\ q_0, q_1 =
I \otimes |0\rangle\langle 0| + RX(\theta) \otimes |1\rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & \cos\left(\rotationangle\right) & 0 & -i\sin\left(\rotationangle\right) \\
0 & 0 & 1 & 0 \\
0 & -i\sin\left(\rotationangle\right) & 0 & \cos\left(\rotationangle\right)
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be:
```python
βββββββββ
q_0: β€ Rx(Ο΄) β
βββββ¬ββββ
q_1: βββββ ββββ
```
$$
\newcommand{\rotationangle}{\frac{\theta}{2}}
CRX(\theta)\ q_1, q_0 =
|0\rangle\langle0| \otimes I + |1\rangle\langle1| \otimes RX(\theta) =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & \cos\left(\rotationangle\right) & -i\sin\left(\rotationangle\right) \\
0 & 0 & -i\sin\left(\rotationangle\right) & \cos\left(\rotationangle\right)
\end{pmatrix}
$$
</Admonition>
Create new CRX gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CRXGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CRXGate.base_class "qiskit.circuit.library.CRXGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CRXGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CRXGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CRXGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CRXGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CRXGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CRXGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CRXGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CRXGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CRXGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CRXGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CRXGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CRXGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CRXGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CRXGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CRXGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/rx.py#L253-L265" signature="inverse(annotated=False)">
Return inverse CRX gate (i.e. with the negative rotation angle).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as the inverse of this gate is always a [`CRXGate`](#qiskit.circuit.library.CRXGate "qiskit.circuit.library.CRXGate") with an inverted parameter value.
**Returns**
inverse gate.
**Return type**
[CRXGate](#qiskit.circuit.library.CRXGate "qiskit.circuit.library.CRXGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CRXGate.mdx
|
---
title: CRYGate
description: API reference for qiskit.circuit.library.CRYGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CRYGate
---
# CRYGate
<Class id="qiskit.circuit.library.CRYGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/ry.py#L139-L279" signature="qiskit.circuit.library.CRYGate(theta, label=None, ctrl_state=None, *, duration=None, unit='dt', _base_label=None)" modifiers="class">
Bases: [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.controlledgate.ControlledGate")
Controlled-RY gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`cry()`](qiskit.circuit.QuantumCircuit#cry "qiskit.circuit.QuantumCircuit.cry") method.
**Circuit symbol:**
```python
q_0: βββββ ββββ
βββββ΄ββββ
q_1: β€ Ry(Ο΄) β
βββββββββ
```
**Matrix representation:**
$$
\newcommand{\rotationangle}{\frac{\theta}{2}}
CRY(\theta)\ q_0, q_1 =
I \otimes |0\rangle\langle 0| + RY(\theta) \otimes |1\rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & \cos\left(\rotationangle\right) & 0 & -\sin\left(\rotationangle\right) \\
0 & 0 & 1 & 0 \\
0 & \sin\left(\rotationangle\right) & 0 & \cos\left(\rotationangle\right)
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be:
```python
βββββββββ
q_0: β€ Ry(Ο΄) β
βββββ¬ββββ
q_1: βββββ ββββ
```
$$
\newcommand{\rotationangle}{\frac{\theta}{2}}
CRY(\theta)\ q_1, q_0 =
|0\rangle\langle 0| \otimes I + |1\rangle\langle 1| \otimes RY(\theta) =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & \cos\left(\rotationangle\right) & -\sin\left(\rotationangle\right) \\
0 & 0 & \sin\left(\rotationangle\right) & \cos\left(\rotationangle\right)
\end{pmatrix}
$$
</Admonition>
Create new CRY gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CRYGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CRYGate.base_class "qiskit.circuit.library.CRYGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CRYGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CRYGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CRYGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CRYGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CRYGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CRYGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CRYGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CRYGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CRYGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CRYGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CRYGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CRYGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CRYGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CRYGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CRYGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/ry.py#L248-L260" signature="inverse(annotated=False)">
Return inverse CRY gate (i.e. with the negative rotation angle)
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as the inverse of this gate is always a [`CRYGate`](#qiskit.circuit.library.CRYGate "qiskit.circuit.library.CRYGate") with an inverted parameter value.
**Returns**
inverse gate.
**Return type**
[CRYGate](#qiskit.circuit.library.CRYGate "qiskit.circuit.library.CRYGate")
.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CRYGate.mdx
|
---
title: CRZGate
description: API reference for qiskit.circuit.library.CRZGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CRZGate
---
# CRZGate
<Class id="qiskit.circuit.library.CRZGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/rz.py#L151-L299" signature="qiskit.circuit.library.CRZGate(theta, label=None, ctrl_state=None, *, duration=None, unit='dt', _base_label=None)" modifiers="class">
Bases: [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.controlledgate.ControlledGate")
Controlled-RZ gate.
This is a diagonal but non-symmetric gate that induces a phase on the state of the target qubit, depending on the control state.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`crz()`](qiskit.circuit.QuantumCircuit#crz "qiskit.circuit.QuantumCircuit.crz") method.
**Circuit symbol:**
```python
q_0: βββββ ββββ
βββββ΄ββββ
q_1: β€ Rz(Ξ») β
βββββββββ
```
**Matrix representation:**
$$
CRZ(\lambda)\ q_0, q_1 =
I \otimes |0\rangle\langle 0| + RZ(\lambda) \otimes |1\rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & e^{-i\frac{\lambda}{2}} & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & e^{i\frac{\lambda}{2}}
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be:
```python
βββββββββ
q_0: β€ Rz(Ξ») β
βββββ¬ββββ
q_1: βββββ ββββ
```
$$
CRZ(\lambda)\ q_1, q_0 =
|0\rangle\langle 0| \otimes I + |1\rangle\langle 1| \otimes RZ(\lambda) =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & e^{-i\frac{\lambda}{2}} & 0 \\
0 & 0 & 0 & e^{i\frac{\lambda}{2}}
\end{pmatrix}
$$
</Admonition>
<Admonition title="See also" type="note">
`CU1Gate`: Due to the global phase difference in the matrix definitions of U1 and RZ, CU1 and CRZ are different gates with a relative phase difference.
</Admonition>
Create new CRZ gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CRZGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CRZGate.base_class "qiskit.circuit.library.CRZGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CRZGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CRZGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CRZGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CRZGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CRZGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CRZGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CRZGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CRZGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CRZGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CRZGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CRZGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CRZGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CRZGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CRZGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CRZGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/rz.py#L266-L278" signature="inverse(annotated=False)">
Return inverse CRZ gate (i.e. with the negative rotation angle).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β
**when set to `True`, this is typically used to return an**
[`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as the inverse of this gate is always a [`CRZGate`](#qiskit.circuit.library.CRZGate "qiskit.circuit.library.CRZGate") with an inverted parameter value.
**Returns:**
CRZGate: inverse gate.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CRZGate.mdx
|
---
title: CSdgGate
description: API reference for qiskit.circuit.library.CSdgGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CSdgGate
---
# CSdgGate
<Class id="qiskit.circuit.library.CSdgGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/s.py#L272-L355" signature="qiskit.circuit.library.CSdgGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
Controlled-S^dagger gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`csdg()`](qiskit.circuit.QuantumCircuit#csdg "qiskit.circuit.QuantumCircuit.csdg") method.
**Circuit symbol:**
```python
q_0: ββββ βββ
ββββ΄βββ
q_1: β€ Sdg β
βββββββ
```
**Matrix representation:**
$$
CS^\dagger \ q_0, q_1 =
I \otimes |0 \rangle\langle 0| + S^\dagger \otimes |1 \rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & -i
\end{pmatrix}
$$
Create new CSdg gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CSdgGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CSdgGate.base_class "qiskit.circuit.library.CSdgGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CSdgGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CSdgGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CSdgGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CSdgGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CSdgGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CSdgGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CSdgGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CSdgGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CSdgGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CSdgGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CSdgGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CSdgGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CSdgGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CSdgGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CSdgGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/s.py#L334-L346" signature="inverse(annotated=False)">
Return inverse of CSdgGate (CSGate).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as the inverse of this gate is always a [`CSGate`](qiskit.circuit.library.CSGate "qiskit.circuit.library.CSGate").
**Returns**
inverse of [`CSdgGate`](#qiskit.circuit.library.CSdgGate "qiskit.circuit.library.CSdgGate")
**Return type**
[CSGate](qiskit.circuit.library.CSGate "qiskit.circuit.library.CSGate")
</Function>
### power
<Function id="qiskit.circuit.library.CSdgGate.power" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/s.py#L348-L352" signature="power(exponent)">
Raise gate to a power.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CSdgGate.mdx
|
---
title: CSGate
description: API reference for qiskit.circuit.library.CSGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CSGate
---
# CSGate
<Class id="qiskit.circuit.library.CSGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/s.py#L185-L269" signature="qiskit.circuit.library.CSGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
Controlled-S gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`cs()`](qiskit.circuit.QuantumCircuit#cs "qiskit.circuit.QuantumCircuit.cs") method.
**Circuit symbol:**
```python
q_0: βββ ββ
βββ΄ββ
q_1: β€ S β
βββββ
```
**Matrix representation:**
$$
CS \ q_0, q_1 =
I \otimes |0 \rangle\langle 0| + S \otimes |1 \rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & i
\end{pmatrix}
$$
Create new CS gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CSGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CSGate.base_class "qiskit.circuit.library.CSGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CSGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CSGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CSGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CSGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CSGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CSGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CSGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CSGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CSGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CSGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CSGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CSGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CSGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CSGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CSGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/s.py#L248-L260" signature="inverse(annotated=False)">
Return inverse of CSGate (CSdgGate).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as the inverse of this gate is always a [`CSdgGate`](qiskit.circuit.library.CSdgGate "qiskit.circuit.library.CSdgGate").
**Returns**
inverse of [`CSGate`](#qiskit.circuit.library.CSGate "qiskit.circuit.library.CSGate")
**Return type**
[CSdgGate](qiskit.circuit.library.CSdgGate "qiskit.circuit.library.CSdgGate")
</Function>
### power
<Function id="qiskit.circuit.library.CSGate.power" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/s.py#L262-L266" signature="power(exponent)">
Raise gate to a power.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CSGate.mdx
|
---
title: CSwapGate
description: API reference for qiskit.circuit.library.CSwapGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CSwapGate
---
# CSwapGate
<Class id="qiskit.circuit.library.CSwapGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/swap.py#L138-L281" signature="qiskit.circuit.library.CSwapGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
Controlled-SWAP gate, also known as the Fredkin gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`cswap()`](qiskit.circuit.QuantumCircuit#cswap "qiskit.circuit.QuantumCircuit.cswap") and `fredkin()` methods.
**Circuit symbol:**
```python
q_0: ββ β
β
q_1: βXβ
β
q_2: βXβ
```
**Matrix representation:**
$$
CSWAP\ q_0, q_1, q_2 =
I \otimes I \otimes |0 \rangle \langle 0| +
SWAP \otimes |1 \rangle \langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_2. Thus a textbook matrix for this gate will be:
```python
q_0: βXβ
β
q_1: βXβ
β
q_2: ββ β
```
$$
CSWAP\ q_2, q_1, q_0 =
|0 \rangle \langle 0| \otimes I \otimes I +
|1 \rangle \langle 1| \otimes SWAP =
\begin{pmatrix}
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\
\end{pmatrix}
$$
</Admonition>
In the computational basis, this gate swaps the states of the two target qubits if the control qubit is in the $|1\rangle$ state.
$$
|0, b, c\rangle \rightarrow |0, b, c\rangle
|1, b, c\rangle \rightarrow |1, c, b\rangle
$$
Create new CSWAP gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CSwapGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CSwapGate.base_class "qiskit.circuit.library.CSwapGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CSwapGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CSwapGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CSwapGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CSwapGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CSwapGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CSwapGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CSwapGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CSwapGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CSwapGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CSwapGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CSwapGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CSwapGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CSwapGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CSwapGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CSwapGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/swap.py#L266-L278" signature="inverse(annotated=False)">
Return inverse CSwap gate (itself).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as this gate is self-inverse.
**Returns**
inverse gate (self-inverse).
**Return type**
[CSwapGate](#qiskit.circuit.library.CSwapGate "qiskit.circuit.library.CSwapGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CSwapGate.mdx
|
---
title: CSXGate
description: API reference for qiskit.circuit.library.CSXGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CSXGate
---
# CSXGate
<Class id="qiskit.circuit.library.CSXGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/sx.py#L207-L305" signature="qiskit.circuit.library.CSXGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
Controlled-βX gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`csx()`](qiskit.circuit.QuantumCircuit#csx "qiskit.circuit.QuantumCircuit.csx") method.
**Circuit symbol:**
```python
q_0: βββ ββ
βββ΄βββ
q_1: β€ βX β
ββββββ
```
**Matrix representation:**
$$
C\sqrt{X} \ q_0, q_1 =
I \otimes |0 \rangle\langle 0| + \sqrt{X} \otimes |1 \rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & (1 + i) / 2 & 0 & (1 - i) / 2 \\
0 & 0 & 1 & 0 \\
0 & (1 - i) / 2 & 0 & (1 + i) / 2
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be:
```python
ββββββ
q_0: β€ βX β
βββ¬βββ
q_1: βββ ββ
```
$$
C\sqrt{X}\ q_1, q_0 =
|0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes \sqrt{X} =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & (1 + i) / 2 & (1 - i) / 2 \\
0 & 0 & (1 - i) / 2 & (1 + i) / 2
\end{pmatrix}
$$
</Admonition>
Create new CSX gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CSXGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CSXGate.base_class "qiskit.circuit.library.CSXGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CSXGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CSXGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CSXGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CSXGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CSXGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CSXGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CSXGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CSXGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CSXGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CSXGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CSXGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CSXGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CSXGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CSXGate.unit">
Get the time unit of duration.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CSXGate.mdx
|
---
title: CU1Gate
description: API reference for qiskit.circuit.library.CU1Gate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CU1Gate
---
# CU1Gate
<Class id="qiskit.circuit.library.CU1Gate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/u1.py#L169-L317" signature="qiskit.circuit.library.CU1Gate(theta, label=None, ctrl_state=None, *, duration=None, unit='dt', _base_label=None)" modifiers="class">
Bases: [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.controlledgate.ControlledGate")
Controlled-U1 gate.
This is a diagonal and symmetric gate that induces a phase on the state of the target qubit, depending on the control state.
**Circuit symbol:**
```python
q_0: ββ ββ
βΞ»
q_1: ββ ββ
```
**Matrix representation:**
$$
CU1(\lambda) =
I \otimes |0\rangle\langle 0| + U1 \otimes |1\rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & e^{i\lambda}
\end{pmatrix}
$$
<Admonition title="See also" type="note">
`CRZGate`: Due to the global phase difference in the matrix definitions of U1 and RZ, CU1 and CRZ are different gates with a relative phase difference.
</Admonition>
Create new CU1 gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CU1Gate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CU1Gate.base_class "qiskit.circuit.library.CU1Gate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CU1Gate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CU1Gate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CU1Gate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CU1Gate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CU1Gate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CU1Gate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CU1Gate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CU1Gate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CU1Gate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CU1Gate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CU1Gate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CU1Gate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CU1Gate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CU1Gate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### control
<Function id="qiskit.circuit.library.CU1Gate.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/u1.py#L260-L290" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False)">
Controlled version of this gate.
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of control qubits.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β An optional label for the gate \[Default: `None`]
* **ctrl\_state** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β control state expressed as integer, string (e.g.\`\`β110β`), or ``None`. If `None`, use all 1s.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β indicates whether the controlled gate can be implemented as an annotated gate.
**Returns**
controlled version of this gate.
**Return type**
[ControlledGate](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")
</Function>
### inverse
<Function id="qiskit.circuit.library.CU1Gate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/u1.py#L292-L305" signature="inverse(annotated=False)">
Return inverted CU1 gate ($CU1(\lambda)^{\dagger} = CU1(-\lambda))$
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as the inverse of this gate is always a [`CU1Gate`](#qiskit.circuit.library.CU1Gate "qiskit.circuit.library.CU1Gate") with inverse parameter values.
**Returns**
inverse gate.
**Return type**
[CU1Gate](#qiskit.circuit.library.CU1Gate "qiskit.circuit.library.CU1Gate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CU1Gate.mdx
|
---
title: CU3Gate
description: API reference for qiskit.circuit.library.CU3Gate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CU3Gate
---
# CU3Gate
<Class id="qiskit.circuit.library.CU3Gate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/u3.py#L167-L333" signature="qiskit.circuit.library.CU3Gate(theta, phi, lam, label=None, ctrl_state=None, *, duration=None, unit='dt', _base_label=None)" modifiers="class">
Bases: [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.controlledgate.ControlledGate")
Controlled-U3 gate (3-parameter two-qubit gate).
This is a controlled version of the U3 gate (generic single qubit rotation). It is restricted to 3 parameters, and so cannot cover generic two-qubit controlled gates).
**Circuit symbol:**
```python
q_0: βββββββ ββββββ
βββββββ΄ββββββ
q_1: β€ U3(Ο΄,Ο,Ξ») β
βββββββββββββ
```
**Matrix representation:**
$$
\newcommand{\rotationangle}{\frac{\theta}{2}}
CU3(\theta, \phi, \lambda)\ q_0, q_1 =
I \otimes |0\rangle\langle 0| +
U3(\theta,\phi,\lambda) \otimes |1\rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & \cos(\rotationangle) & 0 & -e^{i\lambda}\sin(\rotationangle) \\
0 & 0 & 1 & 0 \\
0 & e^{i\phi}\sin(\rotationangle) & 0 & e^{i(\phi+\lambda)}\cos(\rotationangle)
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be:
```python
βββββββββββββ
q_0: β€ U3(Ο΄,Ο,Ξ») β
βββββββ¬ββββββ
q_1: βββββββ ββββββ
```
$$
\newcommand{\rotationangle}{\frac{\theta}{2}}
CU3(\theta, \phi, \lambda)\ q_1, q_0 =
|0\rangle\langle 0| \otimes I +
|1\rangle\langle 1| \otimes U3(\theta,\phi,\lambda) =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & \cos(\rotationangle) & -e^{i\lambda}\sin(\rotationangle) \\
0 & 0 & e^{i\phi}\sin(\rotationangle) & e^{i(\phi+\lambda)}\cos(\rotationangle)
\end{pmatrix}
$$
</Admonition>
Create new CU3 gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CU3Gate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CU3Gate.base_class "qiskit.circuit.library.CU3Gate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CU3Gate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CU3Gate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CU3Gate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CU3Gate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CU3Gate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CU3Gate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CU3Gate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CU3Gate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CU3Gate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CU3Gate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CU3Gate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CU3Gate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CU3Gate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CU3Gate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CU3Gate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/u3.py#L289-L306" signature="inverse(annotated=False)">
Return inverted CU3 gate.
$CU3(\theta,\phi,\lambda)^{\dagger} =CU3(-\theta,-\phi,-\lambda))$
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as the inverse of this gate is always a [`CU3Gate`](#qiskit.circuit.library.CU3Gate "qiskit.circuit.library.CU3Gate") with inverse parameter values.
**Returns**
inverse gate.
**Return type**
[CU3Gate](#qiskit.circuit.library.CU3Gate "qiskit.circuit.library.CU3Gate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CU3Gate.mdx
|
---
title: CUGate
description: API reference for qiskit.circuit.library.CUGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CUGate
---
# CUGate
<Class id="qiskit.circuit.library.CUGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/u.py#L194-L375" signature="qiskit.circuit.library.CUGate(theta, phi, lam, gamma, label=None, ctrl_state=None, *, duration=None, unit='dt', _base_label=None)" modifiers="class">
Bases: [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.controlledgate.ControlledGate")
Controlled-U gate (4-parameter two-qubit gate).
This is a controlled version of the U gate (generic single qubit rotation), including a possible global phase $e^{i\gamma}$ of the U gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`cu()`](qiskit.circuit.QuantumCircuit#cu "qiskit.circuit.QuantumCircuit.cu") method.
**Circuit symbol:**
```python
q_0: βββββββ ββββββ
βββββββ΄βββββββ
q_1: β€ U(Ο΄,Ο,Ξ»,Ξ³) β
ββββββββββββββ
```
**Matrix representation:**
$$
\newcommand{\rotationangle}{\frac{\theta}{2}}
CU(\theta, \phi, \lambda, \gamma)\ q_0, q_1 =
I \otimes |0\rangle\langle 0| +
e^{i\gamma} U(\theta,\phi,\lambda) \otimes |1\rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & e^{i\gamma}\cos(\rotationangle) &
0 & -e^{i(\gamma + \lambda)}\sin(\rotationangle) \\
0 & 0 & 1 & 0 \\
0 & e^{i(\gamma+\phi)}\sin(\rotationangle) &
0 & e^{i(\gamma+\phi+\lambda)}\cos(\rotationangle)
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be:
```python
ββββββββββββββ
q_0: β€ U(Ο΄,Ο,Ξ»,Ξ³) β
βββββββ¬βββββββ
q_1: βββββββ βββββββ
```
$$
\newcommand{\rotationangle}{\frac{\theta}{2}}
CU(\theta, \phi, \lambda, \gamma)\ q_1, q_0 =
|0\rangle\langle 0| \otimes I +
e^{i\gamma}|1\rangle\langle 1| \otimes U(\theta,\phi,\lambda) =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & e^{i\gamma} \cos(\rotationangle) & -e^{i(\gamma + \lambda)}\sin(\rotationangle) \\
0 & 0 &
e^{i(\gamma + \phi)}\sin(\rotationangle) & e^{i(\gamma + \phi+\lambda)}\cos(\rotationangle)
\end{pmatrix}
$$
</Admonition>
Create new CU gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CUGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CUGate.base_class "qiskit.circuit.library.CUGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CUGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CUGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CUGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CUGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CUGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CUGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CUGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CUGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CUGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CUGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CUGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CUGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CUGate.params" />
### unit
<Attribute id="qiskit.circuit.library.CUGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CUGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/u.py#L316-L337" signature="inverse(annotated=False)">
Return inverted CU gate.
$CU(\theta,\phi,\lambda,\gamma)^{\dagger} = CU(-\theta,-\phi,-\lambda,-\gamma))$
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as the inverse of this gate is always a [`CUGate`](#qiskit.circuit.library.CUGate "qiskit.circuit.library.CUGate") with inverse parameter values.
**Returns**
inverse gate.
**Return type**
[CUGate](#qiskit.circuit.library.CUGate "qiskit.circuit.library.CUGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CUGate.mdx
|
---
title: CXGate
description: API reference for qiskit.circuit.library.CXGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CXGate
---
# CXGate
<Class id="qiskit.circuit.library.CXGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L151-L293" signature="qiskit.circuit.library.CXGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
Controlled-X gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`cx()`](qiskit.circuit.QuantumCircuit#cx "qiskit.circuit.QuantumCircuit.cx") and `cnot()` methods.
**Circuit symbol:**
```python
q_0: βββ ββ
βββ΄ββ
q_1: β€ X β
βββββ
```
**Matrix representation:**
$$
CX\ q_0, q_1 =
I \otimes |0\rangle\langle0| + X \otimes |1\rangle\langle1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 \\
0 & 0 & 1 & 0 \\
0 & 1 & 0 & 0
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be:
```python
βββββ
q_0: β€ X β
βββ¬ββ
q_1: βββ ββ
```
$$
CX\ q_1, q_0 =
|0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes X =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1 \\
0 & 0 & 1 & 0
\end{pmatrix}
$$
</Admonition>
In the computational basis, this gate flips the target qubit if the control qubit is in the $|1\rangle$ state. In this sense it is similar to a classical XOR gate.
$$
`|a, b\rangle \rightarrow |a, a \oplus b\rangle`
$$
Create new CX gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CXGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CXGate.base_class "qiskit.circuit.library.CXGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CXGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CXGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CXGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CXGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CXGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CXGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CXGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CXGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CXGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CXGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CXGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CXGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CXGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CXGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### control
<Function id="qiskit.circuit.library.CXGate.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L240-L276" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False)">
Return a controlled-X gate with more control lines.
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of control qubits.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β An optional label for the gate \[Default: `None`]
* **ctrl\_state** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β control state expressed as integer, string (e.g.\`\`β110β`), or ``None`. If `None`, use all 1s.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β indicates whether the controlled gate can be implemented as an annotated gate.
**Returns**
controlled version of this gate.
**Return type**
[ControlledGate](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")
</Function>
### inverse
<Function id="qiskit.circuit.library.CXGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/x.py#L278-L290" signature="inverse(annotated=False)">
Return inverted CX gate (itself).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as this gate is self-inverse.
**Returns**
inverse gate (self-inverse).
**Return type**
[CXGate](#qiskit.circuit.library.CXGate "qiskit.circuit.library.CXGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CXGate.mdx
|
---
title: CYGate
description: API reference for qiskit.circuit.library.CYGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CYGate
---
# CYGate
<Class id="qiskit.circuit.library.CYGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/y.py#L143-L256" signature="qiskit.circuit.library.CYGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
Controlled-Y gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`cy()`](qiskit.circuit.QuantumCircuit#cy "qiskit.circuit.QuantumCircuit.cy") method.
**Circuit symbol:**
```python
q_0: βββ ββ
βββ΄ββ
q_1: β€ Y β
βββββ
```
**Matrix representation:**
$$
CY\ q_0, q_1 =
I \otimes |0 \rangle\langle 0| + Y \otimes |1 \rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 0 & 0 & -i \\
0 & 0 & 1 & 0 \\
0 & i & 0 & 0
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be:
```python
βββββ
q_0: β€ Y β
βββ¬ββ
q_1: βββ ββ
```
$$
CY\ q_1, q_0 =
|0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes Y =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 0 & -i \\
0 & 0 & i & 0
\end{pmatrix}
$$
</Admonition>
Create new CY gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CYGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CYGate.base_class "qiskit.circuit.library.CYGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CYGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CYGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CYGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CYGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CYGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CYGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CYGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CYGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CYGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CYGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CYGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CYGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CYGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CYGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CYGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/y.py#L241-L253" signature="inverse(annotated=False)">
Return inverted CY gate (itself).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as this gate is self-inverse.
**Returns**
inverse gate (self-inverse).
**Return type**
[CYGate](#qiskit.circuit.library.CYGate "qiskit.circuit.library.CYGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CYGate.mdx
|
---
title: CZGate
description: API reference for qiskit.circuit.library.CZGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.CZGate
---
# CZGate
<Class id="qiskit.circuit.library.CZGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/z.py#L151-L242" signature="qiskit.circuit.library.CZGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate "qiskit.circuit.singleton.SingletonControlledGate")
Controlled-Z gate.
This is a Clifford and symmetric gate.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`cz()`](qiskit.circuit.QuantumCircuit#cz "qiskit.circuit.QuantumCircuit.cz") method.
**Circuit symbol:**
```python
q_0: ββ β
β
q_1: ββ β
```
**Matrix representation:**
$$
CZ\ q_0, q_1 =
I \otimes |0\rangle\langle 0| + Z \otimes |1\rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & -1
\end{pmatrix}
$$
In the computational basis, this gate flips the phase of the target qubit if the control qubit is in the $|1\rangle$ state.
Create new CZ gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.CZGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CZGate.base_class "qiskit.circuit.library.CZGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.CZGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.CZGate.condition_bits">
Get Clbits in condition.
</Attribute>
### ctrl\_state
<Attribute id="qiskit.circuit.library.CZGate.ctrl_state">
Return the control state of the gate as a decimal integer.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.CZGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.CZGate.definition">
Return definition in terms of other basic gates. If the gate has open controls, as determined from self.ctrl\_state, the returned definition is conjugated with X without changing the internal \_definition.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.CZGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.CZGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.CZGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.CZGate.name">
Get name of gate. If the gate has open controls the gate name will become:
> \<original\_name\_o\<ctrl\_state>
where \<original\_name> is the gate name for the default case of closed control qubits and \<ctrl\_state> is the integer value of the control state for the gate.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.CZGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_ctrl\_qubits
<Attribute id="qiskit.circuit.library.CZGate.num_ctrl_qubits">
Get number of control qubits.
**Returns**
The number of control qubits for the gate.
**Return type**
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.CZGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.CZGate.params">
Get parameters from base\_gate.
**Returns**
List of gate parameters.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β Controlled gate does not define a base gate
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.CZGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.CZGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/z.py#L227-L239" signature="inverse(annotated=False)">
Return inverted CZ gate (itself).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as this gate is self-inverse.
**Returns**
inverse gate (self-inverse).
**Return type**
[CZGate](#qiskit.circuit.library.CZGate "qiskit.circuit.library.CZGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.CZGate.mdx
|
---
title: DCXGate
description: API reference for qiskit.circuit.library.DCXGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.DCXGate
---
# DCXGate
<Class id="qiskit.circuit.library.DCXGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/dcx.py#L20-L74" signature="qiskit.circuit.library.DCXGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate "qiskit.circuit.singleton.SingletonGate")
Double-CNOT gate.
A 2-qubit Clifford gate consisting of two back-to-back CNOTs with alternate controls.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`dcx()`](qiskit.circuit.QuantumCircuit#dcx "qiskit.circuit.QuantumCircuit.dcx") method.
```python
βββββ
q_0: βββ βββ€ X β
βββ΄βββββ¬ββ
q_1: β€ X ββββ ββ
βββββ
```
This is a classical logic gate, equivalent to a CNOT-SWAP (CNS) sequence, and locally equivalent to an iSWAP.
$$
DCX\ q_0, q_1 =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0
\end{pmatrix}
$$
Create new DCX gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.DCXGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.DCXGate.base_class "qiskit.circuit.library.DCXGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.DCXGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.DCXGate.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.DCXGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.DCXGate.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.DCXGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.DCXGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.DCXGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.DCXGate.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.DCXGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.DCXGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.DCXGate.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.DCXGate.unit">
Get the time unit of duration.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.DCXGate.mdx
|
---
title: Diagonal
description: API reference for qiskit.circuit.library.Diagonal
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.Diagonal
---
# Diagonal
<Class id="qiskit.circuit.library.Diagonal" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/diagonal.py#L31-L125" signature="qiskit.circuit.library.Diagonal(diag)" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
Diagonal circuit.
Circuit symbol:
```python
βββββββββββββ
q_0: β€0 β
β β
q_1: β€1 Diagonal β
β β
q_2: β€2 β
βββββββββββββ
```
Matrix form:
$$
\text{DiagonalGate}\ q_0, q_1, .., q_{n-1} =
\begin{pmatrix}
D[0] & 0 & \dots & 0 \\
0 & D[1] & \dots & 0 \\
\vdots & \vdots & \ddots & 0 \\
0 & 0 & \dots & D[n-1]
\end{pmatrix}
$$
Diagonal gates are useful as representations of Boolean functions, as they can map from $\{0,1\}^{2^n}$ to $\{0,1\}^{2^n}$ space. For example a phase oracle can be seen as a diagonal gate with $\{1, -1\}$ on the diagonals. Such an oracle will induce a $+1$ or :math\`-1\` phase on the amplitude of any corresponding basis state.
Diagonal gates appear in many classically hard oracular problems such as Forrelation or Hidden Shift circuits.
Diagonal gates are represented and simulated more efficiently than a dense $2^n \times 2^n$ unitary matrix.
The reference implementation is via the method described in Theorem 7 of \[1]. The code is based on Emanuel Malvettiβs semester thesis at ETH in 2018, supervised by Raban Iten and Prof. Renato Renner.
**Reference:**
\[1] Shende et al., Synthesis of Quantum Logic Circuits, 2009 [arXiv:0406176](https://arxiv.org/pdf/quant-ph/0406176.pdf)
**Parameters**
**diag** (*Sequence\[*[*complex*](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)")*]*) β List of the $2^k$ diagonal entries (for a diagonal gate on $k$ qubits).
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the list of the diagonal entries or the qubit list is in bad format; if the number of diagonal entries is not $2^k$, where $k$ denotes the number of qubits.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.Diagonal.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.Diagonal.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.Diagonal.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.Diagonal.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.Diagonal.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.Diagonal.instances" attributeValue="166" />
### layout
<Attribute id="qiskit.circuit.library.Diagonal.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.Diagonal.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.Diagonal.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.Diagonal.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.Diagonal.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.Diagonal.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.Diagonal.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.Diagonal.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.Diagonal.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.Diagonal.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.Diagonal.mdx
|
---
title: DiagonalGate
description: API reference for qiskit.circuit.library.DiagonalGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.DiagonalGate
---
# DiagonalGate
<Class id="qiskit.circuit.library.DiagonalGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/diagonal.py#L128-L154" signature="qiskit.circuit.library.DiagonalGate(diag)" modifiers="class">
Bases: [`Gate`](qiskit.circuit.Gate "qiskit.circuit.gate.Gate")
Gate implementing a diagonal transformation.
**Parameters**
**diag** (*Sequence\[*[*complex*](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)")*]*) β list of the $2^k$ diagonal entries (for a diagonal gate on $k$ qubits).
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.DiagonalGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.DiagonalGate.base_class "qiskit.circuit.library.DiagonalGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.DiagonalGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.DiagonalGate.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.DiagonalGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.DiagonalGate.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.DiagonalGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.DiagonalGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.DiagonalGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.DiagonalGate.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.DiagonalGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.DiagonalGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.DiagonalGate.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.DiagonalGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.DiagonalGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/diagonal.py#L152-L154" signature="inverse(annotated=False)">
Return the inverse of the diagonal gate.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.library.DiagonalGate.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/diagonal.py#L144-L150" signature="validate_parameter(parameter)">
Diagonal Gate parameter should accept complex (in addition to the Gate parameter types) and always return build-in complex.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.DiagonalGate.mdx
|
---
title: DraperQFTAdder
description: API reference for qiskit.circuit.library.DraperQFTAdder
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.DraperQFTAdder
---
# DraperQFTAdder
<Class id="qiskit.circuit.library.DraperQFTAdder" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/arithmetic/adders/draper_qft_adder.py#L24-L116" signature="qiskit.circuit.library.DraperQFTAdder(num_state_qubits, kind='fixed', name='DraperQFTAdder')" modifiers="class">
Bases: `Adder`
A circuit that uses QFT to perform in-place addition on two qubit registers.
For registers with $n$ qubits, the QFT adder can perform addition modulo $2^n$ (with `kind="fixed"`) or ordinary addition by adding a carry qubits (with `kind="half"`).
As an example, a non-fixed\_point QFT adder circuit that performs addition on two 2-qubit sized registers is as follows:
```python
a_0: ββββββββββ βββββββ βββββββββββββββββββββββββ ββββββββββββββββ
β β β
a_1: ββββββββββΌβββββββΌβββββββββ βββββββ βββββββββΌββββββββββββββββ
ββββββββ βP(Ο) β β β β βββββββββ
b_0: β€0 βββ βββββββΌβββββββββΌβββββββΌβββββββββΌββββββββ€0 β
β β βP(Ο/2) βP(Ο) β β β β
b_1: β€1 qft ββββββββββ βββββββββ βββββββΌβββββββββΌββββββββ€1 iqft β
β β βP(Ο/2) βP(Ο/4) β β
cout_0: β€2 ββββββββββββββββββββββββββ βββββββββ ββββββββ€2 β
ββββββββ βββββββββ
```
**References:**
\[1] T. G. Draper, Addition on a Quantum Computer, 2000. [arXiv:quant-ph/0008033](https://arxiv.org/pdf/quant-ph/0008033.pdf)
\[2] Ruiz-Perez et al., Quantum arithmetic with the Quantum Fourier Transform, 2017. [arXiv:1411.5949](https://arxiv.org/pdf/1411.5949.pdf)
\[3] Vedral et al., Quantum Networks for Elementary Arithmetic Operations, 1995. [arXiv:quant-ph/9511018](https://arxiv.org/pdf/quant-ph/9511018.pdf)
**Parameters**
* **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β The number of qubits in either input register for state $|a\rangle$ or $|b\rangle$. The two input registers must have the same number of qubits.
* **kind** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The kind of adder, can be `'half'` for a half adder or `'fixed'` for a fixed-sized adder. A half adder contains a carry-out to represent the most-significant bit, but the fixed-sized adder doesnβt and hence performs addition modulo `2 ** num_state_qubits`.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The name of the circuit object.
**Raises**
[**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.12)") β If `num_state_qubits` is lower than 1.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.DraperQFTAdder.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.DraperQFTAdder.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.DraperQFTAdder.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.DraperQFTAdder.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.DraperQFTAdder.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.DraperQFTAdder.instances" attributeValue="166" />
### layout
<Attribute id="qiskit.circuit.library.DraperQFTAdder.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.DraperQFTAdder.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.DraperQFTAdder.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.DraperQFTAdder.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.DraperQFTAdder.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.DraperQFTAdder.num_qubits">
Return number of qubits.
</Attribute>
### num\_state\_qubits
<Attribute id="qiskit.circuit.library.DraperQFTAdder.num_state_qubits">
The number of state qubits, i.e. the number of bits in each input register.
**Returns**
The number of state qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.DraperQFTAdder.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.DraperQFTAdder.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.DraperQFTAdder.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.DraperQFTAdder.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.DraperQFTAdder.mdx
|
---
title: ECRGate
description: API reference for qiskit.circuit.library.ECRGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.ECRGate
---
# ECRGate
<Class id="qiskit.circuit.library.ECRGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/ecr.py#L24-L127" signature="qiskit.circuit.library.ECRGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate "qiskit.circuit.singleton.SingletonGate")
An echoed cross-resonance gate.
This gate is maximally entangling and is equivalent to a CNOT up to single-qubit pre-rotations. The echoing procedure mitigates some unwanted terms (terms other than ZX) to cancel in an experiment. More specifically, this gate implements $\frac{1}{\sqrt{2}}(IX-XY)$.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`ecr()`](qiskit.circuit.QuantumCircuit#ecr "qiskit.circuit.QuantumCircuit.ecr") method.
**Circuit Symbol:**
```python
βββββββββββ βββββββββββββββββββββββββββββββββββββββ
q_0: β€0 β q_0: β€0 ββ€ RX(pi) ββ€0 β
β ECR β = β RZX(pi/4) ββββββββββββ RZX(-pi/4) β
q_1: β€1 β q_1: β€1 ββββββββββββ€1 β
βββββββββββ ββββββββββββββ βββββββββββββββ
```
**Matrix Representation:**
$$
ECR\ q_0, q_1 = \frac{1}{\sqrt{2}}
\begin{pmatrix}
0 & 1 & 0 & i \\
1 & 0 & -i & 0 \\
0 & i & 0 & 1 \\
-i & 0 & 1 & 0
\end{pmatrix}
$$
<Admonition title="Note" type="note">
In Qiskitβs convention, higher qubit indices are more significant (little endian convention). In the above example we apply the gate on (q\_0, q\_1) which results in the $X \otimes Z$ tensor order. Instead, if we apply it on (q\_1, q\_0), the matrix will be $Z \otimes X$:
```python
βββββββββββ
q_0: β€1 β
β ECR β
q_1: β€0 β
βββββββββββ
```
$$
ECR\ q_0, q_1 = \frac{1}{\sqrt{2}}
\begin{pmatrix}
0 & 0 & 1 & i \\
0 & 0 & i & 1 \\
1 & -i & 0 & 0 \\
-i & 1 & 0 & 0
\end{pmatrix}
$$
</Admonition>
Create new ECR gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.ECRGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.ECRGate.base_class "qiskit.circuit.library.ECRGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.ECRGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.ECRGate.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.ECRGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.ECRGate.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.ECRGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.ECRGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.ECRGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.ECRGate.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.ECRGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.ECRGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.ECRGate.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.ECRGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.ECRGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/ecr.py#L112-L124" signature="inverse(annotated=False)">
Return inverse ECR gate (itself).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as this gate is self-inverse.
**Returns**
inverse gate (self-inverse).
**Return type**
[ECRGate](#qiskit.circuit.library.ECRGate "qiskit.circuit.library.ECRGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.ECRGate.mdx
|
---
title: EfficientSU2
description: API reference for qiskit.circuit.library.EfficientSU2
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.EfficientSU2
---
# EfficientSU2
<Class id="qiskit.circuit.library.EfficientSU2" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/n_local/efficient_su2.py#L29-L164" signature="qiskit.circuit.library.EfficientSU2(num_qubits=None, su2_gates=None, entanglement='reverse_linear', reps=3, skip_unentangled_qubits=False, skip_final_rotation_layer=False, parameter_prefix='ΞΈ', insert_barriers=False, initial_state=None, name='EfficientSU2', flatten=None)" modifiers="class">
Bases: [`TwoLocal`](qiskit.circuit.library.TwoLocal "qiskit.circuit.library.n_local.two_local.TwoLocal")
The hardware efficient SU(2) 2-local circuit.
The `EfficientSU2` circuit consists of layers of single qubit operations spanned by SU(2) and $CX$ entanglements. This is a heuristic pattern that can be used to prepare trial wave functions for variational quantum algorithms or classification circuit for machine learning.
SU(2) stands for special unitary group of degree 2, its elements are $2 \times 2$ unitary matrices with determinant 1, such as the Pauli rotation gates.
On 3 qubits and using the Pauli $Y$ and $Z$ su2\_gates as single qubit gates, the hardware efficient SU(2) circuit is represented by:
```python
ββββββββββββββββββββββββ β β β ββββββββββββββββββββββββββ
β€ RY(ΞΈ[0]) ββ€ RZ(ΞΈ[3]) ββββββββββββ βββββ ... ββββ€ RY(ΞΈ[12]) ββ€ RZ(ΞΈ[15]) β
ββββββββββββ€ββββββββββββ€ β βββ΄ββ β β βββββββββββββ€βββββββββββββ€
β€ RY(ΞΈ[1]) ββ€ RZ(ΞΈ[4]) βββββββ βββ€ X ββββ ... ββββ€ RY(ΞΈ[13]) ββ€ RZ(ΞΈ[16]) β
ββββββββββββ€ββββββββββββ€ β βββ΄βββββββ β β βββββββββββββ€βββββββββββββ€
β€ RY(ΞΈ[2]) ββ€ RZ(ΞΈ[5]) βββββ€ X βββββββββ ... ββββ€ RY(ΞΈ[14]) ββ€ RZ(ΞΈ[17]) β
ββββββββββββββββββββββββ β βββββ β β ββββββββββββββββββββββββββ
```
See [`RealAmplitudes`](qiskit.circuit.library.RealAmplitudes "qiskit.circuit.library.RealAmplitudes") for more detail on the possible arguments and options such as skipping unentanglement qubits, which apply here too.
**Examples**
```python
>>> circuit = EfficientSU2(3, reps=1)
>>> print(circuit)
ββββββββββββββββββββββββ ββββββββββββββββββββββββ
q_0: β€ RY(ΞΈ[0]) ββ€ RZ(ΞΈ[3]) ββββ βββββ βββ€ RY(ΞΈ[6]) ββ€ RZ(ΞΈ[9]) ββββββββββββββ
ββββββββββββ€ββββββββββββ€βββ΄ββ β ββββββββββββββββββββββββ€βββββββββββββ
q_1: β€ RY(ΞΈ[1]) ββ€ RZ(ΞΈ[4]) ββ€ X ββββΌββββββββ βββββββ€ RY(ΞΈ[7]) ββ€ RZ(ΞΈ[10]) β
ββββββββββββ€ββββββββββββ€ββββββββ΄ββ βββ΄ββ ββββββββββββ€βββββββββββββ€
q_2: β€ RY(ΞΈ[2]) ββ€ RZ(ΞΈ[5]) βββββββ€ X βββββ€ X ββββββ€ RY(ΞΈ[8]) ββ€ RZ(ΞΈ[11]) β
ββββββββββββββββββββββββ βββββ βββββ βββββββββββββββββββββββββ
```
```python
>>> ansatz = EfficientSU2(4, su2_gates=['rx', 'y'], entanglement='circular', reps=1)
>>> qc = QuantumCircuit(4) # create a circuit and append the RY variational form
>>> qc.compose(ansatz, inplace=True)
>>> qc.draw()
ββββββββββββββββββββββ ββββββββββββ βββββ
q_0: β€ RX(ΞΈ[0]) ββ€ Y ββ€ X ββββ βββ€ RX(ΞΈ[4]) βββββ€ Y ββββββββββββββββββββββ
ββββββββββββ€βββββ€βββ¬βββββ΄ββββββββββββββββββ΄ββββ΄ββββ βββββ
q_1: β€ RX(ΞΈ[1]) ββ€ Y ββββΌβββ€ X βββββββ βββββββ€ RX(ΞΈ[5]) βββββ€ Y ββββββββββ
ββββββββββββ€βββββ€ β βββββ βββ΄ββ ββββββββββββββββ΄ββββ΄βββββββββ
q_2: β€ RX(ΞΈ[2]) ββ€ Y ββββΌβββββββββββ€ X βββββββββββ βββββββ€ RX(ΞΈ[6]) ββ€ Y β
ββββββββββββ€βββββ€ β βββββ βββ΄ββ ββββββββββββ€βββββ€
q_3: β€ RX(ΞΈ[3]) ββ€ Y ββββ βββββββββββββββββββββββ€ X ββββββ€ RX(ΞΈ[7]) ββ€ Y β
βββββββββββββββββ βββββ βββββββββββββββββ
```
**Parameters**
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β The number of qubits of the EfficientSU2 circuit.
* **reps** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Specifies how often the structure of a rotation layer followed by an entanglement layer is repeated.
* **su2\_gates** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*type*](https://docs.python.org/3/library/functions.html#type "(in Python v3.12)") *|*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction "qiskit.circuit.Instruction") *|*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*type*](https://docs.python.org/3/library/functions.html#type "(in Python v3.12)") *|*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction "qiskit.circuit.Instruction") *|*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")*] | None*) β The SU(2) single qubit gates to apply in single qubit gate layers. If only one gate is provided, the same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order.
* **entanglement** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]] | Callable\[\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*],* [*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]]*) β Specifies the entanglement structure. Can be a string (βfullβ, βlinearβ , βreverse\_linearβ, βcircularβ or βscaβ), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to βreverse\_linearβ entanglement. Note that βreverse\_linearβ entanglement provides the same unitary as βfullβ with fewer entangling gates. See the Examples section of [`TwoLocal`](qiskit.circuit.library.TwoLocal "qiskit.circuit.library.TwoLocal") for more detail.
* **initial\_state** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") *| None*) β A QuantumCircuit object to prepend to the circuit.
* **skip\_unentangled\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β If True, the single qubit gates are only applied to qubits that are entangled with another qubit. If False, the single qubit gates are applied to each qubit in the Ansatz. Defaults to False.
* **skip\_final\_rotation\_layer** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β If False, a rotation layer is added at the end of the ansatz. If True, no rotation layer is added.
* **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The parameterized gates require a parameter to be defined, for which we use [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector").
* **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β If True, barriers are inserted in between each layer. If False, no barriers are inserted.
* **flatten** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)") *| None*) β Set this to `True` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if youβre using this circuit for anything besides visualization its **strongly** recommended to set this flag to `True` to avoid a large performance overhead for parameter binding.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.EfficientSU2.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.EfficientSU2.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.EfficientSU2.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.EfficientSU2.data" />
### entanglement
<Attribute id="qiskit.circuit.library.EfficientSU2.entanglement">
Get the entanglement strategy.
**Returns**
The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted.
</Attribute>
### entanglement\_blocks
<Attribute id="qiskit.circuit.library.EfficientSU2.entanglement_blocks">
The blocks in the entanglement layers.
**Returns**
The blocks in the entanglement layers.
</Attribute>
### flatten
<Attribute id="qiskit.circuit.library.EfficientSU2.flatten">
Returns whether the circuit is wrapped in nested gates/instructions or flattened.
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.EfficientSU2.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### initial\_state
<Attribute id="qiskit.circuit.library.EfficientSU2.initial_state">
Return the initial state that is added in front of the n-local circuit.
**Returns**
The initial state.
</Attribute>
### insert\_barriers
<Attribute id="qiskit.circuit.library.EfficientSU2.insert_barriers">
If barriers are inserted in between the layers or not.
**Returns**
`True`, if barriers are inserted in between the layers, `False` if not.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.EfficientSU2.instances" attributeValue="166" />
### layout
<Attribute id="qiskit.circuit.library.EfficientSU2.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.EfficientSU2.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.EfficientSU2.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.EfficientSU2.num_clbits">
Return number of classical bits.
</Attribute>
### num\_layers
<Attribute id="qiskit.circuit.library.EfficientSU2.num_layers">
Return the number of layers in the n-local circuit.
**Returns**
The number of layers in the circuit.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.EfficientSU2.num_parameters" />
### num\_parameters\_settable
<Attribute id="qiskit.circuit.library.EfficientSU2.num_parameters_settable">
The number of total parameters that can be set to distinct values.
This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from `num_parameters` which counts the number of unique [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects currently in the circuit.
**Returns**
The number of parameters originally available in the circuit.
<Admonition title="Note" type="note">
This quantity does not require the circuit to be built yet.
</Admonition>
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.EfficientSU2.num_qubits">
Returns the number of qubits in this circuit.
**Returns**
The number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.EfficientSU2.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### ordered\_parameters
<Attribute id="qiskit.circuit.library.EfficientSU2.ordered_parameters">
The parameters used in the underlying circuit.
This includes float values and duplicates.
**Examples**
```python
>>> # prepare circuit ...
>>> print(nlocal)
βββββββββββββββββββββββββββββββββββββββββββββ
q_0: β€ Ry(1) ββ€ Ry(ΞΈ[1]) ββ€ Ry(ΞΈ[1]) ββ€ Ry(ΞΈ[3]) β
βββββββββββββββββββββββββββββββββββββββββββββ
>>> nlocal.parameters
{Parameter(ΞΈ[1]), Parameter(ΞΈ[3])}
>>> nlocal.ordered_parameters
[1, Parameter(ΞΈ[1]), Parameter(ΞΈ[1]), Parameter(ΞΈ[3])]
```
**Returns**
The parameters objects used in the circuit.
</Attribute>
### parameter\_bounds
<Attribute id="qiskit.circuit.library.EfficientSU2.parameter_bounds">
Return the parameter bounds.
**Returns**
The parameter bounds.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.EfficientSU2.parameters" />
### preferred\_init\_points
<Attribute id="qiskit.circuit.library.EfficientSU2.preferred_init_points">
The initial points for the parameters. Can be stored as initial guess in optimization.
**Returns**
The initial values for the parameters, or None, if none have been set.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.EfficientSU2.prefix" attributeValue="'circuit'" />
### qregs
<Attribute id="qiskit.circuit.library.EfficientSU2.qregs" attributeTypeHint="list[QuantumRegister]">
A list of the quantum registers associated with the circuit.
</Attribute>
### qubits
<Attribute id="qiskit.circuit.library.EfficientSU2.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
### reps
<Attribute id="qiskit.circuit.library.EfficientSU2.reps">
The number of times rotation and entanglement block are repeated.
**Returns**
The number of repetitions.
</Attribute>
### rotation\_blocks
<Attribute id="qiskit.circuit.library.EfficientSU2.rotation_blocks">
The blocks in the rotation layers.
**Returns**
The blocks in the rotation layers.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.EfficientSU2.mdx
|
---
title: EvolvedOperatorAnsatz
description: API reference for qiskit.circuit.library.EvolvedOperatorAnsatz
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.EvolvedOperatorAnsatz
---
# EvolvedOperatorAnsatz
<Class id="qiskit.circuit.library.EvolvedOperatorAnsatz" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/n_local/evolved_operator_ansatz.py#L30-L223" signature="qiskit.circuit.library.EvolvedOperatorAnsatz(operators=None, reps=1, evolution=None, insert_barriers=False, name='EvolvedOps', parameter_prefix='t', initial_state=None, flatten=None)" modifiers="class">
Bases: [`NLocal`](qiskit.circuit.library.NLocal "qiskit.circuit.library.n_local.n_local.NLocal")
The evolved operator ansatz.
**Parameters**
* **operators** (*BaseOperator |* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)") *| None*) β The operators to evolve. If a circuit is passed, we assume it implements an already evolved operator and thus the circuit is not evolved again. Can be a single operator (circuit) or a list of operators (and circuits).
* **reps** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β The number of times to repeat the evolved operators.
* **evolution** (*EvolutionBase |* [*EvolutionSynthesis*](qiskit.synthesis.EvolutionSynthesis "qiskit.synthesis.EvolutionSynthesis") *| None*) β A specification of which evolution synthesis to use for the [`PauliEvolutionGate`](qiskit.circuit.library.PauliEvolutionGate "qiskit.circuit.library.PauliEvolutionGate"). Defaults to first order Trotterization.
* **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Whether to insert barriers in between each evolution.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The name of the circuit.
* **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| Sequence\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]*) β Set the names of the circuit parameters. If a string, the same prefix will be used for each parameters. Can also be a list to specify a prefix per operator.
* **initial\_state** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") *| None*) β A [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") object to prepend to the circuit.
* **flatten** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)") *| None*) β Set this to `True` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if youβre using this circuit for anything besides visualization its **strongly** recommended to set this flag to `True` to avoid a large performance overhead for parameter binding.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.data" />
### entanglement
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.entanglement">
Get the entanglement strategy.
**Returns**
The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted.
</Attribute>
### entanglement\_blocks
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.entanglement_blocks">
The blocks in the entanglement layers.
**Returns**
The blocks in the entanglement layers.
</Attribute>
### evolution
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.evolution">
The evolution converter used to compute the evolution.
**Returns**
The evolution converter used to compute the evolution.
**Return type**
[EvolutionSynthesis](qiskit.synthesis.EvolutionSynthesis "qiskit.synthesis.EvolutionSynthesis")
</Attribute>
### flatten
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.flatten">
Returns whether the circuit is wrapped in nested gates/instructions or flattened.
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### initial\_state
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.initial_state">
Return the initial state that is added in front of the n-local circuit.
**Returns**
The initial state.
</Attribute>
### insert\_barriers
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.insert_barriers">
If barriers are inserted in between the layers or not.
**Returns**
`True`, if barriers are inserted in between the layers, `False` if not.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.instances" attributeValue="166" />
### layout
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.num_clbits">
Return number of classical bits.
</Attribute>
### num\_layers
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.num_layers">
Return the number of layers in the n-local circuit.
**Returns**
The number of layers in the circuit.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.num_parameters" />
### num\_parameters\_settable
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.num_parameters_settable">
The number of total parameters that can be set to distinct values.
This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from `num_parameters` which counts the number of unique [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects currently in the circuit.
**Returns**
The number of parameters originally available in the circuit.
<Admonition title="Note" type="note">
This quantity does not require the circuit to be built yet.
</Admonition>
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.num_qubits">
Returns the number of qubits in this circuit.
**Returns**
The number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### operators
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.operators">
The operators that are evolved in this circuit.
**Returns**
The operators to be evolved (and circuits) contained in this ansatz.
**Return type**
[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")
</Attribute>
### ordered\_parameters
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.ordered_parameters">
The parameters used in the underlying circuit.
This includes float values and duplicates.
**Examples**
```python
>>> # prepare circuit ...
>>> print(nlocal)
βββββββββββββββββββββββββββββββββββββββββββββ
q_0: β€ Ry(1) ββ€ Ry(ΞΈ[1]) ββ€ Ry(ΞΈ[1]) ββ€ Ry(ΞΈ[3]) β
βββββββββββββββββββββββββββββββββββββββββββββ
>>> nlocal.parameters
{Parameter(ΞΈ[1]), Parameter(ΞΈ[3])}
>>> nlocal.ordered_parameters
[1, Parameter(ΞΈ[1]), Parameter(ΞΈ[1]), Parameter(ΞΈ[3])]
```
**Returns**
The parameters objects used in the circuit.
</Attribute>
### parameter\_bounds
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.parameter_bounds">
The parameter bounds for the unbound parameters in the circuit.
**Returns**
A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If `None` is returned, problem is fully unbounded.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.parameters" />
### preferred\_init\_points
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.preferred_init_points">
Getter of preferred initial points based on the given initial state.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.prefix" attributeValue="'circuit'" />
### qregs
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.qregs" attributeTypeHint="list[QuantumRegister]">
A list of the quantum registers associated with the circuit.
</Attribute>
### qubits
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
### reps
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.reps">
The number of times rotation and entanglement block are repeated.
**Returns**
The number of repetitions.
</Attribute>
### rotation\_blocks
<Attribute id="qiskit.circuit.library.EvolvedOperatorAnsatz.rotation_blocks">
The blocks in the rotation layers.
**Returns**
The blocks in the rotation layers.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.EvolvedOperatorAnsatz.mdx
|
---
title: ExactReciprocal
description: API reference for qiskit.circuit.library.ExactReciprocal
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.ExactReciprocal
---
# ExactReciprocal
<Class id="qiskit.circuit.library.ExactReciprocal" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/arithmetic/exact_reciprocal.py#L20-L88" signature="qiskit.circuit.library.ExactReciprocal(num_state_qubits, scaling, neg_vals=False, name='1/x')" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
Exact reciprocal
$$
|x\rangle |0\rangle \mapsto \cos(1/x)|x\rangle|0\rangle + \sin(1/x)|x\rangle |1\rangle
$$
**Parameters**
* **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β The number of qubits representing the value to invert.
* **scaling** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Scaling factor $s$ of the reciprocal function, i.e. to compute $s / x$.
* **neg\_vals** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Whether $x$ might represent negative values. In this case the first qubit is the sign, with $|1\rangle$ for negative and $|0\rangle$ for positive. For the negative case it is assumed that the remaining string represents $1 - x$. This is because $e^{-2 \pi i x} = e^{2 \pi i (1 - x)}$ for $x \in [0,1)$.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The name of the object.
<Admonition title="Note" type="note">
It is assumed that the binary string $x$ represents a number \< 1.
</Admonition>
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.ExactReciprocal.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.ExactReciprocal.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.ExactReciprocal.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.ExactReciprocal.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.ExactReciprocal.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.ExactReciprocal.instances" attributeValue="166" />
### layout
<Attribute id="qiskit.circuit.library.ExactReciprocal.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.ExactReciprocal.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.ExactReciprocal.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.ExactReciprocal.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.ExactReciprocal.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.ExactReciprocal.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.ExactReciprocal.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.ExactReciprocal.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.ExactReciprocal.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.ExactReciprocal.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.ExactReciprocal.mdx
|
---
title: ExcitationPreserving
description: API reference for qiskit.circuit.library.ExcitationPreserving
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.ExcitationPreserving
---
# ExcitationPreserving
<Class id="qiskit.circuit.library.ExcitationPreserving" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/n_local/excitation_preserving.py#L24-L173" signature="qiskit.circuit.library.ExcitationPreserving(num_qubits=None, mode='iswap', entanglement='full', reps=3, skip_unentangled_qubits=False, skip_final_rotation_layer=False, parameter_prefix='ΞΈ', insert_barriers=False, initial_state=None, name='ExcitationPreserving', flatten=None)" modifiers="class">
Bases: [`TwoLocal`](qiskit.circuit.library.TwoLocal "qiskit.circuit.library.n_local.two_local.TwoLocal")
The heuristic excitation-preserving wave function ansatz.
The `ExcitationPreserving` circuit preserves the ratio of $|00\rangle$, $|01\rangle + |10\rangle$ and $|11\rangle$ states. To this end, this circuit uses two-qubit interactions of the form
$$
\newcommand{\rotationangle}{\theta/2}
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & \cos\left(\rotationangle\right) & -i\sin\left(\rotationangle\right) & 0 \\
0 & -i\sin\left(\rotationangle\right) & \cos\left(\rotationangle\right) & 0 \\
0 & 0 & 0 & e^{-i\phi}
\end{pmatrix}
$$
for the mode `'fsim'` or with $e^{-i\phi} = 1$ for the mode `'iswap'`.
Note that other wave functions, such as UCC-ansatzes, are also excitation preserving. However these can become complex quickly, while this heuristically motivated circuit follows a simpler pattern.
This trial wave function consists of layers of $Z$ rotations with 2-qubit entanglements. The entangling is creating using $XX+YY$ rotations and optionally a controlled-phase gate for the mode `'fsim'`.
See [`RealAmplitudes`](qiskit.circuit.library.RealAmplitudes "qiskit.circuit.library.RealAmplitudes") for more detail on the possible arguments and options such as skipping unentanglement qubits, which apply here too.
The rotations of the ExcitationPreserving ansatz can be written as
**Examples**
```python
>>> ansatz = ExcitationPreserving(3, reps=1, insert_barriers=True, entanglement='linear')
>>> print(ansatz) # show the circuit
ββββββββββββ β ββββββββββββββββββββββββββββ β ββββββββββββ
q_0: β€ RZ(ΞΈ[0]) βββββ€0 ββ€0 βββββββββββββββββββββββββββββββββ€ RZ(ΞΈ[5]) β
ββββββββββββ€ β β RXX(ΞΈ[3]) ββ RYY(ΞΈ[3]) βββββββββββββββββββββββββββββ β ββββββββββββ€
q_1: β€ RZ(ΞΈ[1]) βββββ€1 ββ€1 ββ€0 ββ€0 βββββ€ RZ(ΞΈ[6]) β
ββββββββββββ€ β βββββββββββββββββββββββββββββ RXX(ΞΈ[4]) ββ RYY(ΞΈ[4]) β β ββββββββββββ€
q_2: β€ RZ(ΞΈ[2]) βββββββββββββββββββββββββββββββββ€1 ββ€1 βββββ€ RZ(ΞΈ[7]) β
ββββββββββββ β ββββββββββββββββββββββββββββ β ββββββββββββ
```
```python
>>> ansatz = ExcitationPreserving(2, reps=1)
>>> qc = QuantumCircuit(2) # create a circuit and append the RY variational form
>>> qc.cry(0.2, 0, 1) # do some previous operation
>>> qc.compose(ansatz, inplace=True) # add the swaprz
>>> qc.draw()
ββββββββββββββββββββββββββββββββββββββββββββββββββββ
q_0: ββββββ ββββββ€ RZ(ΞΈ[0]) ββ€0 ββ€0 ββ€ RZ(ΞΈ[3]) β
ββββββ΄βββββββββββββββββ€β RXX(ΞΈ[2]) ββ RYY(ΞΈ[2]) βββββββββββββ€
q_1: β€ RY(0.2) ββ€ RZ(ΞΈ[1]) ββ€1 ββ€1 ββ€ RZ(ΞΈ[4]) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
```python
>>> ansatz = ExcitationPreserving(3, reps=1, mode='fsim', entanglement=[[0,2]],
... insert_barriers=True)
>>> print(ansatz)
ββββββββββββ β ββββββββββββββββββββββββββββ β ββββββββββββ
q_0: β€ RZ(ΞΈ[0]) βββββ€0 ββ€0 βββ βββββββββ€ RZ(ΞΈ[5]) β
ββββββββββββ€ β β ββ β β β ββββββββββββ€
q_1: β€ RZ(ΞΈ[1]) βββββ€ RXX(ΞΈ[3]) ββ€ RYY(ΞΈ[3]) βββΌβββββββββ€ RZ(ΞΈ[6]) β
ββββββββββββ€ β β ββ β βΞΈ[4] β ββββββββββββ€
q_2: β€ RZ(ΞΈ[2]) βββββ€1 ββ€1 βββ βββββββββ€ RZ(ΞΈ[7]) β
ββββββββββββ β ββββββββββββββββββββββββββββ β ββββββββββββ
```
**Parameters**
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β The number of qubits of the ExcitationPreserving circuit.
* **mode** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Choose the entangler mode, can be βiswapβ or βfsimβ.
* **reps** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Specifies how often the structure of a rotation layer followed by an entanglement layer is repeated.
* **entanglement** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]] | Callable\[\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*],* [*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]]*) β Specifies the entanglement structure. Can be a string (βfullβ, βlinearβ or βscaβ), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. See the Examples section of [`TwoLocal`](qiskit.circuit.library.TwoLocal "qiskit.circuit.library.TwoLocal") for more detail.
* **initial\_state** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") *| None*) β A QuantumCircuit object to prepend to the circuit.
* **skip\_unentangled\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β If True, the single qubit gates are only applied to qubits that are entangled with another qubit. If False, the single qubit gates are applied to each qubit in the Ansatz. Defaults to False.
* **skip\_final\_rotation\_layer** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β If True, a rotation layer is added at the end of the ansatz. If False, no rotation layer is added. Defaults to True.
* **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The parameterized gates require a parameter to be defined, for which we use [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector").
* **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β If True, barriers are inserted in between each layer. If False, no barriers are inserted.
* **flatten** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)") *| None*) β Set this to `True` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if youβre using this circuit for anything besides visualization its **strongly** recommended to set this flag to `True` to avoid a large performance overhead for parameter binding.
**Raises**
[**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.12)") β If the selected mode is not supported.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.ExcitationPreserving.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.ExcitationPreserving.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.ExcitationPreserving.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.ExcitationPreserving.data" />
### entanglement
<Attribute id="qiskit.circuit.library.ExcitationPreserving.entanglement">
Get the entanglement strategy.
**Returns**
The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted.
</Attribute>
### entanglement\_blocks
<Attribute id="qiskit.circuit.library.ExcitationPreserving.entanglement_blocks">
The blocks in the entanglement layers.
**Returns**
The blocks in the entanglement layers.
</Attribute>
### flatten
<Attribute id="qiskit.circuit.library.ExcitationPreserving.flatten">
Returns whether the circuit is wrapped in nested gates/instructions or flattened.
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.ExcitationPreserving.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### initial\_state
<Attribute id="qiskit.circuit.library.ExcitationPreserving.initial_state">
Return the initial state that is added in front of the n-local circuit.
**Returns**
The initial state.
</Attribute>
### insert\_barriers
<Attribute id="qiskit.circuit.library.ExcitationPreserving.insert_barriers">
If barriers are inserted in between the layers or not.
**Returns**
`True`, if barriers are inserted in between the layers, `False` if not.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.ExcitationPreserving.instances" attributeValue="166" />
### layout
<Attribute id="qiskit.circuit.library.ExcitationPreserving.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.ExcitationPreserving.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.ExcitationPreserving.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.ExcitationPreserving.num_clbits">
Return number of classical bits.
</Attribute>
### num\_layers
<Attribute id="qiskit.circuit.library.ExcitationPreserving.num_layers">
Return the number of layers in the n-local circuit.
**Returns**
The number of layers in the circuit.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.ExcitationPreserving.num_parameters" />
### num\_parameters\_settable
<Attribute id="qiskit.circuit.library.ExcitationPreserving.num_parameters_settable">
The number of total parameters that can be set to distinct values.
This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from `num_parameters` which counts the number of unique [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects currently in the circuit.
**Returns**
The number of parameters originally available in the circuit.
<Admonition title="Note" type="note">
This quantity does not require the circuit to be built yet.
</Admonition>
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.ExcitationPreserving.num_qubits">
Returns the number of qubits in this circuit.
**Returns**
The number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.ExcitationPreserving.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### ordered\_parameters
<Attribute id="qiskit.circuit.library.ExcitationPreserving.ordered_parameters">
The parameters used in the underlying circuit.
This includes float values and duplicates.
**Examples**
```python
>>> # prepare circuit ...
>>> print(nlocal)
βββββββββββββββββββββββββββββββββββββββββββββ
q_0: β€ Ry(1) ββ€ Ry(ΞΈ[1]) ββ€ Ry(ΞΈ[1]) ββ€ Ry(ΞΈ[3]) β
βββββββββββββββββββββββββββββββββββββββββββββ
>>> nlocal.parameters
{Parameter(ΞΈ[1]), Parameter(ΞΈ[3])}
>>> nlocal.ordered_parameters
[1, Parameter(ΞΈ[1]), Parameter(ΞΈ[1]), Parameter(ΞΈ[3])]
```
**Returns**
The parameters objects used in the circuit.
</Attribute>
### parameter\_bounds
<Attribute id="qiskit.circuit.library.ExcitationPreserving.parameter_bounds">
Return the parameter bounds.
**Returns**
The parameter bounds.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.ExcitationPreserving.parameters" />
### preferred\_init\_points
<Attribute id="qiskit.circuit.library.ExcitationPreserving.preferred_init_points">
The initial points for the parameters. Can be stored as initial guess in optimization.
**Returns**
The initial values for the parameters, or None, if none have been set.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.ExcitationPreserving.prefix" attributeValue="'circuit'" />
### qregs
<Attribute id="qiskit.circuit.library.ExcitationPreserving.qregs" attributeTypeHint="list[QuantumRegister]">
A list of the quantum registers associated with the circuit.
</Attribute>
### qubits
<Attribute id="qiskit.circuit.library.ExcitationPreserving.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
### reps
<Attribute id="qiskit.circuit.library.ExcitationPreserving.reps">
The number of times rotation and entanglement block are repeated.
**Returns**
The number of repetitions.
</Attribute>
### rotation\_blocks
<Attribute id="qiskit.circuit.library.ExcitationPreserving.rotation_blocks">
The blocks in the rotation layers.
**Returns**
The blocks in the rotation layers.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.ExcitationPreserving.mdx
|
---
title: FourierChecking
description: API reference for qiskit.circuit.library.FourierChecking
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.FourierChecking
---
# FourierChecking
<Class id="qiskit.circuit.library.FourierChecking" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/fourier_checking.py#L24-L97" signature="qiskit.circuit.library.FourierChecking(f, g)" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
Fourier checking circuit.
The circuit for the Fourier checking algorithm, introduced in \[1], involves a layer of Hadamards, the function $f$, another layer of Hadamards, the function $g$, followed by a final layer of Hadamards. The functions $f$ and $g$ are classical functions realized as phase oracles (diagonal operators with \{-1, 1} on the diagonal).
The probability of observing the all-zeros string is $p(f,g)$. The algorithm solves the promise Fourier checking problem, which decides if f is correlated with the Fourier transform of g, by testing if $p(f,g) <= 0.01$ or $p(f,g) >= 0.05$, promised that one or the other of these is true.
The functions $f$ and $g$ are currently implemented from their truth tables but could be represented concisely and implemented efficiently for special classes of functions.
Fourier checking is a special case of $k$-fold forrelation \[2].
**Reference:**
\[1] S. Aaronson, BQP and the Polynomial Hierarchy, 2009 (Section 3.2). [arXiv:0910.4698](https://arxiv.org/abs/0910.4698)
\[2] S. Aaronson, A. Ambainis, Forrelation: a problem that optimally separates quantum from classical computing, 2014. [arXiv:1411.5729](https://arxiv.org/abs/1411.5729)
Create Fourier checking circuit.
**Parameters**
* **f** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]*) β truth table for f, length 2\*\*n list of \{1,-1}.
* **g** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]*) β truth table for g, length 2\*\*n list of \{1,-1}.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the inputs f and g are not valid.
**Reference Circuit:**

## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.FourierChecking.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.FourierChecking.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.FourierChecking.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.FourierChecking.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.FourierChecking.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.FourierChecking.instances" attributeValue="174" />
### layout
<Attribute id="qiskit.circuit.library.FourierChecking.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.FourierChecking.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.FourierChecking.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.FourierChecking.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.FourierChecking.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.FourierChecking.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.FourierChecking.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.FourierChecking.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.FourierChecking.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.FourierChecking.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.FourierChecking.mdx
|
---
title: FunctionalPauliRotations
description: API reference for qiskit.circuit.library.FunctionalPauliRotations
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.FunctionalPauliRotations
---
# FunctionalPauliRotations
<Class id="qiskit.circuit.library.FunctionalPauliRotations" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/arithmetic/functional_pauli_rotations.py#L22-L114" signature="qiskit.circuit.library.FunctionalPauliRotations(num_state_qubits=None, basis='Y', name='F')" modifiers="class">
Bases: `BlueprintCircuit`, [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC "(in Python v3.12)")
Base class for functional Pauli rotations.
Create a new functional Pauli rotation circuit.
**Parameters**
* **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β The number of qubits representing the state $|x\rangle$.
* **basis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The kind of Pauli rotation to use. Must be βXβ, βYβ or βZβ.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The name of the circuit object.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### basis
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.basis">
The kind of Pauli rotation to be used.
Set the basis to βXβ, βYβ or βZβ for controlled-X, -Y, or -Z rotations respectively.
**Returns**
The kind of Pauli rotation used in controlled rotation.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.data" />
### global\_phase
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.instances" attributeValue="176" />
### layout
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancilla\_qubits
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.num_ancilla_qubits">
The minimum number of ancilla qubits in the circuit.
**Returns**
The minimal number of ancillas required.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.num_parameters" />
### num\_qubits
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.num_qubits">
Return number of qubits.
</Attribute>
### num\_state\_qubits
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.num_state_qubits">
The number of state qubits representing the state $|x\rangle$.
**Returns**
The number of state qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.parameters" />
### prefix
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.prefix" attributeValue="'circuit'" />
### qregs
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.qregs" attributeTypeHint="list[QuantumRegister]">
A list of the quantum registers associated with the circuit.
</Attribute>
### qubits
<Attribute id="qiskit.circuit.library.FunctionalPauliRotations.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.FunctionalPauliRotations.mdx
|
---
title: GlobalPhaseGate
description: API reference for qiskit.circuit.library.GlobalPhaseGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.GlobalPhaseGate
---
# GlobalPhaseGate
<Class id="qiskit.circuit.library.GlobalPhaseGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/global_phase.py#L25-L80" signature="qiskit.circuit.library.GlobalPhaseGate(phase, label=None, *, duration=None, unit='dt')" modifiers="class">
Bases: [`Gate`](qiskit.circuit.Gate "qiskit.circuit.gate.Gate")
The global phase gate ($e^{i\theta}$).
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")
**Mathematical Representation:**
$$
\text{GlobalPhaseGate}\ =
\begin{pmatrix}
e^{i\theta}
\end{pmatrix}
$$
**Parameters**
* **phase** ([*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.parameterexpression.ParameterExpression") *|*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β The value of phase it takes.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β An optional label for the gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.GlobalPhaseGate.base_class "qiskit.circuit.library.GlobalPhaseGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.GlobalPhaseGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.GlobalPhaseGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/global_phase.py#L55-L70" signature="inverse(annotated=False)">
Return inverse GlobalPhaseGate gate.
$\text{GlobalPhaseGate}(\lambda)^{\dagger} = \text{GlobalPhaseGate}(-\lambda)$
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as the inverse is always another [`GlobalPhaseGate`](#qiskit.circuit.library.GlobalPhaseGate "qiskit.circuit.library.GlobalPhaseGate") with an inverted parameter value.
**Returns**
inverse gate.
**Return type**
[GlobalPhaseGate](#qiskit.circuit.library.GlobalPhaseGate "qiskit.circuit.library.GlobalPhaseGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.GlobalPhaseGate.mdx
|
---
title: GMS
description: API reference for qiskit.circuit.library.GMS
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.GMS
---
# GMS
<Class id="qiskit.circuit.library.GMS" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/gms.py#L27-L93" signature="qiskit.circuit.library.GMS(num_qubits, theta)" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
Global MΓΈlmerβSΓΈrensen gate.
**Circuit symbol:**
```python
βββββββββββββ
q_0: β€0 β
β β
q_1: β€1 GMS β
β β
q_2: β€2 β
βββββββββββββ
```
**Expanded Circuit:**

The MΓΈlmerβSΓΈrensen gate is native to ion-trap systems. The global MS can be applied to multiple ions to entangle multiple qubits simultaneously \[1].
In the two-qubit case, this is equivalent to an XX(theta) interaction, and is thus reduced to the RXXGate. The global MS gate is a sum of XX interactions on all pairs \[2].
$$
GMS(\chi_{12}, \chi_{13}, ..., \chi_{n-1 n}) =
exp(-i \sum_{i=1}^{n} \sum_{j=i+1}^{n} X{\otimes}X \frac{\chi_{ij}}{2})
$$
**References:**
\[1] SΓΈrensen, A. and MΓΈlmer, K., Multi-particle entanglement of hot trapped ions. Physical Review Letters. 82 (9): 1835β1838. [arXiv:9810040](https://arxiv.org/abs/quant-ph/9810040)
\[2] Maslov, D. and Nam, Y., Use of global interactions in efficient quantum circuit constructions. New Journal of Physics, 20(3), p.033018. [arXiv:1707.06356](https://arxiv.org/abs/1707.06356)
Create a new Global MΓΈlmerβSΓΈrensen (GMS) gate.
**Parameters**
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β width of gate.
* **theta** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*]] |* [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(in NumPy v1.26)")) β a num\_qubits x num\_qubits symmetric matrix of interaction angles for each qubit pair. The upper triangle is considered.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.GMS.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.GMS.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.GMS.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.GMS.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.GMS.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.GMS.instances" attributeValue="177" />
### layout
<Attribute id="qiskit.circuit.library.GMS.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.GMS.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.GMS.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.GMS.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.GMS.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.GMS.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.GMS.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.GMS.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.GMS.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.GMS.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.GMS.mdx
|
---
title: GR
description: API reference for qiskit.circuit.library.GR
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.GR
---
# GR
<Class id="qiskit.circuit.library.GR" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/gr.py#L19-L70" signature="qiskit.circuit.library.GR(num_qubits, theta, phi)" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
Global R gate.
**Circuit symbol:**
```python
ββββββββββββ
q_0: β€0 β
β β
q_1: β€1 GR(Ο΄,Ο) β
β β
q_2: β€2 β
ββββββββββββ
```
The global R gate is native to atomic systems (ion traps, cold neutrals). The global R can be applied to multiple qubits simultaneously.
In the one-qubit case, this is equivalent to an R(theta, phi) operation, and is thus reduced to the RGate. The global R gate is a direct sum of R operations on all individual qubits.
$$
GR(\theta, \phi) = \exp(-i \sum_{i=1}^{n} (\cos(\phi)X_i + \sin(\phi)Y_i) \theta/2)
$$
**Expanded Circuit:**

Create a new Global R (GR) gate.
**Parameters**
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of qubits.
* **theta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β rotation angle about axis determined by phi
* **phi** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β angle of rotation axis in xy-plane
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.GR.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.GR.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.GR.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.GR.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.GR.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.GR.instances" attributeValue="186" />
### layout
<Attribute id="qiskit.circuit.library.GR.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.GR.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.GR.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.GR.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.GR.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.GR.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.GR.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.GR.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.GR.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.GR.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.GR.mdx
|
---
title: GraphState
description: API reference for qiskit.circuit.library.GraphState
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.GraphState
---
# GraphState
<Class id="qiskit.circuit.library.GraphState" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/graph_state.py#L22-L86" signature="qiskit.circuit.library.GraphState(adjacency_matrix)" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
Circuit to prepare a graph state.
Given a graph G = (V, E), with the set of vertices V and the set of edges E, the corresponding graph state is defined as
$$
|G\rangle = \prod_{(a,b) \in E} CZ_{(a,b)} {|+\rangle}^{\otimes V}
$$
Such a state can be prepared by first preparing all qubits in the $+$ state, then applying a $CZ$ gate for each corresponding graph edge.
Graph state preparation circuits are Clifford circuits, and thus easy to simulate classically. However, by adding a layer of measurements in a product basis at the end, there is evidence that the circuit becomes hard to simulate \[2].
**Reference Circuit:**

**References:**
**\[1] M. Hein, J. Eisert, H.J. Briegel, Multi-party Entanglement in Graph States,**
[arXiv:0307130](https://arxiv.org/pdf/quant-ph/0307130.pdf)
**\[2] D. Koh, Further Extensions of Clifford Circuits & their Classical Simulation Complexities.**
[arXiv:1512.07892](https://arxiv.org/pdf/1512.07892.pdf)
Create graph state preparation circuit.
**Parameters**
**adjacency\_matrix** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)") *| np.ndarray*) β input graph as n-by-n list of 0-1 lists
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If adjacency\_matrix is not symmetric.
The circuit prepares a graph state with the given adjacency matrix.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.GraphState.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.GraphState.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.GraphState.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.GraphState.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.GraphState.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.GraphState.instances" attributeValue="172" />
### layout
<Attribute id="qiskit.circuit.library.GraphState.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.GraphState.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.GraphState.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.GraphState.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.GraphState.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.GraphState.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.GraphState.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.GraphState.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.GraphState.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.GraphState.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.GraphState.mdx
|
---
title: GroverOperator
description: API reference for qiskit.circuit.library.GroverOperator
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.GroverOperator
---
# GroverOperator
<Class id="qiskit.circuit.library.GroverOperator" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/grover_operator.py#L25-L285" signature="qiskit.circuit.library.GroverOperator(oracle, state_preparation=None, zero_reflection=None, reflection_qubits=None, insert_barriers=False, mcx_mode='noancilla', name='Q')" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
The Grover operator.
Groverβs search algorithm \[1, 2] consists of repeated applications of the so-called Grover operator used to amplify the amplitudes of the desired output states. This operator, $\mathcal{Q}$, consists of the phase oracle, $\mathcal{S}_f$, zero phase-shift or zero reflection, $\mathcal{S}_0$, and an input state preparation $\mathcal{A}$:
$$
\mathcal{Q} = \mathcal{A} \mathcal{S}_0 \mathcal{A}^\dagger \mathcal{S}_f
$$
In the standard Grover search we have $\mathcal{A} = H^{\otimes n}$:
$$
\mathcal{Q} = H^{\otimes n} \mathcal{S}_0 H^{\otimes n} \mathcal{S}_f
= D \mathcal{S_f}
$$
The operation $D = H^{\otimes n} \mathcal{S}_0 H^{\otimes n}$ is also referred to as diffusion operator. In this formulation we can see that Groverβs operator consists of two steps: first, the phase oracle multiplies the good states by -1 (with $\mathcal{S}_f$) and then the whole state is reflected around the mean (with $D$).
This class allows setting a different state preparation, as in quantum amplitude amplification (a generalization of Groverβs algorithm), $\mathcal{A}$ might not be a layer of Hardamard gates \[3].
The action of the phase oracle $\mathcal{S}_f$ is defined as
$$
\mathcal{S}_f: |x\rangle \mapsto (-1)^{f(x)}|x\rangle
$$
where $f(x) = 1$ if $x$ is a good state and 0 otherwise. To highlight the fact that this oracle flips the phase of the good states and does not flip the state of a result qubit, we call $\mathcal{S}_f$ a phase oracle.
Note that you can easily construct a phase oracle from a bitflip oracle by sandwiching the controlled X gate on the result qubit by a X and H gate. For instance
```python
Bitflip oracle Phaseflip oracle
q_0: βββ ββ q_0: βββββββββββββ ββββββββββββ
βββ΄ββ βββββββββββββ΄ββββββββββββ
out: β€ X β out: β€ X ββ€ H ββ€ X ββ€ H ββ€ X β
βββββ βββββββββββββββββββββββββ
```
There is some flexibility in defining the oracle and $\mathcal{A}$ operator. Before the Grover operator is applied in Groverβs algorithm, the qubits are first prepared with one application of the $\mathcal{A}$ operator (or Hadamard gates in the standard formulation). Thus, we always have operation of the form $\mathcal{A} \mathcal{S}_f \mathcal{A}^\dagger$. Therefore it is possible to move bitflip logic into $\mathcal{A}$ and leaving the oracle only to do phaseflips via Z gates based on the bitflips. One possible use-case for this are oracles that do not uncompute the state qubits.
The zero reflection $\mathcal{S}_0$ is usually defined as
$$
\mathcal{S}_0 = 2 |0\rangle^{\otimes n} \langle 0|^{\otimes n} - \mathbb{I}_n
$$
where $\mathbb{I}_n$ is the identity on $n$ qubits. By default, this class implements the negative version $2 |0\rangle^{\otimes n} \langle 0|^{\otimes n} - \mathbb{I}_n$, since this can simply be implemented with a multi-controlled Z sandwiched by X gates on the target qubit and the introduced global phase does not matter for Groverβs algorithm.
**Examples**
```python
>>> from qiskit.circuit import QuantumCircuit
>>> from qiskit.circuit.library import GroverOperator
>>> oracle = QuantumCircuit(2)
>>> oracle.z(0) # good state = first qubit is |1>
>>> grover_op = GroverOperator(oracle, insert_barriers=True)
>>> grover_op.decompose().draw()
βββββ β βββββ β βββββ βββββ β βββββ
state_0: β€ Z βββββ€ H βββββ€ X βββββββββ βββ€ X ββββββββββ€ H β
βββββ β βββββ€ β βββββ€ββββββββ΄βββββββ€βββββ β βββββ€
state_1: βββββββββ€ H βββββ€ X ββ€ H ββ€ X ββ€ H ββ€ X βββββ€ H β
β βββββ β βββββββββββββββββββββββββ β βββββ
```
```python
>>> oracle = QuantumCircuit(1)
>>> oracle.z(0) # the qubit state |1> is the good state
>>> state_preparation = QuantumCircuit(1)
>>> state_preparation.ry(0.2, 0) # non-uniform state preparation
>>> grover_op = GroverOperator(oracle, state_preparation)
>>> grover_op.decompose().draw()
βββββββββββββββββββββββββββββββββββββββββββ
state_0: β€ Z ββ€ RY(-0.2) ββ€ X ββ€ Z ββ€ X ββ€ RY(0.2) β
βββββββββββββββββββββββββββββββββββββββββββ
```
```python
>>> oracle = QuantumCircuit(4)
>>> oracle.z(3)
>>> reflection_qubits = [0, 3]
>>> state_preparation = QuantumCircuit(4)
>>> state_preparation.cry(0.1, 0, 3)
>>> state_preparation.ry(0.5, 3)
>>> grover_op = GroverOperator(oracle, state_preparation,
... reflection_qubits=reflection_qubits)
>>> grover_op.decompose().draw()
βββββ βββββ
state_0: βββββββββββββββββββββββ βββββββ€ X βββββββββ βββ€ X ββββββββββββ ββββββββββββββββ
β βββββ β βββββ β
state_1: βββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββΌββββββββββββββββ
β β β
state_2: βββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββΌββββββββββββββββ
βββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββ
state_3: β€ Z ββ€ RY(-0.5) ββ€ RY(-0.1) ββ€ X ββ€ H ββ€ X ββ€ H ββ€ X ββ€ RY(0.1) ββ€ RY(0.5) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
```python
>>> mark_state = Statevector.from_label('011')
>>> diffuse_operator = 2 * DensityMatrix.from_label('000') - Operator.from_label('III')
>>> grover_op = GroverOperator(oracle=mark_state, zero_reflection=diffuse_operator)
>>> grover_op.decompose().draw(fold=70)
βββββββββββββββββββ βββββ Β»
state_0: β€0 ββββββββ€ H βββββββββββββββββββββββββββΒ»
β ββββββββ΄ββββ΄ββββββ βββββ Β»
state_1: β€1 UCRZ(0,pi,0,0) ββ€0 βββββββ€ H βββββββββββΒ»
β ββ UCRZ(pi/2,0) βββββββ΄ββββ΄ββββββββββΒ»
state_2: β€2 ββ€1 ββ€ UCRZ(-pi/4) ββ€ H βΒ»
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββΒ»
Β« βββββββββββββββββββ βββββ
Β«state_0: β€0 ββββββββ€ H ββββββββββββββββββββββββββ
Β« β ββββββββ΄ββββ΄ββββββ βββββ
Β«state_1: β€1 UCRZ(pi,0,0,0) ββ€0 ββββββ€ H βββββββββββ
Β« β ββ UCRZ(pi/2,0) ββββββ΄ββββ΄ββββββββββ
Β«state_2: β€2 ββ€1 ββ€ UCRZ(pi/4) ββ€ H β
Β« βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**References**
**\[1]: L. K. Grover (1996), A fast quantum mechanical algorithm for database search,**
[arXiv:quant-ph/9605043](https://arxiv.org/abs/quant-ph/9605043).
**\[2]: I. Chuang & M. Nielsen, Quantum Computation and Quantum Information,**
Cambridge: Cambridge University Press, 2000. Chapter 6.1.2.
**\[3]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000).**
Quantum Amplitude Amplification and Estimation. [arXiv:quant-ph/0005055](http://arxiv.org/abs/quant-ph/0005055).
**Parameters**
* **oracle** (*Union\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")*,* [*Statevector*](qiskit.quantum_info.Statevector "qiskit.quantum_info.Statevector")*]*) β The phase oracle implementing a reflection about the bad state. Note that this is not a bitflip oracle, see the docstring for more information.
* **state\_preparation** (*Optional\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")*]*) β The operator preparing the good and bad state. For Groverβs algorithm, this is a n-qubit Hadamard gate and for amplitude amplification or estimation the operator $\mathcal{A}$.
* **zero\_reflection** (*Optional\[Union\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")*,* [*DensityMatrix*](qiskit.quantum_info.DensityMatrix "qiskit.quantum_info.DensityMatrix")*,* [*Operator*](qiskit.quantum_info.Operator "qiskit.quantum_info.Operator")*]]*) β The reflection about the zero state, $\mathcal{S}_0$.
* **reflection\_qubits** (*Optional\[List\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]]*) β Qubits on which the zero reflection acts on.
* **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Whether barriers should be inserted between the reflections and A.
* **mcx\_mode** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The mode to use for building the default zero reflection.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The name of the circuit.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.GroverOperator.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.GroverOperator.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.GroverOperator.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.GroverOperator.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.GroverOperator.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.GroverOperator.instances" attributeValue="174" />
### layout
<Attribute id="qiskit.circuit.library.GroverOperator.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.GroverOperator.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.GroverOperator.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.GroverOperator.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.GroverOperator.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.GroverOperator.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.GroverOperator.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### oracle
<Attribute id="qiskit.circuit.library.GroverOperator.oracle">
The oracle implementing a reflection about the bad state.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.GroverOperator.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.GroverOperator.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.GroverOperator.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
### reflection\_qubits
<Attribute id="qiskit.circuit.library.GroverOperator.reflection_qubits">
Reflection qubits, on which S0 is applied (if S0 is not user-specified).
</Attribute>
### state\_preparation
<Attribute id="qiskit.circuit.library.GroverOperator.state_preparation">
The subcircuit implementing the A operator or Hadamards.
</Attribute>
### zero\_reflection
<Attribute id="qiskit.circuit.library.GroverOperator.zero_reflection">
The subcircuit implementing the reflection about 0.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.GroverOperator.mdx
|
---
title: GRX
description: API reference for qiskit.circuit.library.GRX
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.GRX
---
# GRX
<Class id="qiskit.circuit.library.GRX" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/gr.py#L73-L118" signature="qiskit.circuit.library.GRX(num_qubits, theta)" modifiers="class">
Bases: [`GR`](qiskit.circuit.library.GR "qiskit.circuit.library.generalized_gates.gr.GR")
Global RX gate.
**Circuit symbol:**
```python
ββββββββββββ
q_0: β€0 β
β β
q_1: β€1 GRX(Ο΄) β
β β
q_2: β€2 β
ββββββββββββ
```
The global RX gate is native to atomic systems (ion traps, cold neutrals). The global RX can be applied to multiple qubits simultaneously.
In the one-qubit case, this is equivalent to an RX(theta) operations, and is thus reduced to the RXGate. The global RX gate is a direct sum of RX operations on all individual qubits.
$$
GRX(\theta) = \exp(-i \sum_{i=1}^{n} X_i \theta/2)
$$
**Expanded Circuit:**

Create a new Global RX (GRX) gate.
**Parameters**
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of qubits.
* **theta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β rotation angle about x-axis
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.GRX.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.GRX.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.GRX.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.GRX.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.GRX.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.GRX.instances" attributeValue="160" />
### layout
<Attribute id="qiskit.circuit.library.GRX.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.GRX.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.GRX.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.GRX.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.GRX.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.GRX.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.GRX.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.GRX.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.GRX.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.GRX.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.GRX.mdx
|
---
title: GRY
description: API reference for qiskit.circuit.library.GRY
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.GRY
---
# GRY
<Class id="qiskit.circuit.library.GRY" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/gr.py#L121-L166" signature="qiskit.circuit.library.GRY(num_qubits, theta)" modifiers="class">
Bases: [`GR`](qiskit.circuit.library.GR "qiskit.circuit.library.generalized_gates.gr.GR")
Global RY gate.
**Circuit symbol:**
```python
ββββββββββββ
q_0: β€0 β
β β
q_1: β€1 GRY(Ο΄) β
β β
q_2: β€2 β
ββββββββββββ
```
The global RY gate is native to atomic systems (ion traps, cold neutrals). The global RY can be applied to multiple qubits simultaneously.
In the one-qubit case, this is equivalent to an RY(theta) operation, and is thus reduced to the RYGate. The global RY gate is a direct sum of RY operations on all individual qubits.
$$
GRY(\theta) = \exp(-i \sum_{i=1}^{n} Y_i \theta/2)
$$
**Expanded Circuit:**

Create a new Global RY (GRY) gate.
**Parameters**
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of qubits.
* **theta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β rotation angle about y-axis
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.GRY.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.GRY.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.GRY.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.GRY.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.GRY.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.GRY.instances" attributeValue="164" />
### layout
<Attribute id="qiskit.circuit.library.GRY.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.GRY.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.GRY.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.GRY.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.GRY.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.GRY.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.GRY.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.GRY.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.GRY.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.GRY.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.GRY.mdx
|
---
title: GRZ
description: API reference for qiskit.circuit.library.GRZ
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.GRZ
---
# GRZ
<Class id="qiskit.circuit.library.GRZ" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/gr.py#L169-L215" signature="qiskit.circuit.library.GRZ(num_qubits, phi)" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
Global RZ gate.
**Circuit symbol:**
```python
ββββββββββββ
q_0: β€0 β
β β
q_1: β€1 GRZ(Ο) β
β β
q_2: β€2 β
ββββββββββββ
```
The global RZ gate is native to atomic systems (ion traps, cold neutrals). The global RZ can be applied to multiple qubits simultaneously.
In the one-qubit case, this is equivalent to an RZ(phi) operation, and is thus reduced to the RZGate. The global RZ gate is a direct sum of RZ operations on all individual qubits.
$$
GRZ(\phi) = \exp(-i \sum_{i=1}^{n} Z_i \phi)
$$
**Expanded Circuit:**

Create a new Global RZ (GRZ) gate.
**Parameters**
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of qubits.
* **phi** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β rotation angle about z-axis
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.GRZ.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.GRZ.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.GRZ.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.GRZ.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.GRZ.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.GRZ.instances" attributeValue="167" />
### layout
<Attribute id="qiskit.circuit.library.GRZ.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.GRZ.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.GRZ.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.GRZ.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.GRZ.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.GRZ.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.GRZ.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.GRZ.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.GRZ.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.GRZ.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.GRZ.mdx
|
---
title: HamiltonianGate
description: API reference for qiskit.circuit.library.HamiltonianGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.HamiltonianGate
---
# HamiltonianGate
<Class id="qiskit.circuit.library.HamiltonianGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/hamiltonian_gate.py#L37-L137" signature="qiskit.circuit.library.HamiltonianGate(data, time, label=None)" modifiers="class">
Bases: [`Gate`](qiskit.circuit.Gate "qiskit.circuit.gate.Gate")
Class for representing evolution by a Hamiltonian operator as a gate.
This gate resolves to a [`UnitaryGate`](qiskit.circuit.library.UnitaryGate "qiskit.circuit.library.UnitaryGate") as $U(t) = \exp(-i t H)$, which can be decomposed into basis gates if it is 2 qubits or less, or simulated directly in Aer for more qubits.
**Parameters**
* **data** (*np.ndarray |* [*Gate*](qiskit.circuit.Gate "qiskit.circuit.Gate") *| BaseOperator*) β A hermitian operator.
* **time** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")) β Time evolution parameter.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β Unitary name for backend \[Default: `None`].
**Raises**
[**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.12)") β if input data is not an N-qubit unitary operator.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.HamiltonianGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.HamiltonianGate.base_class "qiskit.circuit.library.HamiltonianGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.HamiltonianGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.HamiltonianGate.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.HamiltonianGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.HamiltonianGate.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.HamiltonianGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.HamiltonianGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.HamiltonianGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.HamiltonianGate.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.HamiltonianGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.HamiltonianGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.HamiltonianGate.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.HamiltonianGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### adjoint
<Function id="qiskit.circuit.library.HamiltonianGate.adjoint" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/hamiltonian_gate.py#L115-L117" signature="adjoint()">
Return the adjoint of the unitary.
</Function>
### conjugate
<Function id="qiskit.circuit.library.HamiltonianGate.conjugate" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/hamiltonian_gate.py#L111-L113" signature="conjugate()">
Return the conjugate of the Hamiltonian.
</Function>
### inverse
<Function id="qiskit.circuit.library.HamiltonianGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/hamiltonian_gate.py#L107-L109" signature="inverse(annotated=False)">
Return the adjoint of the unitary.
</Function>
### transpose
<Function id="qiskit.circuit.library.HamiltonianGate.transpose" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/hamiltonian_gate.py#L119-L121" signature="transpose()">
Return the transpose of the Hamiltonian.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.library.HamiltonianGate.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/hamiltonian_gate.py#L130-L137" signature="validate_parameter(parameter)">
Hamiltonian parameter has to be an ndarray, operator or float.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.HamiltonianGate.mdx
|
---
title: HGate
description: API reference for qiskit.circuit.library.HGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.HGate
---
# HGate
<Class id="qiskit.circuit.library.HGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/h.py#L24-L124" signature="qiskit.circuit.library.HGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate "qiskit.circuit.singleton.SingletonGate")
Single-qubit Hadamard gate.
This gate is a pi rotation about the X+Z axis, and has the effect of changing computation basis from $|0\rangle,|1\rangle$ to $|+\rangle,|-\rangle$ and vice-versa.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`h()`](qiskit.circuit.QuantumCircuit#h "qiskit.circuit.QuantumCircuit.h") method.
**Circuit symbol:**
```python
βββββ
q_0: β€ H β
βββββ
```
**Matrix Representation:**
$$
H = \frac{1}{\sqrt{2}}
\begin{pmatrix}
1 & 1 \\
1 & -1
\end{pmatrix}
$$
Create new H gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.HGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.HGate.base_class "qiskit.circuit.library.HGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.HGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.HGate.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.HGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.HGate.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.HGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.HGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.HGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.HGate.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.HGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.HGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.HGate.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.HGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### control
<Function id="qiskit.circuit.library.HGate.control" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/h.py#L76-L107" signature="control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False)">
Return a (multi-)controlled-H gate.
One control qubit returns a CH gate.
**Parameters**
* **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β number of control qubits.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β An optional label for the gate \[Default: `None`]
* **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) β control state expressed as integer, string (e.g.\`\`β110β`), or ``None`. If `None`, use all 1s.
* **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β indicates whether the controlled gate can be implemented as an annotated gate.
**Returns**
controlled version of this gate.
**Return type**
[ControlledGate](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")
</Function>
### inverse
<Function id="qiskit.circuit.library.HGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/h.py#L109-L121" signature="inverse(annotated=False)">
Return inverted H gate (itself).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as this gate is self-inverse.
**Returns**
inverse gate (self-inverse).
**Return type**
[HGate](#qiskit.circuit.library.HGate "qiskit.circuit.library.HGate")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.HGate.mdx
|
---
title: HiddenLinearFunction
description: API reference for qiskit.circuit.library.HiddenLinearFunction
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.HiddenLinearFunction
---
# HiddenLinearFunction
<Class id="qiskit.circuit.library.HiddenLinearFunction" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/hidden_linear_function.py#L22-L98" signature="qiskit.circuit.library.HiddenLinearFunction(adjacency_matrix)" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
Circuit to solve the hidden linear function problem.
The 2D Hidden Linear Function problem is determined by a 2D adjacency matrix A, where only elements that are nearest-neighbor on a grid have non-zero entries. Each row/column corresponds to one binary variable $x_i$.
The hidden linear function problem is as follows:
Consider the quadratic form
$$
q(x) = \sum_{i,j=1}^{n}{x_i x_j} ~(\mathrm{mod}~ 4)
$$
and restrict $q(x)$ onto the nullspace of A. This results in a linear function.
$$
2 \sum_{i=1}^{n}{z_i x_i} ~(\mathrm{mod}~ 4) \forall x \in \mathrm{Ker}(A)
$$
and the goal is to recover this linear function (equivalently a vector $[z_0, ..., z_{n-1}]$). There can be multiple solutions.
In \[1] it is shown that the present circuit solves this problem on a quantum computer in constant depth, whereas any corresponding solution on a classical computer would require circuits that grow logarithmically with $n$. Thus this circuit is an example of quantum advantage with shallow circuits.
**Reference Circuit:**
> 
**Reference:**
\[1] S. Bravyi, D. Gosset, R. Koenig, Quantum Advantage with Shallow Circuits, 2017. [arXiv:1704.00690](https://arxiv.org/abs/1704.00690)
Create new HLF circuit.
**Parameters**
**adjacency\_matrix** ([*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.12)")*\[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]] |* [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(in NumPy v1.26)")) β a symmetric n-by-n list of 0-1 lists. n will be the number of qubits.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If A is not symmetric.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.instances" attributeValue="176" />
### layout
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.HiddenLinearFunction.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.HiddenLinearFunction.mdx
|
---
title: HRSCumulativeMultiplier
description: API reference for qiskit.circuit.library.HRSCumulativeMultiplier
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.HRSCumulativeMultiplier
---
# HRSCumulativeMultiplier
<Class id="qiskit.circuit.library.HRSCumulativeMultiplier" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/arithmetic/multipliers/hrs_cumulative_multiplier.py#L21-L138" signature="qiskit.circuit.library.HRSCumulativeMultiplier(num_state_qubits, num_result_qubits=None, adder=None, name='HRSCumulativeMultiplier')" modifiers="class">
Bases: `Multiplier`
A multiplication circuit to store product of two input registers out-of-place.
Circuit uses the approach from \[1]. As an example, a multiplier circuit that performs a non-modular multiplication on two 3-qubit sized registers with the default adder is as follows (where `Adder` denotes the `CDKMRippleCarryAdder`):
```python
a_0: βββββ βββββββββββββββββββββββββ
β
a_1: βββββΌββββββββββ βββββββββββββββ
β β
a_2: βββββΌββββββββββΌββββββββββ βββββ
βββββ΄ββββββββββ΄ββββββββββ΄βββββ
b_0: β€0 ββ€0 ββ€0 β
β ββ ββ β
b_1: β€1 ββ€1 ββ€1 β
β ββ ββ β
b_2: β€2 ββ€2 ββ€2 β
β ββ ββ β
out_0: β€3 ββ€ ββ€ β
β ββ ββ β
out_1: β€4 ββ€3 ββ€ β
β Adder ββ Adder ββ Adder β
out_2: β€5 ββ€4 ββ€3 β
β ββ ββ β
out_3: β€6 ββ€5 ββ€4 β
β ββ ββ β
out_4: β€ ββ€6 ββ€5 β
β ββ ββ β
out_5: β€ ββ€ ββ€6 β
β ββ ββ β
aux_0: β€7 ββ€7 ββ€7 β
ββββββββββββββββββββββββββββββ
```
Multiplication in this circuit is implemented in a classical approach by performing a series of shifted additions using one of the input registers while the qubits from the other input register act as control qubits for the adders.
**References:**
\[1] HΓ€ner et al., Optimizing Quantum Circuits for Arithmetic, 2018. [arXiv:1805.12445](https://arxiv.org/pdf/1805.12445.pdf)
**Parameters**
* **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β The number of qubits in either input register for state $|a\rangle$ or $|b\rangle$. The two input registers must have the same number of qubits.
* **num\_result\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β The number of result qubits to limit the output to. If number of result qubits is $n$, multiplication modulo $2^n$ is performed to limit the output to the specified number of qubits. Default value is `2 * num_state_qubits` to represent any possible result from the multiplication of the two inputs.
* **adder** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit") *| None*) β Half adder circuit to be used for performing multiplication. The CDKMRippleCarryAdder is used as default if no adder is provided.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β The name of the circuit object.
**Raises**
[**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError "(in Python v3.12)") β If `num_result_qubits` is not default and a custom adder is provided.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.instances" attributeValue="174" />
### layout
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.num_qubits">
Return number of qubits.
</Attribute>
### num\_result\_qubits
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.num_result_qubits">
The number of result qubits to limit the output to.
**Returns**
The number of result qubits.
</Attribute>
### num\_state\_qubits
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.num_state_qubits">
The number of state qubits, i.e. the number of bits in each input register.
**Returns**
The number of state qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.HRSCumulativeMultiplier.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.HRSCumulativeMultiplier.mdx
|
---
title: IGate
description: API reference for qiskit.circuit.library.IGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.IGate
---
# IGate
<Class id="qiskit.circuit.library.IGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/i.py#L20-L73" signature="qiskit.circuit.library.IGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate "qiskit.circuit.singleton.SingletonGate")
Identity gate.
Identity gate corresponds to a single-qubit gate wait cycle, and should not be optimized or unrolled (it is an opaque gate).
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the `i()` and [`id()`](qiskit.circuit.QuantumCircuit#id "qiskit.circuit.QuantumCircuit.id") methods.
**Matrix Representation:**
$$
I = \begin{pmatrix}
1 & 0 \\
0 & 1
\end{pmatrix}
$$
**Circuit symbol:**
```python
βββββ
q_0: β€ I β
βββββ
```
Create new Identity gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.IGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.IGate.base_class "qiskit.circuit.library.IGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.IGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.IGate.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.IGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.IGate.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.IGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.IGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.IGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.IGate.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.IGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.IGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.IGate.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.IGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inverse
<Function id="qiskit.circuit.library.IGate.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/i.py#L54-L66" signature="inverse(annotated=False)">
Returne the inverse gate (itself).
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"). However, for this class this argument is ignored as this gate is self-inverse.
**Returns**
inverse gate (self-inverse).
**Return type**
[IGate](#qiskit.circuit.library.IGate "qiskit.circuit.library.IGate")
.
</Function>
### power
<Function id="qiskit.circuit.library.IGate.power" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/i.py#L68-L70" signature="power(exponent)">
Raise gate to a power.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.IGate.mdx
|
---
title: Initialize
description: API reference for qiskit.circuit.library.Initialize
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.Initialize
---
# Initialize
<Class id="qiskit.circuit.library.Initialize" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/data_preparation/initializer.py#L32-L96" signature="qiskit.circuit.library.Initialize(params, num_qubits=None, normalize=False)" modifiers="class">
Bases: [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.instruction.Instruction")
Complex amplitude initialization.
Class that initializes some flexible collection of qubit registers, implemented by calling the [`StatePreparation`](qiskit.circuit.library.StatePreparation "qiskit.circuit.library.StatePreparation") class. Note that `Initialize` is an [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction") and not a [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate") since it contains a reset instruction, which is not unitary.
**Parameters**
* **params** ([*Statevector*](qiskit.quantum_info.Statevector "qiskit.quantum_info.Statevector") *| Sequence\[*[*complex*](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)")*] |* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *|*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β
The state to initialize to, can be either of the following.
* Statevector or vector of complex amplitudes to initialize to.
* Labels of basis states of the Pauli eigenstates Z, X, Y. See [`Statevector.from_label()`](qiskit.quantum_info.Statevector#from_label "qiskit.quantum_info.Statevector.from_label"). Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label β01β initializes the qubit zero to $|1\rangle$ and the qubit one to $|0\rangle$.
* An integer that is used as a bitmap indicating which qubits to initialize to $|1\rangle$. Example: setting params to 5 would initialize qubit 0 and qubit 2 to $|1\rangle$ and qubit 1 to $|0\rangle$.
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β This parameter is only used if params is an int. Indicates the total number of qubits in the initialize call. Example: initialize covers 5 qubits and params is 3. This allows qubits 0 and 1 to be initialized to $|1\rangle$ and the remaining 3 qubits to be initialized to $|0\rangle$.
* **normalize** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β Whether to normalize an input array to a unit vector.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.Initialize.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.Initialize.base_class "qiskit.circuit.library.Initialize.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.Initialize.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.Initialize.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.Initialize.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.Initialize.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.Initialize.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.Initialize.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.Initialize.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.Initialize.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.Initialize.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.Initialize.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.Initialize.params">
Return initialize params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.Initialize.unit">
Get the time unit of duration.
</Attribute>
## Methods
### broadcast\_arguments
<Function id="qiskit.circuit.library.Initialize.broadcast_arguments" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/data_preparation/initializer.py#L95-L96" signature="broadcast_arguments(qargs, cargs)">
Validation of the arguments.
**Parameters**
* **qargs** (*List*) β List of quantum bit arguments.
* **cargs** (*List*) β List of classical bit arguments.
**Yields**
*Tuple(List, List)* β A tuple with single arguments.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β If the input is not valid. For example, the number of arguments does not match the gate expectation.
</Function>
### gates\_to\_uncompute
<Function id="qiskit.circuit.library.Initialize.gates_to_uncompute" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/data_preparation/initializer.py#L77-L83" signature="gates_to_uncompute()">
Call to create a circuit with gates that take the desired vector to zero.
**Returns**
Circuit to take `self.params` vector to $|{00\ldots0}\rangle$
**Return type**
[*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.Initialize.mdx
|
---
title: InnerProduct
description: API reference for qiskit.circuit.library.InnerProduct
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.InnerProduct
---
# InnerProduct
<Class id="qiskit.circuit.library.InnerProduct" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/boolean_logic/inner_product.py#L20-L78" signature="qiskit.circuit.library.InnerProduct(num_qubits)" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
A 2n-qubit Boolean function that computes the inner product of two n-qubit vectors over $F_2$.
This implementation is a phase oracle which computes the following transform.
$$
\mathcal{IP}_{2n} : F_2^{2n} \rightarrow {-1, 1}
\mathcal{IP}_{2n}(x_1, \cdots, x_n, y_1, \cdots, y_n) = (-1)^{x.y}
$$
The corresponding unitary is a diagonal, which induces a -1 phase on any inputs where the inner product of the top and bottom registers is 1. Otherwise it keeps the input intact.
```python
q0_0: ββ ββββββββββ
β
q0_1: ββΌβββ βββββββ
β β
q0_2: ββΌβββΌβββ ββββ
β β β
q0_3: ββΌβββΌβββΌβββ β
β β β β
q1_0: ββ βββΌβββΌβββΌβ
β β β
q1_1: βββββ βββΌβββΌβ
β β
q1_2: ββββββββ βββΌβ
β
q1_3: βββββββββββ β
```
**Reference Circuit:**

Return a circuit to compute the inner product of 2 n-qubit registers.
**Parameters**
**num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β width of top and bottom registers (half total circuit width)
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.InnerProduct.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.InnerProduct.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.InnerProduct.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.InnerProduct.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.InnerProduct.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.InnerProduct.instances" attributeValue="194" />
### layout
<Attribute id="qiskit.circuit.library.InnerProduct.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.InnerProduct.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.InnerProduct.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.InnerProduct.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.InnerProduct.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.InnerProduct.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.InnerProduct.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.InnerProduct.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.InnerProduct.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.InnerProduct.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.InnerProduct.mdx
|
---
title: IntegerComparator
description: API reference for qiskit.circuit.library.IntegerComparator
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.IntegerComparator
---
# IntegerComparator
<Class id="qiskit.circuit.library.IntegerComparator" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/arithmetic/integer_comparator.py#L25-L243" signature="qiskit.circuit.library.IntegerComparator(num_state_qubits=None, value=None, geq=True, name='cmp')" modifiers="class">
Bases: `BlueprintCircuit`
Integer Comparator.
Operator compares basis states $|i\rangle_n$ against a classically given integer $L$ of fixed value and flips a target qubit if $i \geq L$ (or $<$ depending on the parameter `geq`):
$$
|i\rangle_n |0\rangle \mapsto |i\rangle_n |i \geq L\rangle
$$
This operation is based on twoβs complement implementation of binary subtraction but only uses carry bits and no actual result bits. If the most significant carry bit (the results bit) is 1, the $\geq$ condition is `True` otherwise it is `False`.
Create a new fixed value comparator circuit.
**Parameters**
* **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β Number of state qubits. If this is set it will determine the number of qubits required for the circuit.
* **value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") *| None*) β The fixed value to compare with.
* **geq** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β If True, evaluate a `>=` condition, else `<`.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Name of the circuit.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.IntegerComparator.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.IntegerComparator.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.IntegerComparator.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.IntegerComparator.data" />
### geq
<Attribute id="qiskit.circuit.library.IntegerComparator.geq">
Return whether the comparator compares greater or less equal.
**Returns**
True, if the comparator compares `>=`, False if `<`.
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.IntegerComparator.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.IntegerComparator.instances" attributeValue="196" />
### layout
<Attribute id="qiskit.circuit.library.IntegerComparator.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.IntegerComparator.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.IntegerComparator.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.IntegerComparator.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.IntegerComparator.num_parameters" />
### num\_qubits
<Attribute id="qiskit.circuit.library.IntegerComparator.num_qubits">
Return number of qubits.
</Attribute>
### num\_state\_qubits
<Attribute id="qiskit.circuit.library.IntegerComparator.num_state_qubits">
The number of qubits encoding the state for the comparison.
**Returns**
The number of state qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.IntegerComparator.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.IntegerComparator.parameters" />
### prefix
<Attribute id="qiskit.circuit.library.IntegerComparator.prefix" attributeValue="'circuit'" />
### qregs
<Attribute id="qiskit.circuit.library.IntegerComparator.qregs" attributeTypeHint="list[QuantumRegister]">
A list of the quantum registers associated with the circuit.
</Attribute>
### qubits
<Attribute id="qiskit.circuit.library.IntegerComparator.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
### value
<Attribute id="qiskit.circuit.library.IntegerComparator.value">
The value to compare the qubit register to.
**Returns**
The value against which the value of the qubit register is compared.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.IntegerComparator.mdx
|
---
title: IQP
description: API reference for qiskit.circuit.library.IQP
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.IQP
---
# IQP
<Class id="qiskit.circuit.library.IQP" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/iqp.py#L22-L96" signature="qiskit.circuit.library.IQP(interactions)" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
Instantaneous quantum polynomial (IQP) circuit.
The circuit consists of a column of Hadamard gates, a column of powers of T gates, a sequence of powers of CS gates (up to $\frac{n^2-n}{2}$ of them), and a final column of Hadamard gates, as introduced in \[1].
The circuit is parameterized by an n x n interactions matrix. The powers of each T gate are given by the diagonal elements of the interactions matrix. The powers of the CS gates are given by the upper triangle of the interactions matrix.
**Reference Circuit:**

**Expanded Circuit:**
> 
**References:**
\[1] M. J. Bremner et al. Average-case complexity versus approximate simulation of commuting quantum computations, Phys. Rev. Lett. 117, 080501 (2016). [arXiv:1504.07999](https://arxiv.org/abs/1504.07999)
Create IQP circuit.
**Parameters**
**interactions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)") *| np.ndarray*) β input n-by-n symmetric matrix.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the inputs is not as symmetric matrix.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.IQP.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.IQP.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.IQP.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.IQP.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.IQP.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.IQP.instances" attributeValue="181" />
### layout
<Attribute id="qiskit.circuit.library.IQP.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.IQP.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.IQP.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.IQP.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.IQP.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.IQP.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.IQP.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.IQP.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.IQP.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.IQP.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.IQP.mdx
|
---
title: Isometry
description: API reference for qiskit.circuit.library.Isometry
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.Isometry
---
# Isometry
<Class id="qiskit.circuit.library.Isometry" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/isometry.py#L40-L337" signature="qiskit.circuit.library.Isometry(isometry, num_ancillas_zero, num_ancillas_dirty, epsilon=1e-10)" modifiers="class">
Bases: [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.instruction.Instruction")
Decomposition of arbitrary isometries from $m$ to $n$ qubits.
In particular, this allows to decompose unitaries (m=n) and to do state preparation ($m=0$).
The decomposition is based on \[1].
**References:**
**\[1] Iten et al., Quantum circuits for isometries (2016).**
[Phys. Rev. A 93, 032318](https://journals.aps.org/pra/abstract/10.1103/PhysRevA.93.032318).
**Parameters**
* **isometry** (*np.ndarray*) β An isometry from $m$ to :math\`n\` qubits, i.e., a complex `np.ndarray` of dimension $2^n \times 2^m$ with orthonormal columns (given in the computational basis specified by the order of the ancillas and the input qubits, where the ancillas are considered to be more significant than the input qubits).
* **num\_ancillas\_zero** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of additional ancillas that start in the state $|0\rangle$ (the $n-m$ ancillas required for providing the output of the isometry are not accounted for here).
* **num\_ancillas\_dirty** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β Number of additional ancillas that start in an arbitrary state.
* **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β Error tolerance of calculations.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.Isometry.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.Isometry.base_class "qiskit.circuit.library.Isometry.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.Isometry.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.Isometry.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.Isometry.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.Isometry.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.Isometry.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.Isometry.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.Isometry.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.Isometry.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.Isometry.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.Isometry.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.Isometry.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.Isometry.unit">
Get the time unit of duration.
</Attribute>
## Methods
### inv\_gate
<Function id="qiskit.circuit.library.Isometry.inv_gate" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/isometry.py#L329-L337" signature="inv_gate()">
Return the adjoint of the unitary.
</Function>
### inverse
<Function id="qiskit.circuit.library.Isometry.inverse" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/isometry.py#L130-L134" signature="inverse(annotated=False)">
Invert this instruction.
If annotated is False, the inverse instruction is implemented as a fresh instruction with the recursively inverted definition.
If annotated is True, the inverse instruction is implemented as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation"), and corresponds to the given instruction annotated with the βinverse modifierβ.
Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) In particular, they can choose how to handle the argument `annotated` which may include ignoring it and always returning a concrete gate class if the inverse is defined as a standard gate.
**Parameters**
**annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) β if set to True the output inverse gate will be returned as [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation").
**Returns**
The inverse operation.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") β if the instruction is not composite and an inverse has not been implemented for it.
</Function>
### validate\_parameter
<Function id="qiskit.circuit.library.Isometry.validate_parameter" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/generalized_gates/isometry.py#L320-L327" signature="validate_parameter(parameter)">
Isometry parameter has to be an ndarray.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.Isometry.mdx
|
---
title: iSwapGate
description: API reference for qiskit.circuit.library.iSwapGate
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.iSwapGate
---
# iSwapGate
<Class id="qiskit.circuit.library.iSwapGate" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/iswap.py#L26-L132" signature="qiskit.circuit.library.iSwapGate(*args, _force_mutable=False, **kwargs)" modifiers="class">
Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate "qiskit.circuit.singleton.SingletonGate")
iSWAP gate.
A 2-qubit XX+YY interaction. This is a Clifford and symmetric gate. Its action is to swap two qubit states and phase the $|01\rangle$ and $|10\rangle$ amplitudes by i.
Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") with the [`iswap()`](qiskit.circuit.QuantumCircuit#iswap "qiskit.circuit.QuantumCircuit.iswap") method.
**Circuit Symbol:**
```python
q_0: ββ¨β
β
q_1: ββ¨β
```
**Reference Implementation:**
```python
ββββββββββ βββββ
q_0: β€ S ββ€ H ββββ βββ€ X ββββββ
βββββ€ββββββββ΄βββββ¬βββββββ
q_1: β€ S βββββββ€ X ββββ βββ€ H β
βββββ βββββ βββββ
```
**Matrix Representation:**
$$
iSWAP = R_{XX+YY}\left(-\frac{\pi}{2}\right)
= \exp\left(i \frac{\pi}{4} \left(X{\otimes}X+Y{\otimes}Y\right)\right) =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 0 & i & 0 \\
0 & i & 0 & 0 \\
0 & 0 & 0 & 1
\end{pmatrix}
$$
This gate is equivalent to a SWAP up to a diagonal.
$$
iSWAP =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1
\end{pmatrix}
. \begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & i & 0 & 0 \\
0 & 0 & i & 0 \\
0 & 0 & 0 & 1
\end{pmatrix}
$$
Create new iSwap gate.
## Attributes
### base\_class
<Attribute id="qiskit.circuit.library.iSwapGate.base_class">
Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`.
The βbase classβ of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the βtrueβ class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.iSwapGate.base_class "qiskit.circuit.library.iSwapGate.base_class") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target") from the full parametrised gate.
This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:
```python
>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True
```
In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations.
</Attribute>
### condition
<Attribute id="qiskit.circuit.library.iSwapGate.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.library.iSwapGate.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.library.iSwapGate.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.library.iSwapGate.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.library.iSwapGate.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.library.iSwapGate.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.library.iSwapGate.mutable">
Is this instance is a mutable unique instance or not.
If this attribute is `False` the gate instance is a shared singleton and is not mutable.
</Attribute>
### name
<Attribute id="qiskit.circuit.library.iSwapGate.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.iSwapGate.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.iSwapGate.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.library.iSwapGate.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.library.iSwapGate.unit">
Get the time unit of duration.
</Attribute>
## Methods
### power
<Function id="qiskit.circuit.library.iSwapGate.power" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/standard_gates/iswap.py#L127-L129" signature="power(exponent)">
Raise gate to a power.
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.iSwapGate.mdx
|
---
title: LinearAmplitudeFunction
description: API reference for qiskit.circuit.library.LinearAmplitudeFunction
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.library.LinearAmplitudeFunction
---
# LinearAmplitudeFunction
<Class id="qiskit.circuit.library.LinearAmplitudeFunction" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/arithmetic/linear_amplitude_function.py#L22-L173" signature="qiskit.circuit.library.LinearAmplitudeFunction(num_state_qubits, slope, offset, domain, image, rescaling_factor=1, breakpoints=None, name='F')" modifiers="class">
Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.quantumcircuit.QuantumCircuit")
A circuit implementing a (piecewise) linear function on qubit amplitudes.
An amplitude function $F$ of a function $f$ is a mapping
$$
F|x\rangle|0\rangle = \sqrt{1 - \hat{f}(x)} |x\rangle|0\rangle + \sqrt{\hat{f}(x)}
|x\rangle|1\rangle.
$$
for a function $\hat{f}: \{ 0, ..., 2^n - 1 \} \rightarrow [0, 1]$, where $|x\rangle$ is a $n$ qubit state.
This circuit implements $F$ for piecewise linear functions $\hat{f}$. In this case, the mapping $F$ can be approximately implemented using a Taylor expansion and linearly controlled Pauli-Y rotations, see \[1, 2] for more detail. This approximation uses a `rescaling_factor` to determine the accuracy of the Taylor expansion.
In general, the function of interest $f$ is defined from some interval $[a,b]$, the `domain` to $[c,d]$, the `image`, instead of $\{ 1, ..., N \}$ to $[0, 1]$. Using an affine transformation we can rescale $f$ to $\hat{f}$:
$$
\hat{f}(x) = \frac{f(\phi(x)) - c}{d - c}
$$
with
$$
\phi(x) = a + \frac{b - a}{2^n - 1} x.
$$
If $f$ is a piecewise linear function on $m$ intervals $[p_{i-1}, p_i], i \in \{1, ..., m\}$ with slopes $\alpha_i$ and offsets $\beta_i$ it can be written as
$$
f(x) = \sum_{i=1}^m 1_{[p_{i-1}, p_i]}(x) (\alpha_i x + \beta_i)
$$
where $1_{[a, b]}$ is an indication function that is 1 if the argument is in the interval $[a, b]$ and otherwise 0. The breakpoints $p_i$ can be specified by the `breakpoints` argument.
**References**
**\[1]: Woerner, S., & Egger, D. J. (2018).**
Quantum Risk Analysis. [arXiv:1806.06893](http://arxiv.org/abs/1806.06893)
**\[2]: Gacon, J., Zoufal, C., & Woerner, S. (2020).**
Quantum-Enhanced Simulation-Based Optimization. [arXiv:2005.10780](http://arxiv.org/abs/2005.10780)
**Parameters**
* **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) β The number of qubits used to encode the variable $x$.
* **slope** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*]*) β The slope of the linear function. Can be a list of slopes if it is a piecewise linear function.
* **offset** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*]*) β The offset of the linear function. Can be a list of offsets if it is a piecewise linear function.
* **domain** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*]*) β The domain of the function as tuple $(x_\min{}, x_\max{})$.
* **image** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*]*) β The image of the function as tuple $(f_\min{}, f_\max{})$.
* **rescaling\_factor** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β The rescaling factor to adjust the accuracy in the Taylor approximation.
* **breakpoints** ([*list*](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.12)")*\[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*] | None*) β The breakpoints if the function is piecewise linear. If None, the function is not piecewise.
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) β Name of the circuit.
## Attributes
### ancillas
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.ancillas">
Returns a list of ancilla bits in the order that the registers were added.
</Attribute>
### calibrations
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.calibrations">
Return calibration dictionary.
The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`
</Attribute>
### clbits
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.clbits">
Returns a list of classical bits in the order that the registers were added.
</Attribute>
### data
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.data">
Return the circuit data (instructions and context).
**Returns**
a list-like object containing the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction")s for each instruction.
**Return type**
QuantumCircuitData
</Attribute>
### global\_phase
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.global_phase">
Return the global phase of the current circuit scope in radians.
</Attribute>
### instances
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.instances" attributeValue="196" />
### layout
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.layout">
Return any associated layout information about the circuit
This attribute contains an optional [`TranspileLayout`](qiskit.transpiler.TranspileLayout "qiskit.transpiler.TranspileLayout") object. This is typically set on the output from [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") or [`PassManager.run()`](qiskit.transpiler.PassManager#run "qiskit.transpiler.PassManager.run") to retain information about the permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the [`transpile()`](compiler#qiskit.compiler.transpile "qiskit.compiler.transpile") function, an initial layout which permutes the qubits based on the selected physical qubits on the [`Target`](qiskit.transpiler.Target "qiskit.transpiler.Target"), and a final layout which is an output permutation caused by [`SwapGate`](qiskit.circuit.library.SwapGate "qiskit.circuit.library.SwapGate")s inserted during routing.
</Attribute>
### metadata
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.metadata">
The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided `dict` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit.
</Attribute>
### num\_ancillas
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.num_ancillas">
Return the number of ancilla qubits.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.num_clbits">
Return number of classical bits.
</Attribute>
### num\_parameters
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.num_parameters">
The number of parameter objects in the circuit.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.num_qubits">
Return number of qubits.
</Attribute>
### op\_start\_times
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.op_start_times">
Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit.
**Returns**
List of integers representing instruction start times. The index corresponds to the index of instruction in `QuantumCircuit.data`.
**Raises**
[**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.12)") β When circuit is not scheduled.
</Attribute>
### parameters
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.parameters">
The parameters defined in the circuit.
This attribute returns the [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit sorted alphabetically. Note that parameters instantiated with a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") are still sorted numerically.
**Examples**
The snippet below shows that insertion order of parameters does not matter.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
```
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal β10β comes before β2β in strict alphabetical sorting.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
βββββββββββββββββββββββββββββββ
q: β€ U(angle_1,angle_2,angle_10) β
βββββββββββββββββββββββββββββββ
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
```
To respect numerical sorting, a [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector") can be used.
```python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
```
**Returns**
The sorted [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") objects in the circuit.
</Attribute>
### prefix
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.prefix" attributeValue="'circuit'" />
### qubits
<Attribute id="qiskit.circuit.library.LinearAmplitudeFunction.qubits">
Returns a list of quantum bits in the order that the registers were added.
</Attribute>
## Methods
### post\_processing
<Function id="qiskit.circuit.library.LinearAmplitudeFunction.post_processing" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/library/arithmetic/linear_amplitude_function.py#L154-L173" signature="post_processing(scaled_value)">
Map the function value of the approximated $\hat{f}$ to $f$.
**Parameters**
**scaled\_value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) β A function value from the Taylor expansion of $\hat{f}(x)$.
**Returns**
The `scaled_value` mapped back to the domain of $f$, by first inverting the transformation used for the Taylor approximation and then mapping back from $[0, 1]$ to the original domain.
**Return type**
[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")
</Function>
</Class>
|
repo/docs/api/qiskit/1.0\qiskit.circuit.library.LinearAmplitudeFunction.mdx
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.