Prepare Qiskit 1.1 docs (#1400)

We will set up redirects in closed source.

The new circuit module rewrite suffers from
https://github.com/Qiskit/documentation/issues/1401. That's not blocking
this release, though.
This commit is contained in:
Eric Arellano 2024-05-17 05:05:00 -04:00 committed by GitHub
parent 593e21eb89
commit e057d3c16c
1925 changed files with 115375 additions and 12328 deletions

View File

@ -3840,6 +3840,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -4864,6 +4864,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -5843,6 +5843,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -5888,6 +5888,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -5888,6 +5888,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -5984,6 +5984,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -6009,6 +6009,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -6022,6 +6022,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -6022,6 +6022,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -6022,6 +6022,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -4362,6 +4362,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -4541,6 +4541,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -4524,6 +4524,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -4591,6 +4591,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -4588,6 +4588,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -4951,6 +4951,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -5155,6 +5155,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -5163,6 +5163,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -5159,6 +5159,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -4449,6 +4449,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -3410,6 +3410,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -3463,6 +3463,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -3492,6 +3492,10 @@
{
"title": "Release notes",
"children": [
{
"title": "1.1",
"url": "/api/qiskit/release-notes/1.1"
},
{
"title": "1.0",
"url": "/api/qiskit/release-notes/1.0"

View File

@ -0,0 +1,4 @@
{
"name": "qiskit",
"version": "1.0.2"
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,180 @@
---
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. |

View File

@ -0,0 +1,353 @@
---
title: circuit
description: API reference for qiskit.circuit
in_page_toc_min_heading_level: 2
python_api_type: module
python_api_name: qiskit.circuit
---
<span id="module-qiskit.circuit" />
<span id="qiskit-circuit" />
<span id="quantum-circuits-qiskit-circuit" />
# Quantum Circuits
<span id="module-qiskit.circuit" />
`qiskit.circuit`
## Overview
The fundamental element of quantum computing is the **quantum circuit**. A quantum circuit is a computational routine consisting of coherent quantum operations on quantum data, such as qubits. It is an ordered sequence of quantum gates, measurements and resets, which may be conditioned on real-time classical computation. A set of quantum gates is said to be universal if any unitary transformation of the quantum data can be efficiently approximated arbitrarily well as a sequence of gates in the set. Any quantum program can be represented by a sequence of quantum circuits and classical near-time computation.
In Qiskit, this core element is represented by the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") class. Below is an example of a quantum circuit that makes a three-qubit GHZ state defined as:
$$
|\psi\rangle = \left(|000\rangle+|111\rangle\right)/\sqrt{2}
$$
```python
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
```
![../\_images/circuit-1.png](/images/api/qiskit/1.0/circuit-1.png)
## Supplementary Information
### Quantum Circuit with conditionals
When building a quantum circuit, there can be interest in applying a certain gate only if a classical register has a specific value. This can be done with the [`InstructionSet.c_if()`](qiskit.circuit.InstructionSet#c_if "qiskit.circuit.InstructionSet.c_if") method.
In the following example, we start with a single-qubit circuit formed by only a Hadamard gate ([`HGate`](qiskit.circuit.library.HGate "qiskit.circuit.library.HGate")), in which we expect to get $|0\rangle$ and $|1\rangle$ with equal probability.
```python
from qiskit import transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
```
![../\_images/circuit-2.png](/images/api/qiskit/1.0/circuit-2.png)
```python
from qiskit.providers.basic_provider import BasicSimulator
backend = BasicSimulator()
tqc = transpile(qc, backend)
counts = backend.run(tqc).result().get_counts()
print(counts)
```
```python
{'0': 524, '1': 500}
```
Now, we add an [`XGate`](qiskit.circuit.library.XGate "qiskit.circuit.library.XGate") only if the value of the [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister") is 0. That way, if the state is $|0\rangle$, it will be changed to $|1\rangle$ and if the state is $|1\rangle$, it will not be changed at all, so the final state will always be $|1\rangle$.
```python
from qiskit import transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.x(0).c_if(cr, 0)
qc.measure(0, 0)
qc.draw('mpl')
```
![../\_images/circuit-3.png](/images/api/qiskit/1.0/circuit-3.png)
```python
from qiskit.providers.basic_provider import BasicSimulator
backend = BasicSimulator()
tqc = transpile(qc, backend)
counts = backend.run(tqc).result().get_counts()
print(counts)
```
```python
{'1': 1024}
```
### Quantum Circuit Properties
When constructing quantum circuits, there are several properties that help quantify the “size” of the circuits, and their ability to be run on a noisy quantum device. Some of these, like number of qubits, are straightforward to understand, while others like depth and number of tensor components require a bit more explanation. Here we will explain all of these properties, and, in preparation for understanding how circuits change when run on actual devices, highlight the conditions under which they change.
Consider the following circuit:
```python
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
```
![../\_images/circuit-4.png](/images/api/qiskit/1.0/circuit-4.png)
From the plot, it is easy to see that this circuit has 12 qubits, and a collection of Hadamard, CNOT, X, and SWAP gates. But how to quantify this programmatically? Because we can do single-qubit gates on all the qubits simultaneously, the number of qubits in this circuit is equal to the **width** of the circuit:
```python
qc.width()
```
```python
12
```
We can also just get the number of qubits directly:
```python
qc.num_qubits
```
```python
12
```
<Admonition title="Important" type="danger">
For a quantum circuit composed from just qubits, the circuit width is equal to the number of qubits. This is the definition used in quantum computing. However, for more complicated circuits with classical registers, and classically controlled gates, this equivalence breaks down. As such, from now on we will not refer to the number of qubits in a quantum circuit as the width.
</Admonition>
It is also straightforward to get the number and type of the gates in a circuit using [`QuantumCircuit.count_ops()`](qiskit.circuit.QuantumCircuit#count_ops "qiskit.circuit.QuantumCircuit.count_ops"):
```python
qc.count_ops()
```
```python
OrderedDict([('cx', 8), ('h', 5), ('x', 3), ('swap', 3)])
```
We can also get just the raw count of operations by computing the circuits [`QuantumCircuit.size()`](qiskit.circuit.QuantumCircuit#size "qiskit.circuit.QuantumCircuit.size"):
```python
qc.size()
```
```python
19
```
A particularly important circuit property is known as the circuit **depth**. The depth of a quantum circuit is a measure of how many “layers” of quantum gates, executed in parallel, it takes to complete the computation defined by the circuit. Because quantum gates take time to implement, the depth of a circuit roughly corresponds to the amount of time it takes the quantum computer to execute the circuit. Thus, the depth of a circuit is one important quantity used to measure if a quantum circuit can be run on a device.
The depth of a quantum circuit has a mathematical definition as the longest path in a directed acyclic graph (DAG). However, such a definition is a bit hard to grasp, even for experts. Fortunately, the depth of a circuit can be easily understood by anyone familiar with playing [Tetris](https://en.wikipedia.org/wiki/Tetris). Lets see how to compute this graphically:
![../\_images/depth.gif](/images/api/qiskit/1.0/depth.gif)
We can verify our graphical result using [`QuantumCircuit.depth()`](qiskit.circuit.QuantumCircuit#depth "qiskit.circuit.QuantumCircuit.depth"):
```python
qc.depth()
```
```python
9
```
## Quantum Circuit API
### Quantum Circuit Construction
| | |
| ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")(\*regs\[, name, global\_phase, ...]) | Create a new circuit. |
| [`QuantumRegister`](qiskit.circuit.QuantumRegister "qiskit.circuit.QuantumRegister")(\[size, name, bits]) | Implement a quantum register. |
| [`Qubit`](qiskit.circuit.Qubit "qiskit.circuit.Qubit")(\[register, index]) | Implement a quantum bit. |
| [`ClassicalRegister`](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister")(\[size, name, bits]) | Implement a classical register. |
| [`Clbit`](qiskit.circuit.Clbit "qiskit.circuit.Clbit")(\[register, index]) | Implement a classical bit. |
| [`AncillaRegister`](qiskit.circuit.AncillaRegister "qiskit.circuit.AncillaRegister")(\[size, name, bits]) | Implement an ancilla register. |
| [`AncillaQubit`](qiskit.circuit.AncillaQubit "qiskit.circuit.AncillaQubit")(\[register, index]) | A qubit used as ancillary qubit. |
| [`CircuitInstruction`](qiskit.circuit.CircuitInstruction "qiskit.circuit.CircuitInstruction") | A single instruction in a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"), comprised of the `operation` and various operands. |
| [`Register`](qiskit.circuit.Register "qiskit.circuit.Register")(\[size, name, bits]) | Implement a generic register. |
| [`Bit`](qiskit.circuit.Bit "qiskit.circuit.Bit")(\[register, index]) | Implement a generic bit. |
### Gates and Instructions
| | |
| -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate")(name, num\_qubits, params\[, label, ...]) | Unitary gate. |
| [`ControlledGate`](qiskit.circuit.ControlledGate "qiskit.circuit.ControlledGate")(name, num\_qubits, params\[, ...]) | Controlled unitary gate. |
| [`Delay`](qiskit.circuit.Delay "qiskit.circuit.Delay")(duration\[, unit]) | Do nothing and just delay/wait/idle for a specified duration. |
| [`Instruction`](qiskit.circuit.Instruction "qiskit.circuit.Instruction")(name, num\_qubits, num\_clbits, params) | Generic quantum instruction. |
| [`InstructionSet`](qiskit.circuit.InstructionSet "qiskit.circuit.InstructionSet")(\*\[, resource\_requester]) | Instruction collection, and their contexts. |
| [`Operation`](qiskit.circuit.Operation "qiskit.circuit.Operation")() | Quantum Operation Interface Class. |
| [`EquivalenceLibrary`](qiskit.circuit.EquivalenceLibrary "qiskit.circuit.EquivalenceLibrary")(\*\[, base]) | A library providing a one-way mapping of Gates to their equivalent implementations as QuantumCircuits. |
### Annotated Operations
| | |
| ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation "qiskit.circuit.AnnotatedOperation")(base\_op, modifiers) | Annotated operation. |
| [`InverseModifier`](qiskit.circuit.InverseModifier "qiskit.circuit.InverseModifier")() | Inverse modifier: specifies that the operation is inverted. |
| [`ControlModifier`](qiskit.circuit.ControlModifier "qiskit.circuit.ControlModifier")(\[num\_ctrl\_qubits, ctrl\_state]) | Control modifier: specifies that the operation is controlled by `num_ctrl_qubits` and has control state `ctrl_state`. |
| [`PowerModifier`](qiskit.circuit.PowerModifier "qiskit.circuit.PowerModifier")(power) | Power modifier: specifies that the operation is raised to the power `power`. |
### Control Flow Operations
| | |
| --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`ControlFlowOp`](qiskit.circuit.ControlFlowOp "qiskit.circuit.ControlFlowOp")(name, num\_qubits, num\_clbits, ...) | Abstract class to encapsulate all control flow operations. |
| [`IfElseOp`](qiskit.circuit.IfElseOp "qiskit.circuit.IfElseOp")(condition, true\_body\[, false\_body, ...]) | A circuit operation which executes a program (`true_body`) if a provided condition (`condition`) evaluates to true, and optionally evaluates another program (`false_body`) otherwise. |
| [`WhileLoopOp`](qiskit.circuit.WhileLoopOp "qiskit.circuit.WhileLoopOp")(condition, body\[, label]) | A circuit operation which repeatedly executes a subcircuit (`body`) until a condition (`condition`) evaluates as False. |
| [`ForLoopOp`](qiskit.circuit.ForLoopOp "qiskit.circuit.ForLoopOp")(indexset, loop\_parameter, body\[, ...]) | A circuit operation which repeatedly executes a subcircuit (`body`) parameterized by a parameter `loop_parameter` through the set of integer values provided in `indexset`. |
| [`SwitchCaseOp`](qiskit.circuit.SwitchCaseOp "qiskit.circuit.SwitchCaseOp")(target, cases, \*\[, label]) | A circuit operation that executes one particular circuit block based on matching a given `target` against an ordered list of `values`. |
| [`BreakLoopOp`](qiskit.circuit.BreakLoopOp "qiskit.circuit.BreakLoopOp")(num\_qubits, num\_clbits\[, label]) | A circuit operation which, when encountered, jumps to the end of the nearest enclosing loop. |
| [`ContinueLoopOp`](qiskit.circuit.ContinueLoopOp "qiskit.circuit.ContinueLoopOp")(num\_qubits, num\_clbits\[, label]) | A circuit operation which, when encountered, moves to the next iteration of the nearest enclosing loop. |
The [`SwitchCaseOp`](qiskit.circuit.SwitchCaseOp "qiskit.circuit.SwitchCaseOp") also understands a special value:
**qiskit.circuit.CASE\_DEFAULT**
A special object that represents the “default” case of a switch statement. If you use this as a case target, it must be the last case, and will match anything that wasnt already matched. For example:
```python
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit import SwitchCaseOp, CASE_DEFAULT
body0 = QuantumCircuit(2, 2)
body0.x(0)
body1 = QuantumCircuit(2, 2)
body1.z(0)
body2 = QuantumCircuit(2, 2)
body2.cx(0, 1)
qr, cr = QuantumRegister(2), ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.switch(cr, [(0, body0), (1, body1), (CASE_DEFAULT, body2)], qr, cr)
```
When using the builder interface of [`QuantumCircuit.switch()`](qiskit.circuit.QuantumCircuit#switch "qiskit.circuit.QuantumCircuit.switch"), this can also be accessed as the `DEFAULT` attribute of the bound case-builder object, such as:
```python
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
qr, cr = QuantumRegister(2), ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
with qc.switch(cr) as case:
with case(0):
qc.x(0)
with case(1):
qc.z(0)
with case(case.DEFAULT):
qc.cx(0, 1)
```
### Parametric Quantum Circuits
| | |
| ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter")(name, \*\[, uuid]) | Parameter Class for variable parameters. |
| [`ParameterVector`](qiskit.circuit.ParameterVector "qiskit.circuit.ParameterVector")(name\[, length]) | ParameterVector class to quickly generate lists of parameters. |
| [`ParameterExpression`](qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")(symbol\_map, expr) | ParameterExpression class to enable creating expressions of Parameters. |
### Gate Commutation
| | |
| ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| [`CommutationChecker`](qiskit.circuit.CommutationChecker "qiskit.circuit.CommutationChecker")(\[...]) | This code is essentially copy-pasted from commutative\_analysis.py. |
### Random Circuits
#### random\_circuit
<Function id="qiskit.circuit.random.random_circuit" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/random/utils.py#L23-L209" signature="qiskit.circuit.random.random_circuit(num_qubits, depth, max_operands=4, measure=False, conditional=False, reset=False, seed=None)">
Generate random circuit of arbitrary size and form.
This function will generate a random circuit by randomly selecting gates from the set of standard gates in `qiskit.circuit.library.standard_gates`. For example:
```python
from qiskit.circuit.random import random_circuit
circ = random_circuit(2, 2, measure=True)
circ.draw(output='mpl')
```
![../\_images/circuit-5.png](/images/api/qiskit/1.0/circuit-5.png)
**Parameters**
* **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) number of quantum wires
* **depth** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) layers of operations (i.e. critical path length)
* **max\_operands** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) maximum qubit operands of each gate (between 1 and 4)
* **measure** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) if True, measure all qubits at the end
* **conditional** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) if True, insert middle measurements and conditionals
* **reset** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) if True, insert middle resets
* **seed** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) sets random seed (optional)
**Returns**
constructed circuit
**Return type**
[QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")
**Raises**
[**CircuitError**](#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") when invalid options given
</Function>
### Exceptions
Almost all circuit functions and methods will raise a [`CircuitError`](#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError") when encountering an error that is particular to usage of Qiskit (as opposed to regular typing or indexing problems, which will typically raise the corresponding standard Python error).
#### CircuitError
<Class id="qiskit.circuit.CircuitError" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/exceptions.py#L18-L19" signature="qiskit.circuit.CircuitError(*message)" modifiers="exception">
Base class for errors raised while processing a circuit.
Set the error message.
</Class>

View File

@ -0,0 +1,938 @@
---
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>
Qiskits 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).
Theres 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 its 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 its 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>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,208 @@
---
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 its 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 Qiskits 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 constructors 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 constructors 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 classs `__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, its 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, its 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 cant 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 wed 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)"). Its 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 classs 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.

View File

@ -0,0 +1,84 @@
---
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 Qiskits 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. |

View File

@ -0,0 +1,304 @@
---
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 backends. If any other options is set in the run\_config, it will also override the backends.
* **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 backends.
* **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 doesnt 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 youd 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>

View File

@ -0,0 +1,248 @@
---
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')
```
![../\_images/converters-1.png](/images/api/qiskit/1.0/converters-1.png)
</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>

View File

@ -0,0 +1,50 @@
---
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>

View File

@ -0,0 +1,107 @@
---
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)
```

View File

@ -0,0 +1,47 @@
---
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)

View File

@ -0,0 +1,170 @@
---
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 dont 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>

View File

@ -0,0 +1,351 @@
---
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. |

View File

@ -0,0 +1,499 @@
---
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 cant be removed until the deprecation policy completes.
Its worth pointing out that Terras version support policy doesnt 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 Terras 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, lets 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 theyd 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 backends 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 doesnt 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 Backends basis set your custom gates 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. Youll 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 youve defined the custom gates to use for the backends 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 doesnt 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 providers 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.
Its also worth noting that depending on the basis youre 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 backends [`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 whats 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 backends 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 providers 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 backends 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 cant 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 wont 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.

View File

@ -0,0 +1,52 @@
---
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. |

View File

@ -0,0 +1,122 @@
---
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)
```
![../\_images/providers\_fake\_provider-1\_00.png](/images/api/qiskit/1.0/providers_fake_provider-1_00.png)
![../\_images/providers\_fake\_provider-1\_01.png](/images/api/qiskit/1.0/providers_fake_provider-1_01.png)
![../\_images/providers\_fake\_provider-1\_02.png](/images/api/qiskit/1.0/providers_fake_provider-1_02.png)
## 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>

View File

@ -0,0 +1,39 @@
---
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 |

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,512 @@
---
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.
Qiskits 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 Qiskits [`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 wouldnt 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 Qiskits legacy converter behaviour.
**qiskit.qasm2.LEGACY\_CUSTOM\_INSTRUCTIONS**
A tuple containing the extra custom\_instructions that Qiskits 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 Qiskits 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 Qiskits 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 Qiskits 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 Qiskits 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. Qiskits 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 Qiskits [`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.

View File

@ -0,0 +1,405 @@
---
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 Qiskits 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")
```
![../\_images/qasm3-1.png](/images/api/qiskit/1.0/qasm3-1.png)
### 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.

View File

@ -0,0 +1,100 @@
---
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>

View File

@ -0,0 +1,117 @@
---
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>

View File

@ -0,0 +1,307 @@
---
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)")) instructions qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) instructions 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)")) instructions 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>

View File

@ -0,0 +1,78 @@
---
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 classs 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 users 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>

View File

@ -0,0 +1,311 @@
---
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)")) instructions qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) instructions 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)")) instructions 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>

View File

@ -0,0 +1,313 @@
---
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)")) instructions qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) instructions 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)")) instructions 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>

View File

@ -0,0 +1,448 @@
---
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')
```
![../\_images/qiskit-circuit-ControlledGate-1.png](/images/api/qiskit/1.0/qiskit-circuit-ControlledGate-1.png)
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')
```
![../\_images/qiskit-circuit-ControlledGate-2.png](/images/api/qiskit/1.0/qiskit-circuit-ControlledGate-2.png)
## 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>

View File

@ -0,0 +1,168 @@
---
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>

View File

@ -0,0 +1,326 @@
---
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)")) instructions qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) instructions 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)")) instructions 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>

View File

@ -0,0 +1,382 @@
---
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>

View File

@ -0,0 +1,338 @@
---
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)")) instructions qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) instructions 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)")) instructions 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>

View File

@ -0,0 +1,293 @@
---
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)")) instructions qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) instructions 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)")) instructions 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>

View File

@ -0,0 +1,113 @@
---
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')
```
![../\_images/qiskit-circuit-InstructionSet-1.png](/images/api/qiskit/1.0/qiskit-circuit-InstructionSet-1.png)
</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>

View File

@ -0,0 +1,53 @@
---
title: Operation
description: API reference for qiskit.circuit.Operation
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.Operation
---
# Operation
<Class id="qiskit.circuit.Operation" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/operation.py#L18-L62" signature="qiskit.circuit.Operation" modifiers="class">
Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC "(in Python v3.12)")
Quantum Operation Interface Class. For objects that can be added to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit"). These objects include [`Gate`](qiskit.circuit.Gate "qiskit.circuit.Gate"), `Reset`, `Barrier`, `Measure`, and operators such as [`Clifford`](qiskit.quantum_info.Clifford "qiskit.quantum_info.Clifford"). The main purpose is to add an [`Operation`](#qiskit.circuit.Operation "qiskit.circuit.Operation") to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit") without synthesizing it before the transpilation.
**Example**
Add a Clifford and a Toffoli gate to a QuantumCircuit.
```python
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford, random_clifford
qc = QuantumCircuit(3)
cliff = random_clifford(2)
qc.append(cliff, [0, 1])
qc.ccx(0, 1, 2)
qc.draw('mpl')
```
![../\_images/qiskit-circuit-Operation-1.png](/images/api/qiskit/1.0/qiskit-circuit-Operation-1.png)
## Attributes
### name
<Attribute id="qiskit.circuit.Operation.name">
Unique string identifier for operation type.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.Operation.num_clbits">
Number of classical bits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.Operation.num_qubits">
Number of qubits.
</Attribute>
</Class>

View File

@ -0,0 +1,252 @@
---
title: Parameter
description: API reference for qiskit.circuit.Parameter
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.Parameter
---
# Parameter
<Class id="qiskit.circuit.Parameter" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameter.py#L27-L170" signature="qiskit.circuit.Parameter(name, *, uuid=None)" modifiers="class">
Bases: [`ParameterExpression`](qiskit.circuit.ParameterExpression "qiskit.circuit.parameterexpression.ParameterExpression")
Parameter Class for variable parameters.
A parameter is a variable value that is not required to be fixed at circuit definition.
**Examples**
Construct a variable-rotation X gate using circuit parameters.
```python
from qiskit.circuit import QuantumCircuit, Parameter
# create the parameter
phi = Parameter('phi')
qc = QuantumCircuit(1)
# parameterize the rotation
qc.rx(phi, 0)
qc.draw('mpl')
# bind the parameters after circuit to create a bound circuit
bc = qc.assign_parameters({phi: 3.14})
bc.measure_all()
bc.draw('mpl')
```
![../\_images/qiskit-circuit-Parameter-1\_00.png](/images/api/qiskit/1.0/qiskit-circuit-Parameter-1_00.png)
![../\_images/qiskit-circuit-Parameter-1\_01.png](/images/api/qiskit/1.0/qiskit-circuit-Parameter-1_01.png)
Create a new named [`Parameter`](#qiskit.circuit.Parameter "qiskit.circuit.Parameter").
**Parameters**
* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")) name of the `Parameter`, used for visual representation. This can be any unicode string, e.g. “ϕ”.
* **uuid** (*UUID | None*) For advanced usage only. Override the UUID of this parameter, in order to make it compare equal to some other parameter object. By default, two parameters with the same name do not compare equal to help catch shadowing bugs when two circuits containing the same named parameters are spurious combined. Setting the `uuid` field when creating two parameters to the same thing (along with the same name) allows them to be equal. This is useful during serialization and deserialization.
## Attributes
### name
<Attribute id="qiskit.circuit.Parameter.name">
Returns the name of the [`Parameter`](#qiskit.circuit.Parameter "qiskit.circuit.Parameter").
</Attribute>
### parameters
<Attribute id="qiskit.circuit.Parameter.parameters">
Returns a set of the unbound Parameters in the expression.
</Attribute>
### uuid
<Attribute id="qiskit.circuit.Parameter.uuid">
Returns the [`UUID`](https://docs.python.org/3/library/uuid.html#uuid.UUID "(in Python v3.12)") of the [`Parameter`](#qiskit.circuit.Parameter "qiskit.circuit.Parameter").
In advanced use cases, this property can be passed to the [`Parameter`](#qiskit.circuit.Parameter "qiskit.circuit.Parameter") constructor to produce an instance that compares equal to another instance.
</Attribute>
## Methods
### abs
<Function id="qiskit.circuit.Parameter.abs" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L454-L456" signature="abs()">
Absolute of a ParameterExpression
</Function>
### arccos
<Function id="qiskit.circuit.Parameter.arccos" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L369-L371" signature="arccos()">
Arccos of a ParameterExpression
</Function>
### arcsin
<Function id="qiskit.circuit.Parameter.arcsin" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L365-L367" signature="arcsin()">
Arcsin of a ParameterExpression
</Function>
### arctan
<Function id="qiskit.circuit.Parameter.arctan" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L373-L375" signature="arctan()">
Arctan of a ParameterExpression
</Function>
### assign
<Function id="qiskit.circuit.Parameter.assign" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameter.py#L87-L99" signature="assign(parameter, value)">
Assign one parameter to a value, which can either be numeric or another parameter expression.
**Parameters**
* **parameter** ([*Parameter*](#qiskit.circuit.Parameter "qiskit.circuit.Parameter")) A parameter in this expression whose value will be updated.
* **value** The new value to bind to.
**Returns**
A new expression parameterized by any parameters which were not bound by assignment.
</Function>
### bind
<Function id="qiskit.circuit.Parameter.bind" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L93-L146" signature="bind(parameter_values, allow_unknown_parameters=False)">
Binds the provided set of parameters to their corresponding values.
**Parameters**
* **parameter\_values** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)")) Mapping of Parameter instances to the numeric value to which they will be bound.
* **allow\_unknown\_parameters** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) If `False`, raises an error if `parameter_values` contains Parameters in the keys outside those present in the expression. If `True`, any such parameters are simply ignored.
**Raises**
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError")
* If parameter\_values contains Parameters outside those in self. - If a non-numeric value is passed in parameter\_values.
* [**ZeroDivisionError**](https://docs.python.org/3/library/exceptions.html#ZeroDivisionError "(in Python v3.12)")
* If binding the provided values requires division by zero.
**Returns**
A new expression parameterized by any parameters which were not bound by parameter\_values.
**Return type**
[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.parameterexpression.ParameterExpression")
</Function>
### conjugate
<Function id="qiskit.circuit.Parameter.conjugate" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L70-L75" signature="conjugate()">
Return the conjugate.
**Return type**
[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.parameterexpression.ParameterExpression")
</Function>
### cos
<Function id="qiskit.circuit.Parameter.cos" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L357-L359" signature="cos()">
Cosine of a ParameterExpression
</Function>
### exp
<Function id="qiskit.circuit.Parameter.exp" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L377-L379" signature="exp()">
Exponential of a ParameterExpression
</Function>
### gradient
<Function id="qiskit.circuit.Parameter.gradient" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L279-L313" signature="gradient(param)">
Get the derivative of a parameter expression w\.r.t. a specified parameter expression.
**Parameters**
**param** ([*Parameter*](#qiskit.circuit.Parameter "qiskit.circuit.Parameter")) Parameter w\.r.t. which we want to take the derivative
**Returns**
ParameterExpression representing the gradient of param\_expr w\.r.t. param or complex or float number
**Return type**
[*ParameterExpression*](qiskit.circuit.ParameterExpression "qiskit.circuit.parameterexpression.ParameterExpression") | [complex](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)")
</Function>
### is\_real
<Function id="qiskit.circuit.Parameter.is_real" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L477-L488" signature="is_real()">
Return whether the expression is real
</Function>
### log
<Function id="qiskit.circuit.Parameter.log" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L381-L383" signature="log()">
Logarithm of a ParameterExpression
</Function>
### numeric
<Function id="qiskit.circuit.Parameter.numeric" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L490-L534" signature="numeric()">
Return a Python number representing this object, using the most restrictive of [`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)") and [`complex`](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)") that is valid for this object.
In general, an [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") is only returned if the expression only involved symbolic integers. If floating-point values were used during the evaluation, the return value will be a [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") regardless of whether the represented value is an integer. This is because floating-point values “infect” symbolic computations by their inexact nature, and symbolic libraries will use inexact floating-point semantics not exact real-number semantics when they are involved. If you want to assert that all floating-point calculations *were* carried out at infinite precision (i.e. [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") could represent every intermediate value exactly), you can use [`float.is_integer()`](https://docs.python.org/3/library/stdtypes.html#float.is_integer "(in Python v3.12)") to check if the return float represents an integer and cast it using [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") if so. This would be an unusual pattern; typically one requires this by only ever using explicitly [`Rational`](https://docs.python.org/3/library/numbers.html#numbers.Rational "(in Python v3.12)") objects while working with symbolic expressions.
This is more reliable and performant than using [`is_real()`](#qiskit.circuit.Parameter.is_real "qiskit.circuit.Parameter.is_real") followed by calling [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") or [`complex`](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)"), as in some cases [`is_real()`](#qiskit.circuit.Parameter.is_real "qiskit.circuit.Parameter.is_real") needs to force a floating-point evaluation to determine an accurate result to work around bugs in the upstream symbolic libraries.
**Returns**
A Python number representing the object.
**Raises**
[**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.12)") if there are unbound parameters.
**Return type**
[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)")
</Function>
### sign
<Function id="qiskit.circuit.Parameter.sign" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L385-L387" signature="sign()">
Sign of a ParameterExpression
</Function>
### sin
<Function id="qiskit.circuit.Parameter.sin" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L353-L355" signature="sin()">
Sine of a ParameterExpression
</Function>
### subs
<Function id="qiskit.circuit.Parameter.subs" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameter.py#L101-L110" signature="subs(parameter_map, allow_unknown_parameters=False)">
Substitute self with the corresponding parameter in `parameter_map`.
</Function>
### sympify
<Function id="qiskit.circuit.Parameter.sympify" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L536-L548" signature="sympify()">
Return symbolic expression as a raw Sympy or Symengine object.
Symengine is used preferentially; if both are available, the result will always be a `symengine` object. Symengine is a separate library but has integration with Sympy.
<Admonition title="Note" type="note">
This is for interoperability only. Qiskit will not accept or work with raw Sympy or Symegine expressions in its parameters, because they do not contain the tracking information used in circuit-parameter binding and assignment.
</Admonition>
</Function>
### tan
<Function id="qiskit.circuit.Parameter.tan" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L361-L363" signature="tan()">
Tangent of a ParameterExpression
</Function>
</Class>

View File

@ -0,0 +1,236 @@
---
title: ParameterExpression
description: API reference for qiskit.circuit.ParameterExpression
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.ParameterExpression
---
# ParameterExpression
<Class id="qiskit.circuit.ParameterExpression" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L33-L548" signature="qiskit.circuit.ParameterExpression(symbol_map, expr)" modifiers="class">
Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.12)")
ParameterExpression class to enable creating expressions of Parameters.
Create a new [`ParameterExpression`](#qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression").
Not intended to be called directly, but to be instantiated via operations on other [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") or [`ParameterExpression`](#qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression") objects.
**Parameters**
* **symbol\_map** (*Dict\[*[*Parameter*](qiskit.circuit.Parameter "qiskit.circuit.Parameter")*, \[*[*ParameterExpression*](#qiskit.circuit.ParameterExpression "qiskit.circuit.ParameterExpression")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")*, or* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]]*) Mapping of [`Parameter`](qiskit.circuit.Parameter "qiskit.circuit.Parameter") instances to the `sympy.Symbol` serving as their placeholder in expr.
* **expr** (*sympy.Expr*) Expression of `sympy.Symbol` s.
## Attributes
### parameters
<Attribute id="qiskit.circuit.ParameterExpression.parameters">
Returns a set of the unbound Parameters in the expression.
</Attribute>
## Methods
### abs
<Function id="qiskit.circuit.ParameterExpression.abs" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L454-L456" signature="abs()">
Absolute of a ParameterExpression
</Function>
### arccos
<Function id="qiskit.circuit.ParameterExpression.arccos" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L369-L371" signature="arccos()">
Arccos of a ParameterExpression
</Function>
### arcsin
<Function id="qiskit.circuit.ParameterExpression.arcsin" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L365-L367" signature="arcsin()">
Arcsin of a ParameterExpression
</Function>
### arctan
<Function id="qiskit.circuit.ParameterExpression.arctan" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L373-L375" signature="arctan()">
Arctan of a ParameterExpression
</Function>
### assign
<Function id="qiskit.circuit.ParameterExpression.assign" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L77-L91" signature="assign(parameter, value)">
Assign one parameter to a value, which can either be numeric or another parameter expression.
**Parameters**
* **parameter** ([*Parameter*](qiskit.circuit.Parameter "qiskit.circuit.Parameter")) A parameter in this expression whose value will be updated.
* **value** ([*ParameterExpression*](#qiskit.circuit.ParameterExpression "qiskit.circuit.parameterexpression.ParameterExpression") *|*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)")) The new value to bind to.
**Returns**
A new expression parameterized by any parameters which were not bound by assignment.
**Return type**
[*ParameterExpression*](#qiskit.circuit.ParameterExpression "qiskit.circuit.parameterexpression.ParameterExpression")
</Function>
### bind
<Function id="qiskit.circuit.ParameterExpression.bind" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L93-L146" signature="bind(parameter_values, allow_unknown_parameters=False)">
Binds the provided set of parameters to their corresponding values.
**Parameters**
* **parameter\_values** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)")) Mapping of Parameter instances to the numeric value to which they will be bound.
* **allow\_unknown\_parameters** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) If `False`, raises an error if `parameter_values` contains Parameters in the keys outside those present in the expression. If `True`, any such parameters are simply ignored.
**Raises**
* [**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError")
* If parameter\_values contains Parameters outside those in self. - If a non-numeric value is passed in parameter\_values.
* [**ZeroDivisionError**](https://docs.python.org/3/library/exceptions.html#ZeroDivisionError "(in Python v3.12)")
* If binding the provided values requires division by zero.
**Returns**
A new expression parameterized by any parameters which were not bound by parameter\_values.
**Return type**
[*ParameterExpression*](#qiskit.circuit.ParameterExpression "qiskit.circuit.parameterexpression.ParameterExpression")
</Function>
### conjugate
<Function id="qiskit.circuit.ParameterExpression.conjugate" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L70-L75" signature="conjugate()">
Return the conjugate.
**Return type**
[*ParameterExpression*](#qiskit.circuit.ParameterExpression "qiskit.circuit.parameterexpression.ParameterExpression")
</Function>
### cos
<Function id="qiskit.circuit.ParameterExpression.cos" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L357-L359" signature="cos()">
Cosine of a ParameterExpression
</Function>
### exp
<Function id="qiskit.circuit.ParameterExpression.exp" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L377-L379" signature="exp()">
Exponential of a ParameterExpression
</Function>
### gradient
<Function id="qiskit.circuit.ParameterExpression.gradient" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L279-L313" signature="gradient(param)">
Get the derivative of a parameter expression w\.r.t. a specified parameter expression.
**Parameters**
**param** ([*Parameter*](qiskit.circuit.Parameter "qiskit.circuit.Parameter")) Parameter w\.r.t. which we want to take the derivative
**Returns**
ParameterExpression representing the gradient of param\_expr w\.r.t. param or complex or float number
**Return type**
[*ParameterExpression*](#qiskit.circuit.ParameterExpression "qiskit.circuit.parameterexpression.ParameterExpression") | [complex](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)")
</Function>
### is\_real
<Function id="qiskit.circuit.ParameterExpression.is_real" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L477-L488" signature="is_real()">
Return whether the expression is real
</Function>
### log
<Function id="qiskit.circuit.ParameterExpression.log" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L381-L383" signature="log()">
Logarithm of a ParameterExpression
</Function>
### numeric
<Function id="qiskit.circuit.ParameterExpression.numeric" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L490-L534" signature="numeric()">
Return a Python number representing this object, using the most restrictive of [`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)") and [`complex`](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)") that is valid for this object.
In general, an [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") is only returned if the expression only involved symbolic integers. If floating-point values were used during the evaluation, the return value will be a [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") regardless of whether the represented value is an integer. This is because floating-point values “infect” symbolic computations by their inexact nature, and symbolic libraries will use inexact floating-point semantics not exact real-number semantics when they are involved. If you want to assert that all floating-point calculations *were* carried out at infinite precision (i.e. [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") could represent every intermediate value exactly), you can use [`float.is_integer()`](https://docs.python.org/3/library/stdtypes.html#float.is_integer "(in Python v3.12)") to check if the return float represents an integer and cast it using [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)") if so. This would be an unusual pattern; typically one requires this by only ever using explicitly [`Rational`](https://docs.python.org/3/library/numbers.html#numbers.Rational "(in Python v3.12)") objects while working with symbolic expressions.
This is more reliable and performant than using [`is_real()`](#qiskit.circuit.ParameterExpression.is_real "qiskit.circuit.ParameterExpression.is_real") followed by calling [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.12)") or [`complex`](https://docs.python.org/3/library/functions.html#complex "(in Python v3.12)"), as in some cases [`is_real()`](#qiskit.circuit.ParameterExpression.is_real "qiskit.circuit.ParameterExpression.is_real") needs to force a floating-point evaluation to determine an accurate result to work around bugs in the upstream symbolic libraries.
**Returns**
A Python number representing the object.
**Raises**
[**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.12)") if there are unbound parameters.
**Return type**
[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)")
</Function>
### sign
<Function id="qiskit.circuit.ParameterExpression.sign" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L385-L387" signature="sign()">
Sign of a ParameterExpression
</Function>
### sin
<Function id="qiskit.circuit.ParameterExpression.sin" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L353-L355" signature="sin()">
Sine of a ParameterExpression
</Function>
### subs
<Function id="qiskit.circuit.ParameterExpression.subs" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L148-L196" signature="subs(parameter_map, allow_unknown_parameters=False)">
Returns a new Expression with replacement Parameters.
**Parameters**
* **parameter\_map** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.12)")) Mapping from Parameters in self to the ParameterExpression instances with which they should be replaced.
* **allow\_unknown\_parameters** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) If `False`, raises an error if `parameter_map` contains Parameters in the keys outside those present in the expression. If `True`, any such parameters are simply ignored.
**Raises**
[**CircuitError**](circuit#qiskit.circuit.CircuitError "qiskit.circuit.CircuitError")
* If parameter\_map contains Parameters outside those in self. - If the replacement Parameters in parameter\_map would result in a name conflict in the generated expression.
**Returns**
A new expression with the specified parameters replaced.
**Return type**
[*ParameterExpression*](#qiskit.circuit.ParameterExpression "qiskit.circuit.parameterexpression.ParameterExpression")
</Function>
### sympify
<Function id="qiskit.circuit.ParameterExpression.sympify" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L536-L548" signature="sympify()">
Return symbolic expression as a raw Sympy or Symengine object.
Symengine is used preferentially; if both are available, the result will always be a `symengine` object. Symengine is a separate library but has integration with Sympy.
<Admonition title="Note" type="note">
This is for interoperability only. Qiskit will not accept or work with raw Sympy or Symegine expressions in its parameters, because they do not contain the tracking information used in circuit-parameter binding and assignment.
</Admonition>
</Function>
### tan
<Function id="qiskit.circuit.ParameterExpression.tan" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parameterexpression.py#L361-L363" signature="tan()">
Tangent of a ParameterExpression
</Function>
</Class>

View File

@ -0,0 +1,46 @@
---
title: ParameterVector
description: API reference for qiskit.circuit.ParameterVector
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.ParameterVector
---
# ParameterVector
<Class id="qiskit.circuit.ParameterVector" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parametervector.py#L50-L114" signature="qiskit.circuit.ParameterVector(name, length=0)" modifiers="class">
Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.12)")
ParameterVector class to quickly generate lists of parameters.
## Attributes
### name
<Attribute id="qiskit.circuit.ParameterVector.name">
Returns the name of the ParameterVector.
</Attribute>
### params
<Attribute id="qiskit.circuit.ParameterVector.params">
Returns the list of parameters in the ParameterVector.
</Attribute>
## Methods
### index
<Function id="qiskit.circuit.ParameterVector.index" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parametervector.py#L74-L76" signature="index(value)">
Returns first index of value.
</Function>
### resize
<Function id="qiskit.circuit.ParameterVector.resize" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/parametervector.py#L99-L114" signature="resize(length)">
Resize the parameter vector.
If necessary, new elements are generated. If length is smaller than before, the previous elements are cached and not re-generated if the vector is enlarged again. This is to ensure that the parameter instances do not change.
</Function>
</Class>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,348 @@
---
title: SwitchCaseOp
description: API reference for qiskit.circuit.SwitchCaseOp
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.SwitchCaseOp
---
# SwitchCaseOp
<Class id="qiskit.circuit.SwitchCaseOp" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/switch_case.py#L50-L196" signature="qiskit.circuit.SwitchCaseOp(target, cases, *, label=None)" modifiers="class">
Bases: [`ControlFlowOp`](qiskit.circuit.ControlFlowOp "qiskit.circuit.controlflow.control_flow.ControlFlowOp")
A circuit operation that executes one particular circuit block based on matching a given `target` against an ordered list of `values`. The special value [`CASE_DEFAULT`](circuit#qiskit.circuit.CASE_DEFAULT "qiskit.circuit.CASE_DEFAULT") can be used to represent a default condition.
This is the low-level interface for creating a switch-case statement; in general, the circuit method [`QuantumCircuit.switch()`](qiskit.circuit.QuantumCircuit#switch "qiskit.circuit.QuantumCircuit.switch") should be used as a context manager to access the builder interface. At the low level, you must ensure that all the circuit blocks contain equal numbers of qubits and clbits, and that the order the virtual bits of the containing circuit should be bound is the same for all blocks. This will likely mean that each circuit block is wider than its natural width, as each block must span the union of all the spaces covered by *any* of the blocks.
**Parameters**
* **target** ([*Clbit*](qiskit.circuit.Clbit "qiskit.circuit.Clbit") *|*[*ClassicalRegister*](qiskit.circuit.ClassicalRegister "qiskit.circuit.ClassicalRegister") *|*[*expr.Expr*](circuit_classical#qiskit.circuit.classical.expr.Expr "qiskit.circuit.classical.expr.Expr")) the runtime value to switch on.
* **cases** (*Iterable\[Tuple\[Any,* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")*]]*) an ordered iterable of the corresponding value of the `target` and the circuit block that should be executed if this is matched. There is no fall-through between blocks, and the order matters.
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)")) instructions qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) instructions 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)")) instructions 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.SwitchCaseOp.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.SwitchCaseOp.base_class "qiskit.circuit.SwitchCaseOp.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.SwitchCaseOp.blocks" />
### condition
<Attribute id="qiskit.circuit.SwitchCaseOp.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.SwitchCaseOp.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.SwitchCaseOp.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.SwitchCaseOp.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.SwitchCaseOp.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.SwitchCaseOp.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.SwitchCaseOp.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.SwitchCaseOp.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.SwitchCaseOp.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.SwitchCaseOp.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.SwitchCaseOp.params">
return instruction params.
</Attribute>
### unit
<Attribute id="qiskit.circuit.SwitchCaseOp.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.SwitchCaseOp.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.SwitchCaseOp.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.SwitchCaseOp.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.SwitchCaseOp.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/switch_case.py#L192-L196" 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>
### cases
<Function id="qiskit.circuit.SwitchCaseOp.cases" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/switch_case.py#L170-L180" signature="cases()">
Return a lookup table from case labels to the circuit that would be executed in that case. This object is not generally suitable for creating a new [`SwitchCaseOp`](#qiskit.circuit.SwitchCaseOp "qiskit.circuit.SwitchCaseOp") because any keys that point to the same object will not be grouped.
<Admonition title="See also" type="note">
**[`SwitchCaseOp.cases_specifier()`](#qiskit.circuit.SwitchCaseOp.cases_specifier "qiskit.circuit.SwitchCaseOp.cases_specifier")**
An alternate method that produces its output in a suitable format for creating new [`SwitchCaseOp`](#qiskit.circuit.SwitchCaseOp "qiskit.circuit.SwitchCaseOp") instances.
</Admonition>
</Function>
### cases\_specifier
<Function id="qiskit.circuit.SwitchCaseOp.cases_specifier" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/switch_case.py#L156-L168" signature="cases_specifier()">
Return an iterable where each element is a 2-tuple whose first element is a tuple of jump values, and whose second is the single circuit block that is associated with those values.
This is an abstract specification of the jump table suitable for creating new [`SwitchCaseOp`](#qiskit.circuit.SwitchCaseOp "qiskit.circuit.SwitchCaseOp") instances.
<Admonition title="See also" type="note">
**[`SwitchCaseOp.cases()`](#qiskit.circuit.SwitchCaseOp.cases "qiskit.circuit.SwitchCaseOp.cases")**
Create a lookup table that you can use for your own purposes to jump from values to the circuit that would be executed.
</Admonition>
**Return type**
Iterable\[Tuple\[Tuple, [QuantumCircuit](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")]]
</Function>
### copy
<Function id="qiskit.circuit.SwitchCaseOp.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.SwitchCaseOp.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.SwitchCaseOp.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.SwitchCaseOp.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.SwitchCaseOp.replace_blocks" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/switch_case.py#L186-L190" 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.
**Return type**
[SwitchCaseOp](#qiskit.circuit.SwitchCaseOp "qiskit.circuit.SwitchCaseOp")
</Function>
### reverse\_ops
<Function id="qiskit.circuit.SwitchCaseOp.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.SwitchCaseOp.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.SwitchCaseOp.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.SwitchCaseOp.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>

View File

@ -0,0 +1,327 @@
---
title: WhileLoopOp
description: API reference for qiskit.circuit.WhileLoopOp
in_page_toc_min_heading_level: 1
python_api_type: class
python_api_name: qiskit.circuit.WhileLoopOp
---
# WhileLoopOp
<Class id="qiskit.circuit.WhileLoopOp" isDedicatedPage={true} github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/while_loop.py#L29-L111" signature="qiskit.circuit.WhileLoopOp(condition, 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`) until a condition (`condition`) evaluates as False.
**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 checked prior to executing `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`.
* **body** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit "qiskit.circuit.QuantumCircuit")) The loop body to be repeatedly executed.
* **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)") *| None*) An optional label for identifying the instruction.
The classical bits used in `condition` must be a subset of those attached to `body`.
**Circuit symbol:**
```python
┌─────────────┐
q_0: ┤0 ├
│ │
q_1: ┤1 ├
│ while_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)")) instructions qubit width
* **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) instructions 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)")) instructions 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.WhileLoopOp.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.WhileLoopOp.base_class "qiskit.circuit.WhileLoopOp.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.WhileLoopOp.blocks" />
### condition
<Attribute id="qiskit.circuit.WhileLoopOp.condition">
The classical condition on the instruction.
</Attribute>
### condition\_bits
<Attribute id="qiskit.circuit.WhileLoopOp.condition_bits">
Get Clbits in condition.
</Attribute>
### decompositions
<Attribute id="qiskit.circuit.WhileLoopOp.decompositions">
Get the decompositions of the instruction from the SessionEquivalenceLibrary.
</Attribute>
### definition
<Attribute id="qiskit.circuit.WhileLoopOp.definition">
Return definition in terms of other basic gates.
</Attribute>
### duration
<Attribute id="qiskit.circuit.WhileLoopOp.duration">
Get the duration.
</Attribute>
### label
<Attribute id="qiskit.circuit.WhileLoopOp.label">
Return instruction label
</Attribute>
### mutable
<Attribute id="qiskit.circuit.WhileLoopOp.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.WhileLoopOp.name">
Return the name.
</Attribute>
### num\_clbits
<Attribute id="qiskit.circuit.WhileLoopOp.num_clbits">
Return the number of clbits.
</Attribute>
### num\_qubits
<Attribute id="qiskit.circuit.WhileLoopOp.num_qubits">
Return the number of qubits.
</Attribute>
### params
<Attribute id="qiskit.circuit.WhileLoopOp.params" />
### unit
<Attribute id="qiskit.circuit.WhileLoopOp.unit">
Get the time unit of duration.
</Attribute>
## Methods
### add\_decomposition
<Function id="qiskit.circuit.WhileLoopOp.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.WhileLoopOp.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.WhileLoopOp.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.WhileLoopOp.c_if" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/while_loop.py#L107-L111" 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.WhileLoopOp.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.WhileLoopOp.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.WhileLoopOp.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.WhileLoopOp.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.WhileLoopOp.replace_blocks" github="https://github.com/Qiskit/qiskit/tree/stable/1.0/qiskit/circuit/controlflow/while_loop.py#L103-L105" 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.WhileLoopOp.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.WhileLoopOp.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.WhileLoopOp.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.WhileLoopOp.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>

View File

@ -0,0 +1,436 @@
---
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>

View File

@ -0,0 +1,491 @@
---
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 tweedledums 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>

View File

@ -0,0 +1,18 @@
---
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>

View File

@ -0,0 +1,18 @@
---
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>

View File

@ -0,0 +1,206 @@
---
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:
![../\_images/qiskit-circuit-library-AND-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-AND-1.png)
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]`.
![../\_images/qiskit-circuit-library-AND-2.png](/images/api/qiskit/1.0/qiskit-circuit-library-AND-2.png)
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>

View File

@ -0,0 +1,162 @@
---
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>

View File

@ -0,0 +1,194 @@
---
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>

View File

@ -0,0 +1,198 @@
---
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>

View File

@ -0,0 +1,250 @@
---
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 Qiskits 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>

View File

@ -0,0 +1,204 @@
---
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>

View File

@ -0,0 +1,262 @@
---
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 doesnt 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 doesnt 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>

View File

@ -0,0 +1,207 @@
---
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 Qiskits 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>

View File

@ -0,0 +1,215 @@
---
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>

View File

@ -0,0 +1,221 @@
---
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 Qiskits 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>

View File

@ -0,0 +1,223 @@
---
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 Qiskits 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>

View File

@ -0,0 +1,223 @@
---
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 Qiskits 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>

View File

@ -0,0 +1,201 @@
---
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>

View File

@ -0,0 +1,197 @@
---
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 Qiskits 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>

View File

@ -0,0 +1,201 @@
---
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>

View File

@ -0,0 +1,238 @@
---
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 Qiskits 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>

View File

@ -0,0 +1,219 @@
---
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>

Some files were not shown because too many files have changed in this diff Show More