text,source "--- title: assembler description: API reference for qiskit.assembler in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.assembler --- # Circuit and Schedule Assembler `qiskit.assembler` ## Circuit Assembler ### assemble\_circuits 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)) ``` ## Schedule Assembler ### assemble\_schedules 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) ``` ## Disassembler ### disassemble Disassemble a qobj and return the circuits or pulse schedules, run\_config, and user header. `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. **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) ``` ## RunConfig | | | | -------------------------------------------------------------------------------------------------------------- | ---------------------------- | | [`RunConfig`](qiskit.assembler.RunConfig ""qiskit.assembler.RunConfig"")(\[shots, seed\_simulator, memory, ...]) | Class for Run Configuration. | ",repo/docs/api/qiskit/1.0\assembler.mdx "--- title: circuit description: API reference for qiskit.circuit in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.circuit --- # Quantum Circuits `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 ``` 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. It is also straightforward to get the number and type of the gates in a circuit using [`QuantumCircuit.count_ops()`](qiskit.circuit.QuantumCircuit#count_ops ""qiskit.circuit.QuantumCircuit.count_ops""): ```python qc.count_ops() ``` ```python OrderedDict([('cx', 8), ('h', 5), ('x', 3), ('swap', 3)]) ``` We can also get just the raw count of operations by computing the circuits [`QuantumCircuit.size()`](qiskit.circuit.QuantumCircuit#size ""qiskit.circuit.QuantumCircuit.size""): ```python qc.size() ``` ```python 19 ``` A particularly important circuit property is known as the circuit **depth**. The depth of a quantum circuit is a measure of how many “layers” of quantum gates, executed in parallel, it takes to complete the computation defined by the circuit. Because quantum gates take time to implement, the depth of a circuit roughly corresponds to the amount of time it takes the quantum computer to execute the circuit. Thus, the depth of a circuit is one important quantity used to measure if a quantum circuit can be run on a device. The depth of a quantum circuit has a mathematical definition as the longest path in a directed acyclic graph (DAG). However, such a definition is a bit hard to grasp, even for experts. Fortunately, the depth of a circuit can be easily understood by anyone familiar with playing [Tetris](https://en.wikipedia.org/wiki/Tetris). Lets see how to compute this graphically: ![../\_images/depth.gif](/images/api/qiskit/1.0/depth.gif) We can verify our graphical result using [`QuantumCircuit.depth()`](qiskit.circuit.QuantumCircuit#depth ""qiskit.circuit.QuantumCircuit.depth""): ```python qc.depth() ``` ```python 9 ``` ## Quantum Circuit API ### Quantum Circuit Construction | | | | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")(\*regs\[, name, global\_phase, ...]) | Create a new circuit. | | [`QuantumRegister`](qiskit.circuit.QuantumRegister ""qiskit.circuit.QuantumRegister"")(\[size, name, bits]) | Implement a quantum register. | | [`Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")(\[register, index]) | Implement a quantum bit. | | [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"")(\[size, name, bits]) | Implement a classical register. | | [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")(\[register, index]) | Implement a classical bit. | | [`AncillaRegister`](qiskit.circuit.AncillaRegister ""qiskit.circuit.AncillaRegister"")(\[size, name, bits]) | Implement an ancilla register. | | [`AncillaQubit`](qiskit.circuit.AncillaQubit ""qiskit.circuit.AncillaQubit"")(\[register, index]) | A qubit used as ancillary qubit. | | [`CircuitInstruction`](qiskit.circuit.CircuitInstruction ""qiskit.circuit.CircuitInstruction"") | A single instruction in a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""), comprised of the `operation` and various operands. | | [`Register`](qiskit.circuit.Register ""qiskit.circuit.Register"")(\[size, name, bits]) | Implement a generic register. | | [`Bit`](qiskit.circuit.Bit ""qiskit.circuit.Bit"")(\[register, index]) | Implement a generic bit. | ### Gates and Instructions | | | | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"")(name, num\_qubits, params\[, label, ...]) | Unitary gate. | | [`ControlledGate`](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"")(name, num\_qubits, params\[, ...]) | Controlled unitary gate. | | [`Delay`](qiskit.circuit.Delay ""qiskit.circuit.Delay"")(duration\[, unit]) | Do nothing and just delay/wait/idle for a specified duration. | | [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")(name, num\_qubits, num\_clbits, params) | Generic quantum instruction. | | [`InstructionSet`](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"")(\*\[, resource\_requester]) | Instruction collection, and their contexts. | | [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation"")() | Quantum Operation Interface Class. | | [`EquivalenceLibrary`](qiskit.circuit.EquivalenceLibrary ""qiskit.circuit.EquivalenceLibrary"")(\*\[, base]) | A library providing a one-way mapping of Gates to their equivalent implementations as QuantumCircuits. | ### Annotated Operations | | | | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"")(base\_op, modifiers) | Annotated operation. | | [`InverseModifier`](qiskit.circuit.InverseModifier ""qiskit.circuit.InverseModifier"")() | Inverse modifier: specifies that the operation is inverted. | | [`ControlModifier`](qiskit.circuit.ControlModifier ""qiskit.circuit.ControlModifier"")(\[num\_ctrl\_qubits, ctrl\_state]) | Control modifier: specifies that the operation is controlled by `num_ctrl_qubits` and has control state `ctrl_state`. | | [`PowerModifier`](qiskit.circuit.PowerModifier ""qiskit.circuit.PowerModifier"")(power) | Power modifier: specifies that the operation is raised to the power `power`. | ### Control Flow Operations | | | | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`ControlFlowOp`](qiskit.circuit.ControlFlowOp ""qiskit.circuit.ControlFlowOp"")(name, num\_qubits, num\_clbits, ...) | Abstract class to encapsulate all control flow operations. | | [`IfElseOp`](qiskit.circuit.IfElseOp ""qiskit.circuit.IfElseOp"")(condition, true\_body\[, false\_body, ...]) | A circuit operation which executes a program (`true_body`) if a provided condition (`condition`) evaluates to true, and optionally evaluates another program (`false_body`) otherwise. | | [`WhileLoopOp`](qiskit.circuit.WhileLoopOp ""qiskit.circuit.WhileLoopOp"")(condition, body\[, label]) | A circuit operation which repeatedly executes a subcircuit (`body`) until a condition (`condition`) evaluates as False. | | [`ForLoopOp`](qiskit.circuit.ForLoopOp ""qiskit.circuit.ForLoopOp"")(indexset, loop\_parameter, body\[, ...]) | A circuit operation which repeatedly executes a subcircuit (`body`) parameterized by a parameter `loop_parameter` through the set of integer values provided in `indexset`. | | [`SwitchCaseOp`](qiskit.circuit.SwitchCaseOp ""qiskit.circuit.SwitchCaseOp"")(target, cases, \*\[, label]) | A circuit operation that executes one particular circuit block based on matching a given `target` against an ordered list of `values`. | | [`BreakLoopOp`](qiskit.circuit.BreakLoopOp ""qiskit.circuit.BreakLoopOp"")(num\_qubits, num\_clbits\[, label]) | A circuit operation which, when encountered, jumps to the end of the nearest enclosing loop. | | [`ContinueLoopOp`](qiskit.circuit.ContinueLoopOp ""qiskit.circuit.ContinueLoopOp"")(num\_qubits, num\_clbits\[, label]) | A circuit operation which, when encountered, moves to the next iteration of the nearest enclosing loop. | The [`SwitchCaseOp`](qiskit.circuit.SwitchCaseOp ""qiskit.circuit.SwitchCaseOp"") also understands a special value: **qiskit.circuit.CASE\_DEFAULT** A special object that represents the “default” case of a switch statement. If you use this as a case target, it must be the last case, and will match anything that wasn’t already matched. For example: ```python from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import SwitchCaseOp, CASE_DEFAULT body0 = QuantumCircuit(2, 2) body0.x(0) body1 = QuantumCircuit(2, 2) body1.z(0) body2 = QuantumCircuit(2, 2) body2.cx(0, 1) qr, cr = QuantumRegister(2), ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.switch(cr, [(0, body0), (1, body1), (CASE_DEFAULT, body2)], qr, cr) ``` When using the builder interface of [`QuantumCircuit.switch()`](qiskit.circuit.QuantumCircuit#switch ""qiskit.circuit.QuantumCircuit.switch""), this can also be accessed as the `DEFAULT` attribute of the bound case-builder object, such as: ```python from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qr, cr = QuantumRegister(2), ClassicalRegister(2) qc = QuantumCircuit(qr, cr) with qc.switch(cr) as case: with case(0): qc.x(0) with case(1): qc.z(0) with case(case.DEFAULT): qc.cx(0, 1) ``` ### Parametric Quantum Circuits | | | | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")(name, \*\[, uuid]) | Parameter Class for variable parameters. | | [`ParameterVector`](qiskit.circuit.ParameterVector ""qiskit.circuit.ParameterVector"")(name\[, length]) | ParameterVector class to quickly generate lists of parameters. | | [`ParameterExpression`](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")(symbol\_map, expr) | ParameterExpression class to enable creating expressions of Parameters. | ### Gate Commutation | | | | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | [`CommutationChecker`](qiskit.circuit.CommutationChecker ""qiskit.circuit.CommutationChecker"")(\[...]) | This code is essentially copy-pasted from commutative\_analysis.py. | ### Random Circuits #### random\_circuit 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 ### 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 Base class for errors raised while processing a circuit. Set the error message. ",repo/docs/api/qiskit/1.0\circuit.mdx "--- title: classical description: API reference for qiskit.circuit.classical in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.circuit.classical --- # Classical expressions `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"")). 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. ## Expressions `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). ### Representation The expression system is based on tree representation. All nodes in the tree are final (uninheritable) instances of the abstract base class: #### Expr 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. 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 A classical variable. Variables are immutable after construction, so they can be used as dictionary keys. 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 A single scalar value. 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 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 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 Bitwise negation. `~operand`. ###### LOGIC\_NOT Logical negation. `!operand`. #### Binary 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 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 Bitwise “and”. `lhs & rhs`. ###### BIT\_OR Bitwise “or”. `lhs | rhs`. ###### BIT\_XOR Bitwise “exclusive or”. `lhs ^ rhs`. ###### LOGIC\_AND Logical “and”. `lhs && rhs`. ###### LOGIC\_OR Logical “or”. `lhs || rhs`. ###### EQUAL Numeric equality. `lhs == rhs`. ###### NOT\_EQUAL Numeric inequality. `lhs != rhs`. ###### LESS Numeric less than. `lhs < rhs`. ###### LESS\_EQUAL Numeric less than or equal to. `lhs <= rhs` ###### GREATER Numeric greater than. `lhs > rhs`. ###### GREATER\_EQUAL Numeric greater than or equal to. `lhs >= rhs`. 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 A cast from one type to another, implied by the use of an expression in a different context. ### 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 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(, 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"") 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 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"") There are helper constructor functions for each of the unary operations. #### bit\_not 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"") #### logic\_not 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"") Similarly, the binary operations and relations have helper functions defined. #### bit\_and 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"") #### bit\_or 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"") #### bit\_xor 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"") #### logic\_and 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(, Bool()), Var(, Bool()), Bool()) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.expr.Expr"") #### logic\_or 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(, Bool()), Var(, Bool()), Bool()) ``` **Return type** [*Expr*](#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.expr.Expr"") #### equal 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"") #### not\_equal 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"") #### less 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"") #### less\_equal 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"") #### greater 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"") #### greater\_equal 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"") Qiskit’s legacy method for specifying equality conditions for use in conditionals is to use a two-tuple of a [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"") or [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"") and an integer. This represents an exact equality condition, and there are no ways to specify any other relations. The helper function [`lift_legacy_condition()`](#qiskit.circuit.classical.expr.lift_legacy_condition ""qiskit.circuit.classical.expr.lift_legacy_condition"") converts this legacy format into the new expression syntax. #### lift\_legacy\_condition 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"") ### 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 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 **Return type** *\_T\_co* ##### visit\_cast **Return type** *\_T\_co* ##### visit\_generic **Return type** *\_T\_co* ##### visit\_unary **Return type** *\_T\_co* ##### visit\_value **Return type** *\_T\_co* ##### visit\_var **Return type** *\_T\_co* 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 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"")] 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 Do these two expressions have exactly the same tree structure, up to some key function for the [`Var`](#qiskit.circuit.classical.expr.Var ""qiskit.circuit.classical.expr.expr.Var"") objects? In other words, are these two expressions the exact same trees, except we compare the `Var.var` fields by calling the appropriate `*_var_key` function on them, and comparing that output for equality. This function does not allow any semantic “equivalences” such as asserting that `a == b` is equivalent to `b == a`; the evaluation order of the operands could, in general, cause such a statement to be false (consider hypothetical `extern` functions that access global state). There’s no requirements on the key functions, except that their outputs should have general `__eq__` methods. If a key function returns `None`, the variable will be used verbatim instead. **Parameters** * **left** ([*expr.Expr*](#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.expr.Expr"")) – one of the [`Expr`](#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.expr.Expr"") nodes. * **right** ([*expr.Expr*](#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.expr.Expr"")) – the other [`Expr`](#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.expr.Expr"") node. * **left\_var\_key** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[*[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")*],* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")*] | None*) – a callable whose output should be used when comparing `Var.var` attributes. If this argument is `None` or its output is `None` for a given variable in `left`, the variable will be used verbatim. * **right\_var\_key** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[*[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")*],* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")*] | None*) – same as `left_var_key`, but used on the variables in `right` instead. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") **Examples** Comparing two expressions for structural equivalence, with no remapping of the variables. These are different because the different [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"") instances compare differently: ```python >>> from qiskit.circuit import Clbit >>> from qiskit.circuit.classical import expr >>> left_bits = [Clbit(), Clbit()] >>> right_bits = [Clbit(), Clbit()] >>> left = expr.logic_and(expr.logic_not(left_bits[0]), left_bits[1]) >>> right = expr.logic_and(expr.logic_not(right_bits[0]), right_bits[1]) >>> expr.structurally_equivalent(left, right) False ``` Comparing the same two expressions, but this time using mapping functions that associate the bits with simple indices: ```python >>> left_key = {var: i for i, var in enumerate(left_bits)}.get >>> right_key = {var: i for i, var in enumerate(right_bits)}.get >>> expr.structurally_equivalent(left, right, left_key, right_key) True ``` ## Typing `qiskit.circuit.classical.types` ### 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 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. Types should be considered immutable objects, and you must not mutate them. It is permissible to reuse a [`Type`](#qiskit.circuit.classical.types.Type ""qiskit.circuit.classical.types.Type"") that you take from another object without copying it, and generally this will be the best approach for performance. [`Type`](#qiskit.circuit.classical.types.Type ""qiskit.circuit.classical.types.Type"") objects are designed to be small amounts of data, and it’s best to point to the same instance of the data where possible rather than heap-allocating a new version of the same thing. Where possible, the class constructors will return singleton instances to facilitate this. The two different types available are for Booleans (corresponding to [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"") and the literals `True` and `False`), and unsigned integers (corresponding to [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"") and Python integers). #### Bool The Boolean type. This has exactly two values: `True` and `False`. #### Uint An unsigned integer of fixed bit width. 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 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"") 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 Enumeration listing the possible relations between two types. Types only have a partial ordering, so it’s possible for two types to have no sub-typing relationship. Note that the sub-/supertyping relationship is not the same as whether a type can be explicitly cast from one to another. 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 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)"") ##### is\_supertype 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)"") ##### greater 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) ``` #### 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 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()) >>> types.cast_kind(types.Uint(8), types.Bool()) >>> types.cast_kind(types.Bool(), types.Uint(8)) >>> types.cast_kind(types.Uint(16), types.Uint(8)) ``` **Return type** [*CastKind*](#qiskit.circuit.classical.types.CastKind ""qiskit.circuit.classical.types.ordering.CastKind"") 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 A return value indicating the type of cast that can occur from one type to another. ",repo/docs/api/qiskit/1.0\circuit_classical.mdx "--- title: library description: API reference for qiskit.circuit.library in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.circuit.library --- # Circuit Library `qiskit.circuit.library` The circuit library is a collection of well-studied and valuable circuits, directives, and gates. We call them valuable for different reasons, for instance they can serve as building blocks for algorithms or they are circuits that we think are hard to simulate classically. Each element can be plugged into a circuit using the [`QuantumCircuit.append()`](qiskit.circuit.QuantumCircuit#append ""qiskit.circuit.QuantumCircuit.append"") method and so the circuit library allows users to program at higher levels of abstraction. For example, to append a multi-controlled CNOT: ```python from qiskit.circuit.library import MCXGate gate = MCXGate(4) from qiskit import QuantumCircuit circuit = QuantumCircuit(5) circuit.append(gate, [0, 1, 4, 2, 3]) circuit.draw('mpl') ``` ![../\_images/circuit\_library-1.png](/images/api/qiskit/1.0/circuit_library-1.png) The library is organized in several sections. ## Standard gates These operations are reversible unitary gates and they all subclass [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). As a consequence, they all have the methods [`to_matrix()`](qiskit.circuit.Gate#to_matrix ""qiskit.circuit.Gate.to_matrix""), [`power()`](qiskit.circuit.Gate#power ""qiskit.circuit.Gate.power""), and [`control()`](qiskit.circuit.Gate#control ""qiskit.circuit.Gate.control""), which we can generally only apply to unitary operations. For example: ```python from qiskit.circuit.library import XGate gate = XGate() print(gate.to_matrix()) # X gate print(gate.power(1/2).to_matrix()) # √X gate print(gate.control(1).to_matrix()) # CX (controlled X) gate ``` ```python [[0.+0.j 1.+0.j] [1.+0.j 0.+0.j]] [[0.5+0.5j 0.5-0.5j] [0.5-0.5j 0.5+0.5j]] [[1.+0.j 0.+0.j 0.+0.j 0.+0.j] [0.+0.j 0.+0.j 0.+0.j 1.+0.j] [0.+0.j 0.+0.j 1.+0.j 0.+0.j] [0.+0.j 1.+0.j 0.+0.j 0.+0.j]] ``` | | | | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | [`C3XGate`](qiskit.circuit.library.C3XGate ""qiskit.circuit.library.C3XGate"")(\*args\[, \_force\_mutable]) | The X gate controlled on 3 qubits. | | [`C3SXGate`](qiskit.circuit.library.C3SXGate ""qiskit.circuit.library.C3SXGate"")(\*args\[, \_force\_mutable]) | The 3-qubit controlled sqrt-X gate. | | [`C4XGate`](qiskit.circuit.library.C4XGate ""qiskit.circuit.library.C4XGate"")(\*args\[, \_force\_mutable]) | The 4-qubit controlled X gate. | | [`CCXGate`](qiskit.circuit.library.CCXGate ""qiskit.circuit.library.CCXGate"")(\*args\[, \_force\_mutable]) | CCX gate, also known as Toffoli gate. | | [`DCXGate`](qiskit.circuit.library.DCXGate ""qiskit.circuit.library.DCXGate"")(\*args\[, \_force\_mutable]) | Double-CNOT gate. | | [`CHGate`](qiskit.circuit.library.CHGate ""qiskit.circuit.library.CHGate"")(\*args\[, \_force\_mutable]) | Controlled-Hadamard gate. | | [`CPhaseGate`](qiskit.circuit.library.CPhaseGate ""qiskit.circuit.library.CPhaseGate"")(theta\[, label, ctrl\_state, ...]) | Controlled-Phase gate. | | [`CRXGate`](qiskit.circuit.library.CRXGate ""qiskit.circuit.library.CRXGate"")(theta\[, label, ctrl\_state, ...]) | Controlled-RX gate. | | [`CRYGate`](qiskit.circuit.library.CRYGate ""qiskit.circuit.library.CRYGate"")(theta\[, label, ctrl\_state, ...]) | Controlled-RY gate. | | [`CRZGate`](qiskit.circuit.library.CRZGate ""qiskit.circuit.library.CRZGate"")(theta\[, label, ctrl\_state, ...]) | Controlled-RZ gate. | | [`CSGate`](qiskit.circuit.library.CSGate ""qiskit.circuit.library.CSGate"")(\*args\[, \_force\_mutable]) | Controlled-S gate. | | [`CSdgGate`](qiskit.circuit.library.CSdgGate ""qiskit.circuit.library.CSdgGate"")(\*args\[, \_force\_mutable]) | Controlled-S^dagger gate. | | [`CSwapGate`](qiskit.circuit.library.CSwapGate ""qiskit.circuit.library.CSwapGate"")(\*args\[, \_force\_mutable]) | Controlled-SWAP gate, also known as the Fredkin gate. | | [`CSXGate`](qiskit.circuit.library.CSXGate ""qiskit.circuit.library.CSXGate"")(\*args\[, \_force\_mutable]) | Controlled-√X gate. | | [`CUGate`](qiskit.circuit.library.CUGate ""qiskit.circuit.library.CUGate"")(theta, phi, lam, gamma\[, label, ...]) | Controlled-U gate (4-parameter two-qubit gate). | | [`CU1Gate`](qiskit.circuit.library.CU1Gate ""qiskit.circuit.library.CU1Gate"")(theta\[, label, ctrl\_state, ...]) | Controlled-U1 gate. | | [`CU3Gate`](qiskit.circuit.library.CU3Gate ""qiskit.circuit.library.CU3Gate"")(theta, phi, lam\[, label, ...]) | Controlled-U3 gate (3-parameter two-qubit gate). | | [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"")(\*args\[, \_force\_mutable]) | Controlled-X gate. | | [`CYGate`](qiskit.circuit.library.CYGate ""qiskit.circuit.library.CYGate"")(\*args\[, \_force\_mutable]) | Controlled-Y gate. | | [`CZGate`](qiskit.circuit.library.CZGate ""qiskit.circuit.library.CZGate"")(\*args\[, \_force\_mutable]) | Controlled-Z gate. | | [`CCZGate`](qiskit.circuit.library.CCZGate ""qiskit.circuit.library.CCZGate"")(\*args\[, \_force\_mutable]) | CCZ gate. | | [`ECRGate`](qiskit.circuit.library.ECRGate ""qiskit.circuit.library.ECRGate"")(\*args\[, \_force\_mutable]) | An echoed cross-resonance gate. | | [`HGate`](qiskit.circuit.library.HGate ""qiskit.circuit.library.HGate"")(\*args\[, \_force\_mutable]) | Single-qubit Hadamard gate. | | [`IGate`](qiskit.circuit.library.IGate ""qiskit.circuit.library.IGate"")(\*args\[, \_force\_mutable]) | Identity gate. | | [`MSGate`](qiskit.circuit.library.MSGate ""qiskit.circuit.library.MSGate"")(num\_qubits, theta\[, label]) | MSGate has been deprecated. | | [`PhaseGate`](qiskit.circuit.library.PhaseGate ""qiskit.circuit.library.PhaseGate"")(theta\[, label, duration, unit]) | Single-qubit rotation about the Z axis. | | [`RCCXGate`](qiskit.circuit.library.RCCXGate ""qiskit.circuit.library.RCCXGate"")(\*args\[, \_force\_mutable]) | The simplified Toffoli gate, also referred to as Margolus gate. | | [`RC3XGate`](qiskit.circuit.library.RC3XGate ""qiskit.circuit.library.RC3XGate"")(\*args\[, \_force\_mutable]) | The simplified 3-controlled Toffoli gate. | | [`RGate`](qiskit.circuit.library.RGate ""qiskit.circuit.library.RGate"")(theta, phi\[, label, duration, unit]) | Rotation θ around the cos(φ)x + sin(φ)y axis. | | [`RXGate`](qiskit.circuit.library.RXGate ""qiskit.circuit.library.RXGate"")(theta\[, label, duration, unit]) | Single-qubit rotation about the X axis. | | [`RXXGate`](qiskit.circuit.library.RXXGate ""qiskit.circuit.library.RXXGate"")(theta\[, label, duration, unit]) | A parametric 2-qubit $X \otimes X$ interaction (rotation about XX). | | [`RYGate`](qiskit.circuit.library.RYGate ""qiskit.circuit.library.RYGate"")(theta\[, label, duration, unit]) | Single-qubit rotation about the Y axis. | | [`RYYGate`](qiskit.circuit.library.RYYGate ""qiskit.circuit.library.RYYGate"")(theta\[, label, duration, unit]) | A parametric 2-qubit $Y \otimes Y$ interaction (rotation about YY). | | [`RZGate`](qiskit.circuit.library.RZGate ""qiskit.circuit.library.RZGate"")(phi\[, label, duration, unit]) | Single-qubit rotation about the Z axis. | | [`RZZGate`](qiskit.circuit.library.RZZGate ""qiskit.circuit.library.RZZGate"")(theta\[, label, duration, unit]) | A parametric 2-qubit $Z \otimes Z$ interaction (rotation about ZZ). | | [`RZXGate`](qiskit.circuit.library.RZXGate ""qiskit.circuit.library.RZXGate"")(theta\[, label, duration, unit]) | A parametric 2-qubit $Z \otimes X$ interaction (rotation about ZX). | | [`XXMinusYYGate`](qiskit.circuit.library.XXMinusYYGate ""qiskit.circuit.library.XXMinusYYGate"")(theta\[, beta, label, ...]) | XX-YY interaction gate. | | [`XXPlusYYGate`](qiskit.circuit.library.XXPlusYYGate ""qiskit.circuit.library.XXPlusYYGate"")(theta\[, beta, label, duration, ...]) | XX+YY interaction gate. | | [`SGate`](qiskit.circuit.library.SGate ""qiskit.circuit.library.SGate"")(\*args\[, \_force\_mutable]) | Single qubit S gate (Z\*\*0.5). | | [`SdgGate`](qiskit.circuit.library.SdgGate ""qiskit.circuit.library.SdgGate"")(\*args\[, \_force\_mutable]) | Single qubit S-adjoint gate (\~Z\*\*0.5). | | [`SwapGate`](qiskit.circuit.library.SwapGate ""qiskit.circuit.library.SwapGate"")(\*args\[, \_force\_mutable]) | The SWAP gate. | | [`iSwapGate`](qiskit.circuit.library.iSwapGate ""qiskit.circuit.library.iSwapGate"")(\*args\[, \_force\_mutable]) | iSWAP gate. | | [`SXGate`](qiskit.circuit.library.SXGate ""qiskit.circuit.library.SXGate"")(\*args\[, \_force\_mutable]) | The single-qubit Sqrt(X) gate ($\sqrt{X}$). | | [`SXdgGate`](qiskit.circuit.library.SXdgGate ""qiskit.circuit.library.SXdgGate"")(\*args\[, \_force\_mutable]) | The inverse single-qubit Sqrt(X) gate. | | [`TGate`](qiskit.circuit.library.TGate ""qiskit.circuit.library.TGate"")(\*args\[, \_force\_mutable]) | Single qubit T gate (Z\*\*0.25). | | [`TdgGate`](qiskit.circuit.library.TdgGate ""qiskit.circuit.library.TdgGate"")(\*args\[, \_force\_mutable]) | Single qubit T-adjoint gate (\~Z\*\*0.25). | | [`UGate`](qiskit.circuit.library.UGate ""qiskit.circuit.library.UGate"")(theta, phi, lam\[, label, duration, unit]) | Generic single-qubit rotation gate with 3 Euler angles. | | [`U1Gate`](qiskit.circuit.library.U1Gate ""qiskit.circuit.library.U1Gate"")(theta\[, label, duration, unit]) | Single-qubit rotation about the Z axis. | | [`U2Gate`](qiskit.circuit.library.U2Gate ""qiskit.circuit.library.U2Gate"")(phi, lam\[, label, duration, unit]) | Single-qubit rotation about the X+Z axis. | | [`U3Gate`](qiskit.circuit.library.U3Gate ""qiskit.circuit.library.U3Gate"")(theta, phi, lam\[, label, duration, unit]) | Generic single-qubit rotation gate with 3 Euler angles. | | [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate"")(\*args\[, \_force\_mutable]) | The single-qubit Pauli-X gate ($\sigma_x$). | | [`YGate`](qiskit.circuit.library.YGate ""qiskit.circuit.library.YGate"")(\*args\[, \_force\_mutable]) | The single-qubit Pauli-Y gate ($\sigma_y$). | | [`ZGate`](qiskit.circuit.library.ZGate ""qiskit.circuit.library.ZGate"")(\*args\[, \_force\_mutable]) | The single-qubit Pauli-Z gate ($\sigma_z$). | | [`GlobalPhaseGate`](qiskit.circuit.library.GlobalPhaseGate ""qiskit.circuit.library.GlobalPhaseGate"")(phase\[, label, duration, unit]) | The global phase gate ($e^{i\theta}$). | ## Standard Directives Directives are operations to the quantum stack that are meant to be interpreted by the backend or the transpiler. In general, the transpiler or backend might optionally ignore them if there is no implementation for them. | | | | --------------------------------------------------------------------------------------------------- | -------------------- | | [`Barrier`](qiskit.circuit.library.Barrier ""qiskit.circuit.library.Barrier"")(num\_qubits\[, label]) | Barrier instruction. | ## Standard Operations Operations are non-reversible changes in the quantum state of the circuit. | | | | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | | [`Measure`](qiskit.circuit.library.Measure ""qiskit.circuit.library.Measure"")(\*args\[, \_force\_mutable]) | Quantum measurement in the computational basis. | | [`Reset`](qiskit.circuit.library.Reset ""qiskit.circuit.library.Reset"")(\*args\[, \_force\_mutable]) | Qubit reset. | ## Generalized Gates These “gates” (many are [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") subclasses) allow to set the amount of qubits involved at instantiation time. ```python from qiskit.circuit.library import Diagonal diagonal = Diagonal([1, 1]) print(diagonal.num_qubits) diagonal = Diagonal([1, 1, 1, 1]) print(diagonal.num_qubits) ``` ```python 1 2 ``` | | | | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | [`Diagonal`](qiskit.circuit.library.Diagonal ""qiskit.circuit.library.Diagonal"")(diag) | Diagonal circuit. | | [`DiagonalGate`](qiskit.circuit.library.DiagonalGate ""qiskit.circuit.library.DiagonalGate"")(diag) | Gate implementing a diagonal transformation. | | [`MCMT`](qiskit.circuit.library.MCMT ""qiskit.circuit.library.MCMT"")(gate, num\_ctrl\_qubits, num\_target\_qubits) | The multi-controlled multi-target gate, for an arbitrary singly controlled target gate. | | [`MCMTVChain`](qiskit.circuit.library.MCMTVChain ""qiskit.circuit.library.MCMTVChain"")(gate, num\_ctrl\_qubits, ...) | The MCMT implementation using the CCX V-chain. | | [`Permutation`](qiskit.circuit.library.Permutation ""qiskit.circuit.library.Permutation"")(num\_qubits\[, pattern, seed]) | An n\_qubit circuit that permutes qubits. | | [`PermutationGate`](qiskit.circuit.library.PermutationGate ""qiskit.circuit.library.PermutationGate"")(pattern) | A gate that permutes qubits. | | [`GMS`](qiskit.circuit.library.GMS ""qiskit.circuit.library.GMS"")(num\_qubits, theta) | Global Mølmer–Sørensen gate. | | [`GR`](qiskit.circuit.library.GR ""qiskit.circuit.library.GR"")(num\_qubits, theta, phi) | Global R gate. | | [`GRX`](qiskit.circuit.library.GRX ""qiskit.circuit.library.GRX"")(num\_qubits, theta) | Global RX gate. | | [`GRY`](qiskit.circuit.library.GRY ""qiskit.circuit.library.GRY"")(num\_qubits, theta) | Global RY gate. | | [`GRZ`](qiskit.circuit.library.GRZ ""qiskit.circuit.library.GRZ"")(num\_qubits, phi) | Global RZ gate. | | [`MCPhaseGate`](qiskit.circuit.library.MCPhaseGate ""qiskit.circuit.library.MCPhaseGate"")(lam, num\_ctrl\_qubits\[, label, ...]) | Multi-controlled-Phase gate. | | [`MCXGate`](qiskit.circuit.library.MCXGate ""qiskit.circuit.library.MCXGate"")(\[num\_ctrl\_qubits, label, ...]) | The general, multi-controlled X gate. | | [`MCXGrayCode`](qiskit.circuit.library.MCXGrayCode ""qiskit.circuit.library.MCXGrayCode"")(\[num\_ctrl\_qubits, label, ...]) | Implement the multi-controlled X gate using the Gray code. | | [`MCXRecursive`](qiskit.circuit.library.MCXRecursive ""qiskit.circuit.library.MCXRecursive"")(\[num\_ctrl\_qubits, label, ...]) | Implement the multi-controlled X gate using recursion. | | [`MCXVChain`](qiskit.circuit.library.MCXVChain ""qiskit.circuit.library.MCXVChain"")(\[num\_ctrl\_qubits, dirty\_ancillas, ...]) | Implement the multi-controlled X gate using a V-chain of CX gates. | | [`RVGate`](qiskit.circuit.library.RVGate ""qiskit.circuit.library.RVGate"")(v\_x, v\_y, v\_z\[, basis]) | Rotation around arbitrary rotation axis $\vec{v}$ where $\|\vec{v}\|_2$ is angle of rotation in radians. | | [`PauliGate`](qiskit.circuit.library.PauliGate ""qiskit.circuit.library.PauliGate"")(label) | A multi-qubit Pauli gate. | | [`LinearFunction`](qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.LinearFunction"")(linear\[, validate\_input]) | A linear reversible circuit on n qubits. | | [`Isometry`](qiskit.circuit.library.Isometry ""qiskit.circuit.library.Isometry"")(isometry, num\_ancillas\_zero, ...\[, ...]) | Decomposition of arbitrary isometries from $m$ to $n$ qubits. | | [`UnitaryGate`](qiskit.circuit.library.UnitaryGate ""qiskit.circuit.library.UnitaryGate"")(data\[, label, check\_input]) | Class quantum gates specified by a unitary matrix. | | [`UCGate`](qiskit.circuit.library.UCGate ""qiskit.circuit.library.UCGate"")(gate\_list\[, up\_to\_diagonal]) | Uniformly controlled gate (also called multiplexed gate). | | [`UCPauliRotGate`](qiskit.circuit.library.UCPauliRotGate ""qiskit.circuit.library.UCPauliRotGate"")(angle\_list, rot\_axis) | Uniformly controlled Pauli rotations. | | [`UCRXGate`](qiskit.circuit.library.UCRXGate ""qiskit.circuit.library.UCRXGate"")(angle\_list) | Uniformly controlled Pauli-X rotations. | | [`UCRYGate`](qiskit.circuit.library.UCRYGate ""qiskit.circuit.library.UCRYGate"")(angle\_list) | Uniformly controlled Pauli-Y rotations. | | [`UCRZGate`](qiskit.circuit.library.UCRZGate ""qiskit.circuit.library.UCRZGate"")(angle\_list) | Uniformly controlled Pauli-Z rotations. | ## Boolean Logic Circuits These are [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") subclasses that implement boolean logic operations, such as the logical or of a set of qubit states. | | | | ------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------- | | [`AND`](qiskit.circuit.library.AND ""qiskit.circuit.library.AND"")(num\_variable\_qubits\[, flags, mcx\_mode]) | A circuit implementing the logical AND operation on a number of qubits. | | [`OR`](qiskit.circuit.library.OR ""qiskit.circuit.library.OR"")(num\_variable\_qubits\[, flags, mcx\_mode]) | A circuit implementing the logical OR operation on a number of qubits. | | [`XOR`](qiskit.circuit.library.XOR ""qiskit.circuit.library.XOR"")(num\_qubits\[, amount, seed]) | An n\_qubit circuit for bitwise xor-ing the input with some integer `amount`. | | [`InnerProduct`](qiskit.circuit.library.InnerProduct ""qiskit.circuit.library.InnerProduct"")(num\_qubits) | A 2n-qubit Boolean function that computes the inner product of two n-qubit vectors over $F_2$. | ## Basis Change Circuits These circuits allow basis transformations of the qubit states. For example, in the case of the Quantum Fourier Transform (QFT), it transforms between the computational basis and the Fourier basis. | | | | ------------------------------------------------------------------------------------------------------------ | ---------------------------------- | | [`QFT`](qiskit.circuit.library.QFT ""qiskit.circuit.library.QFT"")(\[num\_qubits, approximation\_degree, ...]) | Quantum Fourier Transform Circuit. | ## Arithmetic Circuits These [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")s perform classical arithmetic, such as addition or multiplication. ### Amplitude Functions | | | | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | [`LinearAmplitudeFunction`](qiskit.circuit.library.LinearAmplitudeFunction ""qiskit.circuit.library.LinearAmplitudeFunction"")(num\_state\_qubits, ...) | A circuit implementing a (piecewise) linear function on qubit amplitudes. | ### Functional Pauli Rotations | | | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------- | | [`FunctionalPauliRotations`](qiskit.circuit.library.FunctionalPauliRotations ""qiskit.circuit.library.FunctionalPauliRotations"")(\[num\_state\_qubits, ...]) | Base class for functional Pauli rotations. | | [`LinearPauliRotations`](qiskit.circuit.library.LinearPauliRotations ""qiskit.circuit.library.LinearPauliRotations"")(\[num\_state\_qubits, ...]) | Linearly-controlled X, Y or Z rotation. | | [`PolynomialPauliRotations`](qiskit.circuit.library.PolynomialPauliRotations ""qiskit.circuit.library.PolynomialPauliRotations"")(\[num\_state\_qubits, ...]) | A circuit implementing polynomial Pauli rotations. | | [`PiecewiseLinearPauliRotations`](qiskit.circuit.library.PiecewiseLinearPauliRotations ""qiskit.circuit.library.PiecewiseLinearPauliRotations"")(\[...]) | Piecewise-linearly-controlled Pauli rotations. | | [`PiecewisePolynomialPauliRotations`](qiskit.circuit.library.PiecewisePolynomialPauliRotations ""qiskit.circuit.library.PiecewisePolynomialPauliRotations"")(\[...]) | Piecewise-polynomially-controlled Pauli rotations. | | [`PiecewiseChebyshev`](qiskit.circuit.library.PiecewiseChebyshev ""qiskit.circuit.library.PiecewiseChebyshev"")(f\_x\[, degree, ...]) | Piecewise Chebyshev approximation to an input function. | ### Adders | | | | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | [`DraperQFTAdder`](qiskit.circuit.library.DraperQFTAdder ""qiskit.circuit.library.DraperQFTAdder"")(num\_state\_qubits\[, kind, name]) | A circuit that uses QFT to perform in-place addition on two qubit registers. | | [`CDKMRippleCarryAdder`](qiskit.circuit.library.CDKMRippleCarryAdder ""qiskit.circuit.library.CDKMRippleCarryAdder"")(num\_state\_qubits\[, ...]) | A ripple-carry circuit to perform in-place addition on two qubit registers. | | [`VBERippleCarryAdder`](qiskit.circuit.library.VBERippleCarryAdder ""qiskit.circuit.library.VBERippleCarryAdder"")(num\_state\_qubits\[, ...]) | The VBE ripple carry adder \[1]. | | [`WeightedAdder`](qiskit.circuit.library.WeightedAdder ""qiskit.circuit.library.WeightedAdder"")(\[num\_state\_qubits, weights, name]) | A circuit to compute the weighted sum of qubit registers. | ### Multipliers | | | | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | [`HRSCumulativeMultiplier`](qiskit.circuit.library.HRSCumulativeMultiplier ""qiskit.circuit.library.HRSCumulativeMultiplier"")(num\_state\_qubits\[, ...]) | A multiplication circuit to store product of two input registers out-of-place. | | [`RGQFTMultiplier`](qiskit.circuit.library.RGQFTMultiplier ""qiskit.circuit.library.RGQFTMultiplier"")(num\_state\_qubits\[, ...]) | A QFT multiplication circuit to store product of two input registers out-of-place. | ### Comparators | | | | --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | | [`IntegerComparator`](qiskit.circuit.library.IntegerComparator ""qiskit.circuit.library.IntegerComparator"")(\[num\_state\_qubits, value, ...]) | Integer Comparator. | ### Functions on binary variables | | | | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | [`QuadraticForm`](qiskit.circuit.library.QuadraticForm ""qiskit.circuit.library.QuadraticForm"")(\[num\_result\_qubits, ...]) | Implements a quadratic form on binary variables encoded in qubit registers. | ### Other arithmetic functions | | | | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | | [`ExactReciprocal`](qiskit.circuit.library.ExactReciprocal ""qiskit.circuit.library.ExactReciprocal"")(num\_state\_qubits, scaling\[, ...]) | Exact reciprocal | ## Particular Quantum Circuits | | | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | [`FourierChecking`](qiskit.circuit.library.FourierChecking ""qiskit.circuit.library.FourierChecking"")(f, g) | Fourier checking circuit. | | [`GraphState`](qiskit.circuit.library.GraphState ""qiskit.circuit.library.GraphState"")(adjacency\_matrix) | Circuit to prepare a graph state. | | [`HiddenLinearFunction`](qiskit.circuit.library.HiddenLinearFunction ""qiskit.circuit.library.HiddenLinearFunction"")(adjacency\_matrix) | Circuit to solve the hidden linear function problem. | | [`IQP`](qiskit.circuit.library.IQP ""qiskit.circuit.library.IQP"")(interactions) | Instantaneous quantum polynomial (IQP) circuit. | | [`QuantumVolume`](qiskit.circuit.library.QuantumVolume ""qiskit.circuit.library.QuantumVolume"")(num\_qubits\[, depth, seed, ...]) | A quantum volume model circuit. | | [`PhaseEstimation`](qiskit.circuit.library.PhaseEstimation ""qiskit.circuit.library.PhaseEstimation"")(num\_evaluation\_qubits, unitary) | Phase Estimation circuit. | | [`GroverOperator`](qiskit.circuit.library.GroverOperator ""qiskit.circuit.library.GroverOperator"")(oracle\[, state\_preparation, ...]) | The Grover operator. | | [`PhaseOracle`](qiskit.circuit.library.PhaseOracle ""qiskit.circuit.library.PhaseOracle"")(expression\[, synthesizer, var\_order]) | Phase Oracle. | | [`PauliEvolutionGate`](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate"")(operator\[, time, label, ...]) | Time-evolution of an operator consisting of Paulis. | | [`HamiltonianGate`](qiskit.circuit.library.HamiltonianGate ""qiskit.circuit.library.HamiltonianGate"")(data, time\[, label]) | Class for representing evolution by a Hamiltonian operator as a gate. | | [`UnitaryOverlap`](qiskit.circuit.library.UnitaryOverlap ""qiskit.circuit.library.UnitaryOverlap"")(unitary1, unitary2\[, ...]) | Circuit that returns the overlap between two unitaries $U_2^{\dag} U_1$. | ## N-local circuits These `BlueprintCircuit` subclasses are used as parameterized models (a.k.a. ansatzes or variational forms) in variational algorithms. They are heavily used in near-term algorithms in e.g. Chemistry, Physics or Optimization. | | | | ----------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | [`NLocal`](qiskit.circuit.library.NLocal ""qiskit.circuit.library.NLocal"")(\[num\_qubits, rotation\_blocks, ...]) | The n-local circuit class. | | [`TwoLocal`](qiskit.circuit.library.TwoLocal ""qiskit.circuit.library.TwoLocal"")(\[num\_qubits, rotation\_blocks, ...]) | The two-local circuit. | | [`PauliTwoDesign`](qiskit.circuit.library.PauliTwoDesign ""qiskit.circuit.library.PauliTwoDesign"")(\[num\_qubits, reps, seed, ...]) | The Pauli Two-Design ansatz. | | [`RealAmplitudes`](qiskit.circuit.library.RealAmplitudes ""qiskit.circuit.library.RealAmplitudes"")(\[num\_qubits, entanglement, ...]) | The real-amplitudes 2-local circuit. | | [`EfficientSU2`](qiskit.circuit.library.EfficientSU2 ""qiskit.circuit.library.EfficientSU2"")(\[num\_qubits, su2\_gates, ...]) | The hardware efficient SU(2) 2-local circuit. | | [`EvolvedOperatorAnsatz`](qiskit.circuit.library.EvolvedOperatorAnsatz ""qiskit.circuit.library.EvolvedOperatorAnsatz"")(\[operators, reps, ...]) | The evolved operator ansatz. | | [`ExcitationPreserving`](qiskit.circuit.library.ExcitationPreserving ""qiskit.circuit.library.ExcitationPreserving"")(\[num\_qubits, mode, ...]) | The heuristic excitation-preserving wave function ansatz. | | [`QAOAAnsatz`](qiskit.circuit.library.QAOAAnsatz ""qiskit.circuit.library.QAOAAnsatz"")(\[cost\_operator, reps, ...]) | A generalized QAOA quantum circuit with a support of custom initial states and mixers. | ## Data encoding circuits These `BlueprintCircuit` encode classical data in quantum states and are used as feature maps for classification. | | | | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | | [`PauliFeatureMap`](qiskit.circuit.library.PauliFeatureMap ""qiskit.circuit.library.PauliFeatureMap"")(\[feature\_dimension, reps, ...]) | The Pauli Expansion circuit. | | [`ZFeatureMap`](qiskit.circuit.library.ZFeatureMap ""qiskit.circuit.library.ZFeatureMap"")(feature\_dimension\[, reps, ...]) | The first order Pauli Z-evolution circuit. | | [`ZZFeatureMap`](qiskit.circuit.library.ZZFeatureMap ""qiskit.circuit.library.ZZFeatureMap"")(feature\_dimension\[, reps, ...]) | Second-order Pauli-Z evolution circuit. | | [`StatePreparation`](qiskit.circuit.library.StatePreparation ""qiskit.circuit.library.StatePreparation"")(params\[, num\_qubits, ...]) | Complex amplitude state preparation. | | [`Initialize`](qiskit.circuit.library.Initialize ""qiskit.circuit.library.Initialize"")(params\[, num\_qubits, normalize]) | Complex amplitude initialization. | ## Template circuits Templates are functions that return circuits that compute the identity. They are used at circuit optimization where matching part of the template allows the compiler to replace the match with the inverse of the remainder from the template. In this example, the identity constant in a template is checked: ```python from qiskit.circuit.library.templates import template_nct_4b_1 from qiskit.quantum_info import Operator import numpy as np template = template_nct_4b_1() identity = np.identity(2 ** len(template.qubits), dtype=complex) data = Operator(template).data np.allclose(data, identity) # True, template_nct_4b_1 is the identity ``` ### NCT (Not-CNOT-Toffoli) template circuits Template circuits for [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate""), [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate""), and [`CCXGate`](qiskit.circuit.library.CCXGate ""qiskit.circuit.library.CCXGate"") (Toffoli) gates. **Reference:** Maslov, D. and Dueck, G. W. and Miller, D. M., Techniques for the synthesis of reversible Toffoli networks, 2007 [http://dx.doi.org/10.1145/1278349.1278355](http://dx.doi.org/10.1145/1278349.1278355) #### template\_nct\_2a\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_2a\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_2a\_3 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_4a\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_4a\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_4a\_3 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_4b\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_4b\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_5a\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_5a\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_5a\_3 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_5a\_4 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_6a\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_6a\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_6a\_3 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_6a\_4 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_6b\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_6b\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_6c\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_7a\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_7b\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_7c\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_7d\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_7e\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9a\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_3 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_4 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_5 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_6 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_7 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_8 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_9 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_10 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_11 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9c\_12 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9d\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9d\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9d\_3 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9d\_4 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9d\_5 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9d\_6 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9d\_7 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9d\_8 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9d\_9 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### template\_nct\_9d\_10 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### Clifford template circuits Template circuits over Clifford gates. #### clifford\_2\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_2\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_2\_3 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_2\_4 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_3\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_4\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_4\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_4\_3 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_4\_4 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_5\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_6\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_6\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_6\_3 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_6\_4 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_6\_5 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_8\_1 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_8\_2 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") #### clifford\_8\_3 **Returns** template as a quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### RZXGate template circuits Template circuits with [`RZXGate`](qiskit.circuit.library.RZXGate ""qiskit.circuit.library.RZXGate""). #### rzx\_yz Template for CX - RYGate - CX. #### rzx\_xz Template for CX - RXGate - CX. #### rzx\_cy Template for CX - RYGate - CX. #### rzx\_zz1 Template for CX - RZGate - CX. #### rzx\_zz2 Template for CX - RZGate - CX. #### rzx\_zz3 Template for CX - RZGate - CX. ",repo/docs/api/qiskit/1.0\circuit_library.mdx "--- title: singleton description: API reference for qiskit.circuit.singleton in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.circuit.singleton --- # Singleton instructions `qiskit.circuit.singleton` The machinery in this module is for defining subclasses of [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") and [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") that preferentially return a shared immutable singleton instance when instantiated. Taking the example of [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate""), the final user-facing result is that: * There is a regular class called `XGate`, which derives from [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). * Doing something like `XGate(label=""my_gate"")` produces an object whose type is exactly `XGate`, and all the mutability works completely as expected; all the methods resolve to exactly those defined by [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate""), [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""), or parents. * Doing `XGate()` produces a singleton object whose type is a synthetic `_SingletonXGate` class, which derives [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate"") but overrides [`__setattr__()`](https://docs.python.org/3/reference/datamodel.html#object.__setattr__ ""(in Python v3.12)"") to make itself immutable. The object itself has precisely the same instance attributes as `XGate()` would have if there was no singleton handling. This object will return itself under [`copy()`](https://docs.python.org/3/library/copy.html#copy.copy ""(in Python v3.12)""), [`deepcopy()`](https://docs.python.org/3/library/copy.html#copy.deepcopy ""(in Python v3.12)"") and roundtrip through [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle ""(in Python v3.12)""). The same can be true for, for example, [`Measure`](qiskit.circuit.library.Measure ""qiskit.circuit.library.Measure""), except that it’s a subclass of [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") only, and not [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). The classes in this module are for advanced use, because they are closely entwined with the heart of Qiskit’s data model for circuits. 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 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. ### SingletonGate 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. ### SingletonControlledGate 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. When inheriting from one of these classes, the produced class will have an eagerly created singleton instance that will be returned whenever the class is constructed with arguments that have been defined to be singletons. Typically this will be the defaults. These instances are immutable; attempts to modify their properties will raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)""). *All* subclasses of [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") have a [`mutable`](qiskit.circuit.Instruction#mutable ""qiskit.circuit.Instruction.mutable"") property. For most instructions this is `True`, while for the singleton instances it is `False`. One can use the [`to_mutable()`](qiskit.circuit.Instruction#to_mutable ""qiskit.circuit.Instruction.to_mutable"") method to get a version of the instruction that is owned and safe to mutate. The singleton instances are not exact instances of their base class; they are special subclasses that cannot construct new objects. This means that: ```python type(XGate()) is not XGate ``` You should not rely on [`type`](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"") having an exact value; use [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance ""(in Python v3.12)"") instead for type checking. If you need to reliably retrieve the base class from an [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction""), see the [`Instruction.base_class`](qiskit.circuit.Instruction#base_class ""qiskit.circuit.Instruction.base_class"") attribute; singleton instances set this correctly. For most cases in using Qiskit, [`Instruction.name`](qiskit.circuit.Instruction#name ""qiskit.circuit.Instruction.name"") is a more suitable determiner of what an instruction “means” in a circuit. ### Deriving new singletons The simplest example of deriving a new singleton instruction is simply to inherit from the correct base and supply an [`__init__()`](https://docs.python.org/3/reference/datamodel.html#object.__init__ ""(in Python v3.12)"") method that has immutable defaults for any arguments. For example: ```python from qiskit.circuit.singleton import SingletonInstruction class MyInstruction(SingletonInstruction): def __init__(self, label=None): super().__init__(""my_instruction"", 1, 0, label=label) assert MyInstruction() is MyInstruction() assert MyInstruction(label=""some label"") is not MyInstruction() assert MyInstruction(label=""some label"").mutable ``` The singleton instance will use all the constructor’s defaults. You can also derive from an instruction that is itself a singleton. The singleton nature of the class will be inherited, though the singleton instances of the two classes will be different: ```python class MyOtherInstruction(MyInstruction): pass assert MyOtherInstruction() is MyOtherInstruction() assert MyOtherInstruction() is not MyInstruction() ``` If for some reason you want to derive from [`SingletonInstruction`](#qiskit.circuit.singleton.SingletonInstruction ""qiskit.circuit.singleton.SingletonInstruction""), or one of the related or subclasses but *do not* want the default singleton instance to be created, such as if you are defining a new abstract base class, you can set the keyword argument `create_default_singleton=False` in the class definition: ```python class NotASingleton(SingletonInstruction, create_default_singleton=False): def __init__(self): return super().__init__(""my_mutable"", 1, 0, []) assert NotASingleton() is not NotASingleton() ``` If your constructor does not have defaults for all its arguments, you must set `create_default_singleton=False`. Subclasses of [`SingletonInstruction`](#qiskit.circuit.singleton.SingletonInstruction ""qiskit.circuit.singleton.SingletonInstruction"") and the other associated classes can control how their constructor’s arguments are interpreted, in order to help the singleton machinery return the singleton even in the case than an optional argument is explicitly set to its default. #### \_singleton\_lookup\_key Given the arguments to the constructor, return a key tuple that identifies the singleton instance to retrieve, or `None` if the arguments imply that a mutable object must be created. For performance, as a special case, this method will not be called if the class constructor was given zero arguments (e.g. the construction `XGate()` will not call this method, but `XGate(label=None)` will), and the default singleton will immediately be returned. This static method can (and probably should) be overridden by subclasses. The derived signature should match the class’s `__init__`; this method should then examine the arguments to determine whether it requires mutability, or what the cache key (if any) should be. The function should return either `None` or valid `dict` key (i.e. hashable and implements equality). Returning `None` means that the created instance must be mutable. No further singleton-based processing will be done, and the class creation will proceed as if there was no singleton handling. Otherwise, the returned key can be anything hashable and no special meaning is ascribed to it. Whenever this method returns the same key, the same singleton instance will be returned. We suggest that you use a tuple of the values of all arguments that can be set while maintaining the singleton nature. Only keys that match the default arguments or arguments given to `additional_singletons` at class-creation time will actually return singletons; other values will return a standard mutable instance. The singleton machinery will handle an unhashable return from this function gracefully by returning a mutable instance. Subclasses should ensure that their key is hashable in the happy path, but they do not need to manually verify that the user-supplied arguments are hashable. For example, it’s safe to implement this as: ```python @staticmethod def _singleton_lookup_key(*args, **kwargs): return None if kwargs else args ``` even though a user might give some unhashable type as one of the `args`. 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 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. There are several moving parts to tackle here. The behaviour of having `XGate()` return some singleton object that is an (inexact) instance of [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate"") but *without* calling `__init__` requires us to override [`type.__call__`](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)""). This means that [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate"") must have a metaclass that defines `__call__` to return the singleton instance. Next, we need to ensure that there *is* a singleton instance for `XGate()` to return. This can be done dynamically on each call (i.e. check if the instance exists and create it if not), but since we also want that instance to be very special, it’s easier to hook in and create it during the definition of the `XGate` type object. This also has the advantage that we do not need to make the singleton object pickleable; we only need to specify where to retrieve it from during the unpickle, because the creation of the base type object will recreate the singleton. We want the singleton instance to: * be immutable; it should reject all attempts to mutate itself. * have exactly the same state as an `XGate()` would have had if there was no singleton handling. We do this in a three-step procedure: 1. Before creating any singletons, we separately define the overrides needed to make an [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") and a [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") immutable. This is `_SingletonInstructionOverrides` and the other `_*Overrides` classes. 2. While we are creating the `XGate` type object, we dynamically *also* create a subclass of it that has the immutable overrides in its method-resolution order in the correct place. These override the standard methods / properties that are defined on the mutable gate (we do not attempt to override any cases where the type object we are creating has extra inplace methods). 3. We can’t instantiate this new subclass, because when it calls `XGate.__init__`, it will attempt to set some attributes, and these will be rejected by immutability. Instead, we first create a completely regular `XGate` instance, and then we dynamically change its type to the singleton class, freezing it. We could do this entirely within the metaclass machinery, but that would require `XGate` to be defined as something like: ```python class XGate(Gate, metaclass=_SingletonMeta, overrides=_SingletonGateOverrides): ... ``` which is super inconvenient (or we’d have to have `_SingletonMeta` do a bunch of fragile introspection). Instead, we use the [`abc.ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"")/[`abc.ABCMeta`](https://docs.python.org/3/library/abc.html#abc.ABCMeta ""(in Python v3.12)"") pattern of defining a concrete middle class ([`SingletonGate`](#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") in the [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate"") case) that sets the metaclass, selects the overrides to be applied, and has an [`__init_subclass__()`](https://docs.python.org/3/reference/datamodel.html#object.__init_subclass__ ""(in Python v3.12)"") that applies the singleton-subclass-creation steps above. The overrides are in separate classes so that *mutable* [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate"") instances do not have them in their own method-resolution orders; doing this is easier to implement, but requires all the setters and checkers to dance around at runtime trying to validate whether mutating the instance is allowed. Finally, to actually build all this machinery up, the base is `_SingletonMeta`, which is a metaclass compatible with any metaclass of [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction""). This defines the [`__call__()`](https://docs.python.org/3/reference/datamodel.html#object.__call__ ""(in Python v3.12)"") machinery that overrides [`type.__call__`](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"") to return the singleton instances. The other component of it is its [`__new__()`](https://docs.python.org/3/reference/datamodel.html#object.__new__ ""(in Python v3.12)""), which is called (non-trivially) during the creation of [`SingletonGate`](#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") and [`SingletonInstruction`](#qiskit.circuit.singleton.SingletonInstruction ""qiskit.circuit.singleton.SingletonInstruction"") with its `overrides` keyword argument set to define the `__init_subclass__` of those classes with the above properties. We use the metaclass to add this method dynamically, because the [`__init_subclass__()`](https://docs.python.org/3/reference/datamodel.html#object.__init_subclass__ ""(in Python v3.12)"") machinery wants to be abstract, closing over the `overrides` and the base class, but still able to call [`super`](https://docs.python.org/3/library/functions.html#super ""(in Python v3.12)""). It’s more convenient to do this dynamically, closing over the desired class variable and using the two-argument form of [`super`](https://docs.python.org/3/library/functions.html#super ""(in Python v3.12)""), since the zero-argument form does magic introspection based on where its containing function was defined. Handling multiple singletons requires storing the initialization arguments in some form, to allow the [`to_mutable()`](qiskit.circuit.Instruction#to_mutable ""qiskit.circuit.Instruction.to_mutable"") method and pickling to be defined. We do this as a lookup dictionary on the singleton *type object*. This is logically an instance attribute, but because we need to dynamically switch in the dynamic \_Singleton type onto an instance of the base type, that gets rather complex; either we have to require that the base already has an instance dictionary, or we risk breaking the `__slots__` layout during the switch. Since the singletons have lifetimes that last until garbage collection of their base class’s type object, we can fake out this instance dictionary using a type-object dictionary that maps instance pointers to the data we want to store. An alternative would be to build a new type object for each individual singleton that closes over (or stores) the initializer arguments, but type objects are quite heavy and the principle is largely same anyway. ",repo/docs/api/qiskit/1.0\circuit_singleton.mdx "--- title: classicalfunction description: API reference for qiskit.circuit.classicalfunction in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.circuit.classicalfunction --- # ClassicalFunction compiler `qiskit.circuit.classicalfunction` ## Overview The classical function compiler provides the necessary tools to map a classical potentially irreversible functions into quantum circuits. Below is a simple example of how to synthesize a simple boolean function defined using Python into a QuantumCircuit: > ```python > from qiskit.circuit.classicalfunction import classical_function > from qiskit.circuit.classicalfunction.types import Int1 > > @classical_function > def grover_oracle(a: Int1, b: Int1, c: Int1, d: Int1) -> Int1: > return (not a and b and not c and d) > > quantum_circuit = grover_oracle.synth(registerless=False) > quantum_circuit.draw('text') > > a: ──o── > │ > b: ──■── > │ > c: ──o── > │ > d: ──■── > ┌─┴─┐ > return: ┤ X ├ > └───┘ > ``` Following Qiskit’s little-endian bit ordering convention, the left-most bit (`a`) is the most significant bit and the right-most bit (`d`) is the least significant bit. ## Supplementary Information ### Tweedledum Tweedledum is a C++-17 header-only library that implements a large set of reversible (and quantum) synthesis, optimization, and mapping algorithms. The classical function compiler relies on it and its dependencies to both represent logic networks and synthesize them into quantum circuits. ### ClassicalFunction data types At the moment, the only type supported by the classical\_function compilers is `qiskit.circuit.classicalfunction.types.Int1`. The classical function function to parse *must* include type hints (just `Int1` for now). The resulting gate will be a gate in the size of the sum of all the parameters and the return. The type `Int1` means the classical function will only operate at bit level. ## ClassicalFunction compiler API ### classical\_function Decorator for a classical function that returns a ClassicalFunction object. ### ClassicalFunction | | | | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | [`ClassicalFunction`](qiskit.circuit.classicalfunction.ClassicalFunction ""qiskit.circuit.classicalfunction.ClassicalFunction"")(source\[, name]) | Represent a classical function and its logic network. | | [`BooleanExpression`](qiskit.circuit.classicalfunction.BooleanExpression ""qiskit.circuit.classicalfunction.BooleanExpression"")(expression\[, name, var\_order]) | The Boolean Expression gate. | ### Exceptions | | | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | | [`ClassicalFunctionCompilerTypeError`](qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError ""qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError"")(\*message) | ClassicalFunction compiler type error. | | [`ClassicalFunctionParseError`](qiskit.circuit.classicalfunction.ClassicalFunctionParseError ""qiskit.circuit.classicalfunction.ClassicalFunctionParseError"")(\*message) | ClassicalFunction compiler parse error. | | [`ClassicalFunctionCompilerTypeError`](qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError ""qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError"")(\*message) | ClassicalFunction compiler type error. | ",repo/docs/api/qiskit/1.0\classicalfunction.mdx "--- title: compiler description: API reference for qiskit.compiler in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.compiler --- # Compilation Routines `qiskit.compiler` ## Circuit and Pulse Compilation Functions ### assemble Assemble a list of circuits or pulse schedules into a `Qobj`. This function serializes the payloads, which could be either circuits or schedules, to create `Qobj` “experiments”. It further annotates the experiment payload with header and configurations. NOTE: Backend.options is not used within assemble. The required values (previously given by backend.set\_options) should be manually extracted from options and supplied directly when calling. **Parameters** * **experiments** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")*] |* [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"")*] |* [*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"")*]*) – Circuit(s) or pulse schedule(s) to execute * **backend** ([*Backend*](qiskit.providers.Backend ""qiskit.providers.backend.Backend"") *| None*) – If set, some runtime options are automatically grabbed from `backend.configuration()` and `backend.defaults()`. If any other option is explicitly set (e.g., `rep_time`), it will override the backend’s. If any other options is set in the run\_config, it will also override the backend’s. * **qobj\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – String identifier to annotate the `Qobj` * **qobj\_header** ([*QobjHeader*](qiskit.qobj.QobjHeader ""qiskit.qobj.common.QobjHeader"") *|*[*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict ""(in Python v3.12)"") *| None*) – User input that will be inserted in `Qobj` header, and will also be copied to the corresponding Result header. Headers do not affect the run. * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Number of repetitions of each circuit, for sampling. Default: 1024 or `max_shots` from the backend configuration, whichever is smaller * **memory** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, per-shot measurement bitstrings are returned as well (provided the backend supports it). For OpenPulse jobs, only measurement level 2 supports this option. * **seed\_simulator** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Random seed to control sampling, for when backend is a simulator * **qubit\_lo\_freq** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None*) – List of job level qubit drive LO frequencies in Hz. Overridden by `schedule_los` if specified. Must have length `n_qubits.` * **meas\_lo\_freq** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None*) – List of measurement LO frequencies in Hz. Overridden by `schedule_los` if specified. Must have length `n_qubits.` * **qubit\_lo\_range** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None*) – List of job level drive LO ranges each of form `[range_min, range_max]` in Hz. Used to validate `qubit_lo_freq`. Must have length `n_qubits.` * **meas\_lo\_range** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None*) – List of job level measurement LO ranges each of form `[range_min, range_max]` in Hz. Used to validate `meas_lo_freq`. Must have length `n_qubits.` * **schedule\_los** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict ""(in Python v3.12)"")*\[PulseChannel,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | LoConfig] |* [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict ""(in Python v3.12)"")*\[PulseChannel,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | LoConfig | None*) – Experiment level (ie circuit or schedule) LO frequency configurations for qubit drive and measurement channels. These values override the job level values from `default_qubit_los` and `default_meas_los`. Frequencies are in Hz. Settable for OpenQASM 2 and pulse jobs. * **meas\_level** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| MeasLevel*) – Set the appropriate level of the measurement output for pulse experiments. * **meas\_return** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| MeasReturnType*) – Level of measurement data for the backend to return. **For `meas_level` 0 and 1:** * `single` returns information from every shot. * `avg` returns average measurement output (averaged over number of shots). * **meas\_map** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"")*]] | None*) – List of lists, containing qubits that must be measured together. * **memory\_slot\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Size of each memory slot if the output is Level 0. * **rep\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time per program execution in seconds. Must be from the list provided by the backend (`backend.configuration().rep_times`). Defaults to the first entry. * **rep\_delay** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Delay between programs in seconds. Only supported on certain backends (if `backend.configuration().dynamic_reprate_enabled=True`). If supported, `rep_delay` will be used instead of `rep_time` and must be from the range supplied by the backend (`backend.configuration().rep_delay_range`). Default is given by `backend.configuration().default_rep_delay`. * **parameter\_binds** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict ""(in Python v3.12)"")*\[*[*Parameter*](qiskit.circuit.Parameter ""qiskit.circuit.parameter.Parameter"")*,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]] | None*) – List of Parameter bindings over which the set of experiments will be executed. Each list element (bind) should be of the form \{Parameter1: value1, Parameter2: value2, …}. All binds will be executed across all experiments; e.g., if parameter\_binds is a length-n list, and there are m experiments, a total of m x n experiments will be run (one for each experiment/bind pair). * **parametric\_pulses** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*] | None*) – A list of pulse shapes which are supported internally on the backend. Example: ```python ['gaussian', 'constant'] ``` * **init\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to reset the qubits to the ground state for each shot. Default: `True`. * **\*\*run\_config** ([*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict ""(in Python v3.12)"")) – Extra arguments used to configure the run (e.g., for Aer configurable backends). Refer to the backend documentation for details on these arguments. **Returns** A `Qobj` that can be run on a backend. Depending on the type of input, this will be either a `QasmQobj` or a `PulseQobj`. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input cannot be interpreted as either circuits or schedules **Return type** [*QasmQobj*](qiskit.qobj.QasmQobj ""qiskit.qobj.qasm_qobj.QasmQobj"") | [*PulseQobj*](qiskit.qobj.PulseQobj ""qiskit.qobj.pulse_qobj.PulseQobj"") ### schedule 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"")] ### transpile Transpile one or more circuits, according to some desired transpilation targets. Transpilation is potentially done in parallel using multiprocessing when `circuits` is a list with > 1 [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") object depending on the local environment and configuration. **Parameters** * **circuits** (*\_CircuitT*) – Circuit(s) to transpile * **backend** ([*Backend*](qiskit.providers.Backend ""qiskit.providers.backend.Backend"") *| None*) – If set, the transpiler will compile the input circuit to this target device. If any other option is explicitly set (e.g., `coupling_map`), it will override the backend’s. * **basis\_gates** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*] | None*) – List of basis gate names to unroll to (e.g: `['u1', 'u2', 'u3', 'cx']`). If `None`, do not unroll. * **inst\_map** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.instruction_schedule_map.InstructionScheduleMap"")*] | None*) – Mapping of unrolled gates to pulse schedules. If this is not provided, transpiler tries to get from the backend. If any user defined calibration is found in the map and this is used in a circuit, transpiler attaches the custom gate definition to the circuit. This enables one to flexibly override the low-level instruction implementation. This feature is available iff the backend supports the pulse gate experiment. * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.coupling.CouplingMap"") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]] | None*) – Directed coupling map (perhaps custom) to target in mapping. If the coupling map is symmetric, both directions need to be specified. Multiple formats are supported: 1. `CouplingMap` instance 2. List, must be given as an adjacency matrix, where each entry specifies all directed two-qubit interactions supported by backend, e.g: `[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]` * **backend\_properties** ([*BackendProperties*](qiskit.providers.models.BackendProperties ""qiskit.providers.models.backendproperties.BackendProperties"") *| None*) – properties returned by a backend, including information on gate errors, readout errors, qubit coherence times, etc. Find a backend that provides this information with: `backend.properties()` * **initial\_layout** ([*Layout*](qiskit.transpiler.Layout ""qiskit.transpiler.layout.Layout"") *|*[*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict ""(in Python v3.12)"") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"") *| None*) – Initial position of virtual qubits on physical qubits. If this layout makes the circuit compatible with the coupling\_map constraints, it will be used. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. Multiple formats are supported: 1. `Layout` instance 2. Dict \* virtual to physical: ```python {qr[0]: 0, qr[1]: 3, qr[2]: 5} ``` * physical to virtual: ```python {0: qr[0], 3: qr[1], 5: qr[2]} ``` 3. List * virtual to physical: ```python [0, 3, 5] # virtual qubits are ordered (in addition to named) ``` * physical to virtual: ```python [qr[0], None, None, qr[1], None, qr[2]] ``` * **layout\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of layout selection pass (‘trivial’, ‘dense’, ‘sabre’). This can also be the external plugin name to use for the `layout` stage. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins ""qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins"") with `""layout""` for the `stage_name` argument. * **routing\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of routing pass (‘basic’, ‘lookahead’, ‘stochastic’, ‘sabre’, ‘none’). Note This can also be the external plugin name to use for the `routing` stage. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins ""qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins"") with `""routing""` for the `stage_name` argument. * **translation\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of translation pass (‘unroller’, ‘translator’, ‘synthesis’) This can also be the external plugin name to use for the `translation` stage. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins ""qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins"") with `""translation""` for the `stage_name` argument. * **scheduling\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of scheduling pass. \* `'as_soon_as_possible'`: Schedule instructions greedily, as early as possible on a qubit resource. (alias: `'asap'`) \* `'as_late_as_possible'`: Schedule instructions late, i.e. keeping qubits in the ground state when possible. (alias: `'alap'`) If `None`, no scheduling will be done. This can also be the external plugin name to use for the `scheduling` stage. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins ""qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins"") with `""scheduling""` for the `stage_name` argument. * **instruction\_durations** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None,* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]] |* [*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None]] |* [*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*,* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]] |* [*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*,* [*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]] |* [*InstructionDurations*](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.instruction_durations.InstructionDurations"") *| None*) – Durations of instructions. Applicable only if scheduling\_method is specified. The gate lengths defined in `backend.properties` are used as default. They are overwritten if this `instruction_durations` is specified. The format of `instruction_durations` must be as follows. The instruction\_durations must be given as a list of tuples \[(instruction\_name, qubits, duration, unit), …]. | \[(‘cx’, \[0, 1], 12.3, ‘ns’), (‘u3’, \[0], 4.56, ‘ns’)] | \[(‘cx’, \[0, 1], 1000), (‘u3’, \[0], 300)] If unit is omitted, the default is ‘dt’, which is a sample time depending on backend. If the time unit is ‘dt’, the duration must be an integer. * **dt** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – Backend sample time (resolution) in seconds. If `None` (default), `backend.configuration().dt` is used. * **approximation\_degree** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – heuristic dial used for circuit approximation (1.0=no approximation, 0.0=maximal approximation) * **timing\_constraints** ([*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None*) – An optional control hardware restriction on instruction time resolution. A quantum computer backend may report a set of restrictions, namely: * granularity: An integer value representing minimum pulse gate resolution in units of `dt`. A user-defined pulse gate should have duration of a multiple of this granularity value. * min\_length: An integer value representing minimum pulse gate length in units of `dt`. A user-defined pulse gate should be longer than this length. * pulse\_alignment: An integer value representing a time resolution of gate instruction starting time. Gate instruction should start at time which is a multiple of the alignment value. * acquire\_alignment: An integer value representing a time resolution of measure instruction starting time. Measure instruction should start at time which is a multiple of the alignment value. This information will be provided by the backend configuration. If the backend doesn’t have any restriction on the instruction time allocation, then `timing_constraints` is None and no adjustment will be performed. * **seed\_transpiler** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Sets random seed for the stochastic parts of the transpiler * **optimization\_level** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – How much optimization to perform on the circuits. Higher levels generate more optimized circuits, at the expense of longer transpilation time. * 0: no optimization * 1: light optimization * 2: heavy optimization * 3: even heavier optimization If `None`, level 1 will be chosen as default. * **callback** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[BasePass,* [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")*,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*,* [*PropertySet*](qiskit.passmanager.PropertySet ""qiskit.passmanager.compilation_status.PropertySet"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*],* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")*] | None*) – A callback function that will be called after each pass execution. The function will be called with 5 keyword arguments, | `pass_`: the pass being run. | `dag`: the dag output of the pass. | `time`: the time to execute the pass. | `property_set`: the property set. | `count`: the index for the pass execution. The exact arguments passed expose the internals of the pass manager, and are subject to change as the pass manager internals change. If you intend to reuse a callback function over multiple releases, be sure to check that the arguments being passed are the same. To use the callback feature, define a function that will take in kwargs dict and access the variables. For example: ```python def callback_func(**kwargs): pass_ = kwargs['pass_'] dag = kwargs['dag'] time = kwargs['time'] property_set = kwargs['property_set'] count = kwargs['count'] ... transpile(circ, callback=callback_func) ``` * **output\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*] | None*) – A list with strings to identify the output circuits. The length of the list should be exactly the length of the `circuits` parameter. * **unitary\_synthesis\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the unitary synthesis method to use. By default `'default'` is used. You can see a list of installed plugins with [`unitary_synthesis_plugin_names()`](qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names ""qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names""). * **unitary\_synthesis\_plugin\_config** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *| None*) – An optional configuration dictionary that will be passed directly to the unitary synthesis plugin. By default this setting will have no effect as the default unitary synthesis method does not take custom configuration. This should only be necessary when a unitary synthesis plugin is specified with the `unitary_synthesis_method` argument. As this is custom for each unitary synthesis plugin refer to the plugin documentation for how to use this option. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.target.Target"") *| None*) – A backend transpiler target. Normally this is specified as part of the `backend` argument, but if you have manually constructed a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object you can specify it manually here. This will override the target from `backend`. * **hls\_config** ([*HLSConfig*](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") *| None*) – An optional configuration class `HLSConfig` that will be passed directly to `HighLevelSynthesis` transformation pass. This configuration class allows to specify for various high-level objects the lists of synthesis algorithms and their parameters. * **init\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The plugin name to use for the `init` stage. By default an external plugin is not used. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins ""qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins"") with `""init""` for the stage name argument. * **optimization\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The plugin name to use for the `optimization` stage. By default an external plugin is not used. You can see a list of installed plugins by using [`list_stage_plugins()`](transpiler_plugins#qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins ""qiskit.transpiler.preset_passmanagers.plugin.list_stage_plugins"") with `""optimization""` for the `stage_name` argument. * **ignore\_backend\_supplied\_default\_methods** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to `True` any default methods specified by a backend will be ignored. Some backends specify alternative default methods to support custom compilation target-specific passes/plugins which support backend-specific compilation techniques. If you’d prefer that these defaults were not used this option is used to disable those backend-specific defaults. * **num\_processes** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The maximum number of parallel processes to launch for this call to transpile if parallel execution is enabled. This argument overrides `num_processes` in the user configuration file, and the `QISKIT_NUM_PROCS` environment variable. If set to `None` the system default or local user configuration will be used. **Returns** The transpiled circuit(s). **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – in case of bad inputs to transpiler (like conflicting parameters) or errors in passes **Return type** *\_CircuitT* ### sequence 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"")] ",repo/docs/api/qiskit/1.0\compiler.mdx "--- title: converters description: API reference for qiskit.converters in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.converters --- # Circuit Converters `qiskit.converters` ### circuit\_to\_dag 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) ``` ### dag\_to\_circuit 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) ### circuit\_to\_instruction 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) ``` ### circuit\_to\_gate 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"") ### dagdependency\_to\_circuit 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"") ### circuit\_to\_dagdependency 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"") ### dag\_to\_dagdependency 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"") ### dagdependency\_to\_dag 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"") ",repo/docs/api/qiskit/1.0\converters.mdx "--- title: dagcircuit description: API reference for qiskit.dagcircuit in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.dagcircuit --- # DAG Circuits `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 Base class for errors raised by the DAGCircuit object. Set the error message. ### DAGDependencyError Base class for errors raised by the DAGDependency object. Set the error message. ",repo/docs/api/qiskit/1.0\dagcircuit.mdx "--- title: exceptions description: API reference for qiskit.exceptions in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.exceptions --- # Top-level exceptions `qiskit.exceptions` ## Exceptions All Qiskit-related exceptions raised by Qiskit are subclasses of the base: ### QiskitError Base class for errors raised by Qiskit. Set the error message. 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. 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 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 Two more uncommon errors relate to failures in reading user-configuration files, or specifying a filename that cannot be used: ### QiskitUserConfigError Raised when an error is encountered reading a user config file. Set the error message. ### InvalidFileError Raised when the file provided is not valid for the specific task. Set the error message. ## 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 Common subclass of warnings for Qiskit-specific warnings being raised. 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 Raised when an optional library raises errors during its import. When experimental features are being used, Qiskit will raise [`ExperimentalWarning`](#qiskit.exceptions.ExperimentalWarning ""qiskit.exceptions.ExperimentalWarning""). Qiskit experimental features can break at any minor release and their API might change without previous notification. Their use is not recommended in production. ### ExperimentalWarning Raised when an experimental feature is being used. ### Filtering warnings Python has built-in mechanisms to filter warnings, described in the documentation of the [`warnings`](https://docs.python.org/3/library/warnings.html#module-warnings ""(in Python v3.12)"") module. You can use these subclasses in your warning filters from within Python to silence warnings you are not interested in. For example, if you are knowingly using experimental features and are comfortable that they make break in later versions, you can silence [`ExperimentalWarning`](#qiskit.exceptions.ExperimentalWarning ""qiskit.exceptions.ExperimentalWarning"") like this: ```python import warnings from qiskit.exceptions import ExperimentalWarning warnings.filterwarnings(""ignore"", category=ExperimentalWarning) ``` ",repo/docs/api/qiskit/1.0\exceptions.mdx "--- title: qiskit description: API reference for qiskit in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit --- # API Reference * [Quantum Circuits (`qiskit.circuit`)](circuit) * [Circuit Library (`qiskit.circuit.library`)](circuit_library) * [Classical expressions (`qiskit.circuit.classical`)](circuit_classical) * [Singleton instructions (`qiskit.circuit.singleton`)](circuit_singleton) * [Compilation Routines (`qiskit.compiler`)](compiler) * [Visualizations (`qiskit.visualization`)](visualization) * [ClassicalFunction compiler (`qiskit.circuit.classicalfunction`)](classicalfunction) * [Circuit Converters (`qiskit.converters`)](converters) * [Circuit and Schedule Assembler (`qiskit.assembler`)](assembler) * [DAG Circuits (`qiskit.dagcircuit`)](dagcircuit) * [Passmanager (`qiskit.passmanager`)](passmanager) * [Providers Interface (`qiskit.providers`)](providers) * [Writing a New Provider](providers#writing-a-new-provider) * [Migrating between Backend API Versions](providers#migrating-between-backend-api-versions) * [BasicProvider: Python-based Simulators (`qiskit.providers.basic_provider`)](providers_basic_provider) * [Fake Provider (`qiskit.providers.fake_provider`)](providers_fake_provider) * [Backend Objects (`qiskit.providers.models`)](providers_models) * [Pulse (`qiskit.pulse`)](pulse) * [Circuit Scheduler (`qiskit.scheduler`)](scheduler) * [Circuit Synthesis (`qiskit.synthesis`)](synthesis) * [Primitives (`qiskit.primitives`)](primitives) * [OpenQASM 2 (`qiskit.qasm2`)](qasm2) * [OpenQASM 3 (`qiskit.qasm3`)](qasm3) * [Qobj (`qiskit.qobj`)](qobj) * [QPY serialization (`qiskit.qpy`)](qpy) * [Quantum Information (`qiskit.quantum_info`)](quantum_info) * [Experiment Results (`qiskit.result`)](result) * [Transpiler (`qiskit.transpiler`)](transpiler) * [Transpiler Passes (`qiskit.transpiler.passes`)](transpiler_passes) * [Preset Passmanagers (`qiskit.transpiler.preset_passmanagers`)](transpiler_preset) * [Transpiler Stage Plugin Interface (`qiskit.transpiler.preset_passmanagers.plugin`)](transpiler_plugins) * [Synthesis Plugins (`qiskit.transpiler.passes.synthesis.plugin`)](transpiler_synthesis_plugins) * [Utilities (`qiskit.utils`)](utils) * [Top-level exceptions (`qiskit.exceptions`)](exceptions) ",repo/docs/api/qiskit/1.0\index.mdx "--- title: passmanager description: API reference for qiskit.passmanager in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.passmanager --- # 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. 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. The passes may consume the hardware constraints that the Qiskit backend may provide. Finally, the IR is converted back to some Python object. Note that the input type and output type are not necessarily the same. Compilation in the pass manager is a chain of `Task` executions that take an IR and output a new IR with some optimization or data analysis. An atomic task is a *pass* which is a subclass of [`GenericPass`](qiskit.passmanager.GenericPass ""qiskit.passmanager.GenericPass"") that implements a `run()` method that performs some work on the received IR. A set of passes may form a *flow controller*, which is a subclass of [`BaseController`](qiskit.passmanager.BaseController ""qiskit.passmanager.BaseController""), which can implement arbitrary compilation-state-dependent logic for deciding which pass will get run next. Passes share intermediate data via the [`PropertySet`](qiskit.passmanager.PropertySet ""qiskit.passmanager.PropertySet"") object which is a free-form dictionary. A pass can populate the property set dictionary during the task execution. A flow controller can also consume the property set to control the pass execution, but this access must be read-only. The property set is portable and handed over from pass to pass at execution. In addition to the property set, tasks also receive a [`WorkflowStatus`](qiskit.passmanager.WorkflowStatus ""qiskit.passmanager.WorkflowStatus"") data structure. This object is initialized when the pass manager is run and handed over to underlying tasks. The status is updated after every pass is run, and contains information about the pipeline state (number of passes run, failure state, and so on) as opposed to the [`PropertySet`](qiskit.passmanager.PropertySet ""qiskit.passmanager.PropertySet""), which contains information about the IR being optimized. A pass manager is a wrapper of the flow controller, with responsibilities of * Scheduling optimization tasks, * Converting an input Python object to a particular Qiskit IR, * Initializing a property set and workflow status, * Running scheduled tasks to apply a series of transformations to the IR, * Converting the IR back to an output Python object. This indicates that the flow controller itself is type-agnostic, and a developer must implement a subclass of the [`BasePassManager`](qiskit.passmanager.BasePassManager ""qiskit.passmanager.BasePassManager"") to manage the data conversion steps. This *veil of ignorance* allows us to choose the most efficient data representation for a particular pass manager task, while we can reuse the flow control machinery for different input and output types. A single flow controller always takes a single IR object, and returns a single IR object. Parallelism for multiple input objects is supported by the [`BasePassManager`](qiskit.passmanager.BasePassManager ""qiskit.passmanager.BasePassManager"") by broadcasting the flow controller via the [`parallel_map()`](utils#qiskit.utils.parallel_map ""qiskit.utils.parallel_map"") function. ## Examples We look into a toy optimization task, namely, preparing a row of numbers and remove a digit if the number is five. Such task might be easily done by converting the input numbers into string. We use the pass manager framework here, putting the efficiency aside for a moment to learn how to build a custom Qiskit compiler. ```python from qiskit.passmanager import BasePassManager, GenericPass, ConditionalController class ToyPassManager(BasePassManager): def _passmanager_frontend(self, input_program: int, **kwargs) -> str: return str(input_program) def _passmanager_backend(self, passmanager_ir: str, in_program: int, **kwargs) -> int: return int(passmanager_ir) ``` This pass manager inputs and outputs an integer number, while performing the optimization tasks on a string data. Hence, input, IR, output type are integer, string, integer, respectively. The `_passmanager_frontend()` method defines the conversion from the input data to IR, and `_passmanager_backend()` defines the conversion from the IR to output data. The pass manager backend is also given an `in_program` parameter that contains the original `input_program` to the front end, for referencing any original metadata of the input program for the final conversion. Next, we implement a pass that removes a digit when the number is five. ```python class RemoveFive(GenericPass): def run(self, passmanager_ir: str): return passmanager_ir.replace(""5"", """") task = RemoveFive() ``` Finally, we instantiate a pass manager and schedule the task with it. Running the pass manager with random row of numbers returns new numbers that don’t contain five. ```python pm = ToyPassManager() pm.append(task) pm.run([123456789, 45654, 36785554]) ``` Output: ```python [12346789, 464, 36784] ``` Now we consider the case of conditional execution. We avoid execution of the “remove five” task when the input number is six digits or less. Such control can be implemented by a flow controller. We start from an analysis pass that provides the flow controller with information about the number of digits. ```python class CountDigits(GenericPass): def run(self, passmanager_ir: str): self.property_set[""ndigits""] = len(passmanager_ir) analysis_task = CountDigits() ``` Then, we wrap the remove five task with the [`ConditionalController`](qiskit.passmanager.ConditionalController ""qiskit.passmanager.ConditionalController"") that runs the stored tasks only when the condition is met. ```python def digit_condition(property_set): # Return True when condition is met. return property_set[""ndigits""] > 6 conditional_task = ConditionalController( tasks=[RemoveFive()], condition=digit_condition, ) ``` As before, we schedule these passes with the pass manager and run. ```python pm = ToyPassManager() pm.append(analysis_task) pm.append(conditional_task) pm.run([123456789, 45654, 36785554]) ``` Output: ```python [12346789, 45654, 36784] ``` The “remove five” task is triggered only for the first and third input values, which have more than six digits. With the pass manager framework, a developer can flexibly customize the optimization task by combining multiple passes and flow controllers. See details for following class API documentations. ## Interface ### Base classes | | | | ---------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | | [`BasePassManager`](qiskit.passmanager.BasePassManager ""qiskit.passmanager.BasePassManager"")(\[tasks, max\_iteration]) | Pass manager base class. | | [`BaseController`](qiskit.passmanager.BaseController ""qiskit.passmanager.BaseController"")(\[options]) | Base class of controller. | | [`GenericPass`](qiskit.passmanager.GenericPass ""qiskit.passmanager.GenericPass"")() | Base class of a single pass manager task. | ### Flow controllers | | | | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | [`FlowControllerLinear`](qiskit.passmanager.FlowControllerLinear ""qiskit.passmanager.FlowControllerLinear"")(\[tasks, options]) | A standard flow controller that runs tasks one after the other. | | [`ConditionalController`](qiskit.passmanager.ConditionalController ""qiskit.passmanager.ConditionalController"")(\[tasks, condition, ...]) | A flow controller runs the pipeline once if the condition is true, or does nothing if the condition is false. | | [`DoWhileController`](qiskit.passmanager.DoWhileController ""qiskit.passmanager.DoWhileController"")(\[tasks, do\_while, options]) | Run the given tasks in a loop until the `do_while` condition on the property set becomes `False`. | ### Compilation state | | | | -------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | [`PropertySet`](qiskit.passmanager.PropertySet ""qiskit.passmanager.PropertySet"") | A default dictionary-like object. | | [`WorkflowStatus`](qiskit.passmanager.WorkflowStatus ""qiskit.passmanager.WorkflowStatus"")(\[count, completed\_passes, ...]) | Collection of compilation status of workflow, i.e. pass manager run. | | [`PassManagerState`](qiskit.passmanager.PassManagerState ""qiskit.passmanager.PassManagerState"")(workflow\_status, property\_set) | A portable container object that pass manager tasks communicate through generator. | ### Exceptions #### PassManagerError Pass manager error. Set the error message. ",repo/docs/api/qiskit/1.0\passmanager.mdx "--- title: primitives description: API reference for qiskit.primitives in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.primitives --- # 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 [ ] 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 [ [, # ], # [] ] 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 [ ] 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 [ , # , # ] job2 = estimator.run( [psi1, psi2, psi1], [H1, H2, H3], [theta1, theta2, theta3] ) job_result = job2.result() print(f""The primitive-job finished with result {job_result}"") ``` ## Overview of SamplerV1 Sampler class calculates probabilities or quasi-probabilities of bitstrings from quantum circuits. A sampler is initialized with an empty parameter set. The sampler is used to create a [`JobV1`](qiskit.providers.JobV1 ""qiskit.providers.JobV1""), via the [`qiskit.primitives.Sampler.run()`](qiskit.primitives.Sampler#run ""qiskit.primitives.Sampler.run"") method. This method is called with the following parameters * quantum circuits ($\psi_i(\theta)$): list of (parameterized) quantum circuits. (a list of [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") objects) * parameter values ($\theta_k$): list of sets of parameter values to be bound to the parameters of the quantum circuits. (list of list of float) The method returns a [`JobV1`](qiskit.providers.JobV1 ""qiskit.providers.JobV1"") object, calling [`qiskit.providers.JobV1.result()`](qiskit.providers.JobV1#result ""qiskit.providers.JobV1.result"") yields a [`SamplerResult`](qiskit.primitives.SamplerResult ""qiskit.primitives.SamplerResult"") object, which contains probabilities or quasi-probabilities of bitstrings, plus optional metadata like error bars in the samples. Here is an example of how sampler is used. ```python from qiskit.primitives import Sampler from qiskit import QuantumCircuit from qiskit.circuit.library import RealAmplitudes # a Bell circuit bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell.measure_all() # two parameterized circuits pqc = RealAmplitudes(num_qubits=2, reps=2) pqc.measure_all() pqc2 = RealAmplitudes(num_qubits=2, reps=3) pqc2.measure_all() theta1 = [0, 1, 1, 2, 3, 5] theta2 = [0, 1, 2, 3, 4, 5, 6, 7] # initialization of the sampler sampler = Sampler() # Sampler runs a job on the Bell circuit job = sampler.run( circuits=[bell], parameter_values=[[]], parameters=[[]] ) job_result = job.result() print([q.binary_probabilities() for q in job_result.quasi_dists]) # Sampler runs a job on the parameterized circuits job2 = sampler.run( circuits=[pqc, pqc2], parameter_values=[theta1, theta2], parameters=[pqc.parameters, pqc2.parameters]) job_result = job2.result() print([q.binary_probabilities() for q in job_result.quasi_dists]) ``` ## Migration from Primitives V1 to V2 The formal distinction between the Primitives V1 and V2 APIs are the base classes from which primitives implementations inherit, which are all listed at the bottom of the page. At a conceptual level, however, here are some notable differences keep in mind when migrating from V1 to V2: 1. The V2 primitives favour vectorized inputs, where single circuits can be grouped with vector-valued (or more generally, array-valued) specifications. Each group is called a primitive unified bloc (pub), and each pub gets its own result. For example, in the estimator, you can compare the following differences: ```python # Favoured V2 pattern. There is only one pub here, but there could be more. job = estimator_v2.run([(circuit, [obs1, obs2, obs3, obs4])]) evs = job.result()[0].data.evs # V1 equivalent, where the same circuit must be provided four times. job = estimator_v1.run([circuit] * 4, [obs1, obs2, obs3, obs4]) evs = job.result().values ``` Not shown in the above example, for brevity, is that the circuit can be parametric, with arrays of parameter value sets broadcasted against the array of observables. The sampler is similar, but with no observables: ```python # Favoured V2 pattern. There is only one pub here, but there could be more. job = sampler_v2.run([(circuit, [vals1, vals2, vals3])]) samples = job.result()[0].data # V1 equivalent, where the same circuit must be provided three times. sampler_v1.run([circuit] * 3, [vals1, vals2, vals3]) quasi_dists = job.result().quasi_dists ``` 2. The V2 sampler returns samples of classical outcomes, preserving the shot order in which they were measured. This is in contrast to the V1 sampler that outputs quasi-probability distributions which are instead an *estimate of the distribution* over classical outcomes. Moreover, the V2 sampler result objects organize data in terms of their input circuits’ classical register names, which provides natural compatibility with dynamic circuits. The closest analog of quasi-probability distributions in the V2 interface is the [`get_counts()`](qiskit.primitives.BitArray#get_counts ""qiskit.primitives.BitArray.get_counts"") method, shown in the example below. However, we emphasize that for utility scale experiments (100+ qubits), the chances of measuring the same bitstring twice are small, so that binning like counts in a dictionary format will not typically be an efficient data processing strategy. ```python circuit = QuantumCircuit(QuantumRegister(2, ""qreg""), ClassicalRegister(2, ""alpha"")) circuit.h(0) circuit.cx(0, 1) circuit.measure([0, 1], [0, 1]) # V1 sampler usage result = sampler_v1.run([circuit]).result() quasi_dist = result.quasi_dists[0] # V2 sampler usage result = sampler_v2.run([circuit]).result() # these are the bit values from the alpha register, over all shots bitvals = result[0].data.alpha # we can use it to generate a Counts mapping, which is similar to a quasi prob distribution counts = bitvals.get_counts() # which can in turn be converted to the V1 type through normalization quasi_dist = QuasiDistribution({outcome: freq / shots for outcome, freq in counts.items()}) ``` 3. The V2 primitives have brought the concept of sampling overhead, inherent to all quantum systems via their inherent probabilistic nature, out of the options and into the API itself. For the sampler, this means that the `shots` argument is now part of the [`run()`](qiskit.primitives.BaseSamplerV2#run ""qiskit.primitives.BaseSamplerV2.run"") signature, and moreover that each pub is able to specify its own value for `shots`, which takes precedence over any value given to the method. The sampler has an analogous `precision` argument that specifies the error bars that the primitive implementation should target for expectation values estimates. This concept is not present in the API of the V1 primitives, though all implementations of the V1 primitives have related settings somewhere in their options. ```python # Sample two circuits at 128 shots each. sampler_v2.run([circuit1, circuit2], shots=128) # Sample two circuits at different amounts of shots. The ""None""s are necessary as placeholders # for the lack of parameter values in this example. sampler_v2.run([(circuit1, None, 123), (circuit2, None, 456)]) # Estimate expectation values for two pubs, both with 0.05 precision. estimator_v2.run([(circuit1, obs_array1), (circuit2, obs_array_2)], precision=0.05) ``` ## Primitives API ### Primitives V2 | | | | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | [`BaseEstimatorV2`](qiskit.primitives.BaseEstimatorV2 ""qiskit.primitives.BaseEstimatorV2"")() | Estimator V2 base class. | | [`StatevectorEstimator`](qiskit.primitives.StatevectorEstimator ""qiskit.primitives.StatevectorEstimator"")(\*\[, default\_precision, ...]) | Simple implementation of [`BaseEstimatorV2`](qiskit.primitives.BaseEstimatorV2 ""qiskit.primitives.BaseEstimatorV2"") with full state vector simulation. | ### Sampler V2 | | | | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | [`BaseSamplerV2`](qiskit.primitives.BaseSamplerV2 ""qiskit.primitives.BaseSamplerV2"")() | Sampler V2 base class. | | [`StatevectorSampler`](qiskit.primitives.StatevectorSampler ""qiskit.primitives.StatevectorSampler"")(\*\[, default\_shots, seed]) | Simple implementation of [`BaseSamplerV2`](qiskit.primitives.BaseSamplerV2 ""qiskit.primitives.BaseSamplerV2"") using full state vector simulation. | ### Results V2 | | | | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | [`BitArray`](qiskit.primitives.BitArray ""qiskit.primitives.BitArray"")(array, num\_bits) | Stores an array of bit values. | | [`DataBin`](qiskit.primitives.DataBin ""qiskit.primitives.DataBin"")() | Base class for data bin containers. | | [`PrimitiveResult`](qiskit.primitives.PrimitiveResult ""qiskit.primitives.PrimitiveResult"")(pub\_results\[, metadata]) | A container for multiple pub results and global metadata. | | [`PubResult`](qiskit.primitives.PubResult ""qiskit.primitives.PubResult"")(data\[, metadata]) | Result of Primitive Unified Bloc. | | [`BasePrimitiveJob`](qiskit.primitives.BasePrimitiveJob ""qiskit.primitives.BasePrimitiveJob"")(job\_id, \*\*kwargs) | Primitive job abstract base class. | | [`PrimitiveJob`](qiskit.primitives.PrimitiveJob ""qiskit.primitives.PrimitiveJob"")(function, \*args, \*\*kwargs) | Primitive job class for the reference implementations of Primitives. | ### Estimator V1 | | | | ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | [`BaseEstimator`](qiskit.primitives.BaseEstimator ""qiskit.primitives.BaseEstimator"") | alias of [`BaseEstimatorV1`](qiskit.primitives.BaseEstimatorV1 ""qiskit.primitives.base.base_estimator.BaseEstimatorV1"") | | [`BaseEstimatorV1`](qiskit.primitives.BaseEstimatorV1 ""qiskit.primitives.BaseEstimatorV1"")(\*\[, options]) | Estimator V1 base class. | | [`Estimator`](qiskit.primitives.Estimator ""qiskit.primitives.Estimator"")(\*\[, options]) | Reference implementation of [`BaseEstimator`](qiskit.primitives.BaseEstimator ""qiskit.primitives.BaseEstimator""). | | [`BackendEstimator`](qiskit.primitives.BackendEstimator ""qiskit.primitives.BackendEstimator"")(backend\[, options, ...]) | Evaluates expectation value using Pauli rotation gates. | | [`EstimatorResult`](qiskit.primitives.EstimatorResult ""qiskit.primitives.EstimatorResult"")(values, metadata) | Result of Estimator. | ### Sampler V1 | | | | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | [`BaseSampler`](qiskit.primitives.BaseSampler ""qiskit.primitives.BaseSampler"") | alias of [`BaseSamplerV1`](qiskit.primitives.BaseSamplerV1 ""qiskit.primitives.base.base_sampler.BaseSamplerV1"") | | [`BaseSamplerV1`](qiskit.primitives.BaseSamplerV1 ""qiskit.primitives.BaseSamplerV1"")(\*\[, options]) | Sampler V1 base class | | [`Sampler`](qiskit.primitives.Sampler ""qiskit.primitives.Sampler"")(\*\[, options]) | Sampler class. | | [`BackendSampler`](qiskit.primitives.BackendSampler ""qiskit.primitives.BackendSampler"")(backend\[, options, ...]) | A `BaseSampler` implementation that provides an interface for leveraging the sampler interface from any backend. | | [`SamplerResult`](qiskit.primitives.SamplerResult ""qiskit.primitives.SamplerResult"")(quasi\_dists, metadata) | Result of Sampler. | ",repo/docs/api/qiskit/1.0\primitives.mdx "--- title: providers description: API reference for qiskit.providers in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.providers --- # Providers Interface `qiskit.providers` This module contains the classes used to build external providers for Terra. A provider is anything that provides an external service to Terra. The typical example of this is a Backend provider which provides [`Backend`](qiskit.providers.Backend ""qiskit.providers.Backend"") objects which can be used for executing [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") and/or [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") objects. This module contains the abstract classes which are used to define the interface between a provider and terra. ## Version Support Each providers interface abstract class is individually versioned. When we need to make a change to an interface a new abstract class will be created to define the new interface. These interface changes are not guaranteed to be backwards compatible between versions. ### Version Changes Each minor version release of qiskit-terra **may** increment the version of any providers interface a single version number. It will be an aggregate of all the interface changes for that release on that interface. ### Version Support Policy To enable providers to have time to adjust to changes in this interface Terra will support multiple versions of each class at once. Given the nature of one version per release the version deprecation policy is a bit more conservative than the standard deprecation policy. Terra will support a provider interface version for a minimum of 3 minor releases or the first release after 6 months from the release that introduced a version, whichever is longer, prior to a potential deprecation. After that the standard deprecation policy will apply to that interface version. This will give providers and users sufficient time to adapt to potential breaking changes in the interface. So for example lets say in 0.19.0 `BackendV2` is introduced and in the 3 months after the release of 0.19.0 we release 0.20.0, 0.21.0, and 0.22.0, then 7 months after 0.19.0 we release 0.23.0. In 0.23.0 we can deprecate BackendV2, and it needs to still be supported and can’t be removed until the deprecation policy completes. It’s worth pointing out that Terra’s version support policy doesn’t mean providers themselves will have the same support story, they can (and arguably should) update to newer versions as soon as they can, the support window is just for Terra’s supported versions. Part of this lengthy window prior to deprecation is to give providers enough time to do their own deprecation of a potential end user impacting change in a user facing part of the interface prior to bumping their version. For example, let’s say we changed the signature to `Backend.run()` in `BackendV34` in a backwards incompatible way. Before Aer could update its [`AerSimulator`](https://qiskit.github.io/qiskit-aer/stubs/qiskit_aer.AerSimulator.html#qiskit_aer.AerSimulator ""(in Qiskit Aer v0.14.0)"") class to be based on version 34 they’d need to deprecate the old signature prior to switching over. The changeover for Aer is not guaranteed to be lockstep with Terra so we need to ensure there is a sufficient amount of time for Aer to complete its deprecation cycle prior to removing version 33 (ie making version 34 mandatory/the minimum version). ## Abstract Classes ### Provider | | | | --------------------------------------------------------------------------- | ------------------------------------------------------------- | | [`Provider`](qiskit.providers.Provider ""qiskit.providers.Provider"")() | Base common type for all versioned Provider abstract classes. | | [`ProviderV1`](qiskit.providers.ProviderV1 ""qiskit.providers.ProviderV1"")() | Base class for a Backend Provider. | ### Backend | | | | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [`Backend`](qiskit.providers.Backend ""qiskit.providers.Backend"")() | Base common type for all versioned Backend abstract classes. | | [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"")(configuration\[, provider]) | Abstract class for Backends | | [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"")(\[provider, name, description, ...]) | Abstract class for Backends | | [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"")(\[t1, t2, frequency]) | A representation of the properties of a qubit on a backend. | | [`BackendV2Converter`](qiskit.providers.BackendV2Converter ""qiskit.providers.BackendV2Converter"")(backend\[, name\_mapping, ...]) | A converter class that takes a [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") instance and wraps it in a [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") interface. | | [`convert_to_target`](qiskit.providers.convert_to_target ""qiskit.providers.convert_to_target"")(configuration\[, ...]) | Decode transpiler target from backend data set. | ### Options | | | | ---------------------------------------------------------------------------- | ------------------- | | [`Options`](qiskit.providers.Options ""qiskit.providers.Options"")(\*\*kwargs) | Base options object | ### Job | | | | ---------------------------------------------------------------------------------------- | -------------------------------------------------------- | | [`Job`](qiskit.providers.Job ""qiskit.providers.Job"")() | Base common type for all versioned Job abstract classes. | | [`JobV1`](qiskit.providers.JobV1 ""qiskit.providers.JobV1"")(backend, job\_id, \*\*kwargs) | Class to handle jobs | ### Job Status | | | | ----------------------------------------------------------------------------- | ------------------------------------- | | [`JobStatus`](qiskit.providers.JobStatus ""qiskit.providers.JobStatus"")(value) | Class for job status enumerated type. | ### Exceptions #### QiskitBackendNotFoundError Base class for errors raised while looking for a backend. Set the error message. #### BackendPropertyError Base class for errors raised while looking for a backend property. Set the error message. #### JobError Base class for errors raised by Jobs. Set the error message. #### JobTimeoutError Base class for timeout errors raised by jobs. Set the error message. #### BackendConfigurationError Base class for errors raised by the BackendConfiguration. Set the error message. # Writing a New Provider If you have a quantum device or simulator that you would like to integrate with Qiskit you will need to write a provider. A provider will provide Terra with a method to get available [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") objects. The [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") object provides both information describing a backend and its operation for the [`transpiler`](transpiler#module-qiskit.transpiler ""qiskit.transpiler"") so that circuits can be compiled to something that is optimized and can execute on the backend. It also provides the [`run()`](qiskit.providers.BackendV2#run ""qiskit.providers.BackendV2.run"") method which can run the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") objects and/or [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") objects. This enables users and other Qiskit APIs to get results from executing circuits on devices in a standard fashion regardless of how the backend is implemented. At a high level the basic steps for writing a provider are: > * Implement a [`ProviderV1`](qiskit.providers.ProviderV1 ""qiskit.providers.ProviderV1"") subclass that handles access to the backend(s). > > * Implement a [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") subclass and its [`run()`](qiskit.providers.BackendV2#run ""qiskit.providers.BackendV2.run"") method. > > * Add any custom gates for the backend’s basis to the session [`EquivalenceLibrary`](qiskit.circuit.EquivalenceLibrary ""qiskit.circuit.EquivalenceLibrary"") instance. > > * Implement a [`JobV1`](qiskit.providers.JobV1 ""qiskit.providers.JobV1"") subclass that handles interacting with a running job. For a simple example of a provider, see the [qiskit-aqt-provider](https://github.com/Qiskit-Partners/qiskit-aqt-provider) ## 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. ## 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. #### Custom Basis Gates 1. If your backend doesn’t use gates in the Qiskit circuit library ([`qiskit.circuit.library`](circuit_library#module-qiskit.circuit.library ""qiskit.circuit.library"")) you can integrate support for this into your provider. The basic method for doing this is first to define a [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") subclass for each custom gate in the basis set. For example: ```python import numpy as np from qiskit.circuit import Gate from qiskit.circuit import QuantumCircuit class SYGate(Gate): def __init__(self, label=None): super().__init__(""sy"", 1, [], label=label) def _define(self): qc = QuantumCircuit(1) q.ry(np.pi / 2, 0) self.definition = qc ``` The key thing to ensure is that for any custom gates in your Backend’s basis set your custom gate’s name attribute (the first param on `super().__init__()` in the `__init__` definition above) does not conflict with the name of any other gates. The name attribute is what is used to identify the gate in the basis set for the transpiler. If there is a conflict the transpiler will not know which gate to use. 2. Add the custom gate to the target for your backend. This can be done with the [`Target.add_instruction()`](qiskit.transpiler.Target#add_instruction ""qiskit.transpiler.Target.add_instruction"") method. You’ll need to add an instance of `SYGate` and its parameters to the target so the transpiler knows it exists. For example, assuming this is part of your [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") implementation for your backend: ```python from qiskit.transpiler import InstructionProperties sy_props = { (0,): InstructionProperties(duration=2.3e-6, error=0.0002) (1,): InstructionProperties(duration=2.1e-6, error=0.0001) (2,): InstructionProperties(duration=2.5e-6, error=0.0003) (3,): InstructionProperties(duration=2.2e-6, error=0.0004) } self.target.add_instruction(SYGate(), sy_props) ``` The keys in `sy_props` define the qubits where the backend `SYGate` can be used on, and the values define the properties of `SYGate` on that qubit. For multiqubit gates the tuple keys contain all qubit combinations the gate works on (order is significant, i.e. `(0, 1)` is different from `(1, 0)`). 3. After you’ve defined the custom gates to use for the backend’s basis set then you need to add equivalence rules to the standard equivalence library so that the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") function and [`transpiler`](transpiler#module-qiskit.transpiler ""qiskit.transpiler"") module can convert an arbitrary circuit using the custom basis set. This can be done by defining equivalent circuits, in terms of the custom gate, for standard gates. Typically if you can convert from a [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"") (if your basis doesn’t include a standard 2 qubit gate) and some commonly used single qubit rotation gates like the [`HGate`](qiskit.circuit.library.HGate ""qiskit.circuit.library.HGate"") and [`UGate`](qiskit.circuit.library.UGate ""qiskit.circuit.library.UGate"") that should be sufficient for the transpiler to translate any circuit into the custom basis gates. But, the more equivalence rules that are defined from standard gates to your basis the more efficient translation from an arbitrary circuit to the target basis will be (although not always, and there is a diminishing margin of return). For example, if you were to add some rules for the above custom `SYGate` we could define the [`U2Gate`](qiskit.circuit.library.U2Gate ""qiskit.circuit.library.U2Gate"") and [`HGate`](qiskit.circuit.library.HGate ""qiskit.circuit.library.HGate""): ```python from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary from qiskit.circuit.library import HGate from qiskit.circuit.library import ZGate from qiskit.circuit.library import RZGate from qiskit.circuit.library import U2Gate # H => Z SY q = qiskit.QuantumRegister(1, ""q"") def_sy_h = qiskit.QuantumCircuit(q) def_sy_h.append(ZGate(), [q[0]], []) def_sy_h.append(SYGate(), [q[0]], []) SessionEquivalenceLibrary.add_equivalence( HGate(), def_sy_h) # u2 => Z SY Z phi = qiskit.circuit.Parameter('phi') lam = qiskit.circuit.Parameter('lambda') q = qiskit.QuantumRegister(1, ""q"") def_sy_u2 = qiskit.QuantumCircuit(q) def_sy_u2.append(RZGate(lam), [q[0]], []) def_sy_u2.append(SYGate(), [q[0]], []) def_sy_u2.append(RZGate(phi), [q[0]], []) SessionEquivalenceLibrary.add_equivalence( U2Gate(phi, lam), def_sy_u2) ``` You will want this to be run on import so that as soon as the provider’s package is imported it will be run. This will ensure that any time the [`BasisTranslator`](qiskit.transpiler.passes.BasisTranslator ""qiskit.transpiler.passes.BasisTranslator"") pass is run with the custom gates the equivalence rules are defined. It’s also worth noting that depending on the basis you’re using, some optimization passes in the transpiler, such as [`Optimize1qGatesDecomposition`](qiskit.transpiler.passes.Optimize1qGatesDecomposition ""qiskit.transpiler.passes.Optimize1qGatesDecomposition""), may not be able to operate with your custom basis. For our `SYGate` example, the [`Optimize1qGatesDecomposition`](qiskit.transpiler.passes.Optimize1qGatesDecomposition ""qiskit.transpiler.passes.Optimize1qGatesDecomposition"") will not be able to simplify runs of single qubit gates into the SY basis. This is because the `OneQubitEulerDecomposer` class does not know how to work in the SY basis. To solve this the `SYGate` class would need to be added to Qiskit and `OneQubitEulerDecomposer` updated to support decomposing to the `SYGate`. Longer term that is likely a better direction for custom basis gates and contributing the definitions and support in the transpiler will ensure that it continues to be well supported by Qiskit moving forward. #### Custom Transpiler Passes The transpiler supports the ability for backends to provide custom transpiler stage implementations to facilitate hardware specific optimizations and circuit transformations. Currently there are two stages supported, `get_translation_stage_plugin()` and `get_scheduling_stage_plugin()` which allow a backend to specify string plugin names to be used as the default translation and scheduling stages, respectively. These hook points in a [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") class can be used if your backend has requirements for compilation that are not met by the current backend/[`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") interface. Please also consider submitting a Github issue describing your use case as there is interest in improving these interfaces to be able to describe more hardware architectures in greater depth. To leverage these hook points you just need to add the methods to your [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") implementation and have them return a string plugin name. For example: ```python class Mybackend(BackendV2): def get_scheduling_stage_plugin(self): return ""SpecialDD"" def get_translation_stage_plugin(self): return ""BasisTranslatorWithCustom1qOptimization"" ``` This snippet of a backend implementation will now have the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") function use the `SpecialDD` plugin for the scheduling stage and the `BasisTranslatorWithCustom1qOptimization` plugin for the translation stage by default when the target is set to `Mybackend`. Note that users may override these choices by explicitly selecting a different plugin name. For this interface to work though transpiler stage plugins must be implemented for the returned plugin name. You can refer to [`qiskit.transpiler.preset_passmanagers.plugin`](transpiler_plugins#module-qiskit.transpiler.preset_passmanagers.plugin ""qiskit.transpiler.preset_passmanagers.plugin"") module documentation for details on how to implement plugins. The typical expectation is that if your backend requires custom passes as part of a compilation stage the provider package will include the transpiler stage plugins that use those passes. However, this is not required and any valid method (from a built-in method or external plugin) can be used. This way if these two compilation steps are **required** for running or providing efficient output on `Mybackend` the transpiler will be able to perform these custom steps without any manual user input. ### Run Method Of key importance is the [`run()`](qiskit.providers.BackendV2#run ""qiskit.providers.BackendV2.run"") method, which is used to actually submit circuits to a device or simulator. The run method handles submitting the circuits to the backend to be executed and returning a [`Job`](qiskit.providers.Job ""qiskit.providers.Job"") object. Depending on the type of backend this typically involves serializing the circuit object into the API format used by a backend. For example, on IBM backends from the `qiskit-ibm-provider` package this involves converting from a quantum circuit and options into a [`qpy`](qpy#module-qiskit.qpy ""qiskit.qpy"") payload embedded in JSON and submitting that to the IBM Quantum API. Since every backend interface is different (and in the case of the local simulators serialization may not be needed) it is expected that the backend’s [`run`](qiskit.providers.BackendV2#run ""qiskit.providers.BackendV2.run"") method will handle this conversion. An example run method would be something like: ```python def run(self, circuits. **kwargs): for kwarg in kwargs: if not hasattr(kwarg, self.options): warnings.warn( ""Option %s is not used by this backend"" % kwarg, UserWarning, stacklevel=2) options = { 'shots': kwargs.get('shots', self.options.shots) 'memory': kwargs.get('memory', self.options.shots), } job_json = convert_to_wire_format(circuit, options) job_handle = submit_to_backend(job_jsonb) return MyJob(self. job_handle, job_json, circuit) ``` ### Options There are often several options for a backend that control how a circuit is run. The typical example of this is something like the number of `shots` which is how many times the circuit is to be executed. The options available for a backend are defined using an [`Options`](qiskit.providers.Options ""qiskit.providers.Options"") object. This object is initially created by the [`_default_options`](qiskit.providers.BackendV2#_default_options ""qiskit.providers.BackendV2._default_options"") method of a Backend class. The default options returns an initialized [`Options`](qiskit.providers.Options ""qiskit.providers.Options"") object with all the default values for all the options a backend supports. For example, if the backend supports only supports `shots` the [`_default_options`](qiskit.providers.BackendV2#_default_options ""qiskit.providers.BackendV2._default_options"") method would look like: ```python @classmethod def _default_options(cls): return Options(shots=1024) ``` You can also set validators on an [`Options`](qiskit.providers.Options ""qiskit.providers.Options"") object to provide limits and validation on user provided values based on what’s acceptable for your backend. For example, if the `""shots""` option defined above can be set to any value between 1 and 4096 you can set the validator on the options object for you backend with: ```python self.options.set_validator(""shots"", (1, 4096)) ``` you can refer to the [`set_validator()`](qiskit.providers.Options#set_validator ""qiskit.providers.Options.set_validator"") documentation for a full list of validation options. ## Job The output from the [`run`](qiskit.providers.BackendV2#run ""qiskit.providers.BackendV2.run"") method is a [`JobV1`](qiskit.providers.JobV1 ""qiskit.providers.JobV1"") object. Each provider is expected to implement a custom job subclass that defines the behavior for the provider. There are 2 types of jobs depending on the backend’s execution method, either a sync or async. By default jobs are considered async and the expectation is that it represents a handle to the async execution of the circuits submitted with `Backend.run()`. An async job object provides users the ability to query the status of the execution, cancel a running job, and block until the execution is finished. The [`result`](qiskit.providers.JobV1#result ""qiskit.providers.JobV1.result"") is the primary user facing method which will block until the execution is complete and then will return a [`Result`](qiskit.result.Result ""qiskit.result.Result"") object with results of the job. For some backends (mainly local simulators) the execution of circuits is a synchronous operation and there is no need to return a handle to a running job elsewhere. For sync jobs its expected that the [`run`](qiskit.providers.BackendV1#run ""qiskit.providers.BackendV1.run"") method on the backend will block until a [`Result`](qiskit.result.Result ""qiskit.result.Result"") object is generated and the sync job will return with that inner [`Result`](qiskit.result.Result ""qiskit.result.Result"") object. An example job class for an async API based backend would look something like: ```python from qiskit.providers import JobV1 as Job from qiskit.providers import JobError from qiskit.providers import JobTimeoutError from qiskit.providers.jobstatus import JobStatus from qiskit.result import Result class MyJob(Job): def __init__(self, backend, job_id, job_json, circuits): super().__init__(backend, job_id) self._backend = backend self.job_json = job_json self.circuits = circuits def _wait_for_result(self, timeout=None, wait=5): start_time = time.time() result = None while True: elapsed = time.time() - start_time if timeout and elapsed >= timeout: raise JobTimeoutError('Timed out waiting for result') result = get_job_status(self._job_id) if result['status'] == 'complete': break if result['status'] == 'error': raise JobError('Job error') time.sleep(wait) return result def result(self, timeout=None, wait=5): result = self._wait_for_result(timeout, wait) results = [{'success': True, 'shots': len(result['counts']), 'data': result['counts']}] return Result.from_dict({ 'results': results, 'backend_name': self._backend.configuration().backend_name, 'backend_version': self._backend.configuration().backend_version, 'job_id': self._job_id, 'qobj_id': ', '.join(x.name for x in self.circuits), 'success': True, }) def status(self): result = get_job_status(self._job_id) if result['status'] == 'running': status = JobStatus.RUNNING elif result['status'] == 'complete': status = JobStatus.DONE else: status = JobStatus.ERROR return status def submit(self): raise NotImplementedError ``` and for a sync job: ```python class MySyncJob(Job): _async = False def __init__(self, backend, job_id, result): super().__init__(backend, job_id) self._result = result def submit(self): return def result(self): return self._result def status(self): return JobStatus.DONE ``` ## Primitives While not directly part of the provider interface, the [`qiskit.primitives`](primitives#module-qiskit.primitives ""qiskit.primitives"") module is tightly coupled with providers. Specifically the primitive interfaces, such as `BaseSampler` and `BaseEstimator`, are designed to enable provider implementations to provide custom implementations which are optimized for the provider’s backends. This can include customizations like circuit transformations, additional pre- and post-processing, batching, caching, error mitigation, etc. The concept of the [`qiskit.primitives`](primitives#module-qiskit.primitives ""qiskit.primitives"") module is to explicitly enable this as the primitive objects are higher level abstractions to produce processed higher level outputs (such as probability distributions and expectation values) that abstract away the mechanics of getting the best result efficiently, to concentrate on higher level applications using these outputs. For example, if your backends were well suited to leverage [mthree](https://github.com/Qiskit-Partners/mthree/) measurement mitigation to improve the quality of the results, you could implement a provider-specific [`Sampler`](qiskit.primitives.Sampler ""qiskit.primitives.Sampler"") implementation that leverages the `M3Mitigation` class internally to run the circuits and return quasi-probabilities directly from mthree in the result. Doing this would enable algorithms to get the best results with mitigation applied directly from your backends. You can refer to the documentation in [`qiskit.primitives`](primitives#module-qiskit.primitives ""qiskit.primitives"") on how to write custom implementations. Also the built-in implementations: [`Sampler`](qiskit.primitives.Sampler ""qiskit.primitives.Sampler""), [`Estimator`](qiskit.primitives.Estimator ""qiskit.primitives.Estimator""), [`BackendSampler`](qiskit.primitives.BackendSampler ""qiskit.primitives.BackendSampler""), and [`BackendEstimator`](qiskit.primitives.BackendEstimator ""qiskit.primitives.BackendEstimator"") can serve as references/models on how to implement these as well. # Migrating between Backend API Versions ## BackendV1 -> BackendV2 The [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") class re-defined user access for most properties of a backend to make them work with native Qiskit data structures and have flatter access patterns. However this means when using a provider that upgrades from [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") to [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") existing access patterns will need to be adjusted. It is expected for existing providers to deprecate the old access where possible to provide a graceful migration, but eventually users will need to adjust code. The biggest change to adapt to in [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") is that most of the information accessible about a backend is contained in its [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object and the backend’s attributes often query its [`target`](qiskit.providers.BackendV2#target ""qiskit.providers.BackendV2.target"") attribute to return information, however in many cases the attributes only provide a subset of information the target can contain. For example, `backend.coupling_map` returns a [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") constructed from the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") accessible in the [`target`](qiskit.providers.BackendV2#target ""qiskit.providers.BackendV2.target"") attribute, however the target may contain instructions that operate on more than two qubits (which can’t be represented in a [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")) or has instructions that only operate on a subset of qubits (or two qubit links for a two qubit instruction) which won’t be detailed in the full coupling map returned by [`coupling_map`](qiskit.providers.BackendV2#coupling_map ""qiskit.providers.BackendV2.coupling_map""). So depending on your use case it might be necessary to look deeper than just the equivalent access with [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2""). Below is a table of example access patterns in [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") and the new form with [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2""): | [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") | [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") | Notes | | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `backend.configuration().n_qubits` | `backend.num_qubits` | | | `backend.configuration().coupling_map` | `backend.coupling_map` | The return from [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") is a [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") object. while in [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") it is an edge list. Also this is just a view of the information contained in `backend.target` which may only be a subset of the information contained in [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object. | | `backend.configuration().backend_name` | `backend.name` | | | `backend.configuration().backend_version` | `backend.backend_version` | The [`version`](qiskit.providers.BackendV2#version ""qiskit.providers.BackendV2.version"") attribute represents the version of the abstract [`Backend`](qiskit.providers.Backend ""qiskit.providers.Backend"") interface the object implements while [`backend_version`](qiskit.providers.BackendV2#backend_version ""qiskit.providers.BackendV2.backend_version"") is metadata about the version of the backend itself. | | `backend.configuration().basis_gates` | `backend.operation_names` | The [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") return is a list of operation names contained in the `backend.target` attribute. The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") may contain more information that can be expressed by this list of names. For example, that some operations only work on a subset of qubits or that some names implement the same gate with different parameters. | | `backend.configuration().dt` | `backend.dt` | | | `backend.configuration().dtm` | `backend.dtm` | | | `backend.configuration().max_experiments` | `backend.max_circuits` | | | `backend.configuration().online_date` | `backend.online_date` | | | `InstructionDurations.from_backend(backend)` | `backend.instruction_durations` | | | `backend.defaults().instruction_schedule_map` | `backend.instruction_schedule_map` | | | `backend.properties().t1(0)` | `backend.qubit_properties(0).t1` | | | `backend.properties().t2(0)` | `backend.qubit_properties(0).t2` | | | `backend.properties().frequency(0)` | `backend.qubit_properties(0).frequency` | | | `backend.properties().readout_error(0)` | `backend.target[""measure""][(0,)].error` | In [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") the error rate for the [`Measure`](qiskit.circuit.library.Measure ""qiskit.circuit.library.Measure"") operation on a given qubit is used to model the readout error. However a [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") can implement multiple measurement types and list them separately in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target""). | | `backend.properties().readout_length(0)` | `backend.target[""measure""][(0,)].duration` | In [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") the duration for the [`Measure`](qiskit.circuit.library.Measure ""qiskit.circuit.library.Measure"") operation on a given qubit is used to model the readout length. However, a [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") can implement multiple measurement types and list them separately in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target""). | There is also a [`BackendV2Converter`](qiskit.providers.BackendV2Converter ""qiskit.providers.BackendV2Converter"") class available that enables you to wrap a [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") object with a [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") interface. ",repo/docs/api/qiskit/1.0\providers.mdx "--- title: basic_provider description: API reference for qiskit.providers.basic_provider in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.providers.basic_provider --- # BasicProvider: Python-based Simulators `qiskit.providers.basic_provider` A module of Python-based quantum simulators. Simulators can be accessed via the BasicProvider provider, e.g.: ```python from qiskit.providers.basic_provider import BasicProvider backend = BasicProvider().get_backend('basic_simulator') ``` ## Simulators | | | | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | [`BasicSimulator`](qiskit.providers.basic_provider.BasicSimulator ""qiskit.providers.basic_provider.BasicSimulator"")(\[provider, target]) | Python implementation of a basic (non-efficient) quantum simulator. | ## Provider | | | | ------------------------------------------------------------------------------------------------------------------ | ----------------------------- | | [`BasicProvider`](qiskit.providers.basic_provider.BasicProvider ""qiskit.providers.basic_provider.BasicProvider"")() | Provider for test simulators. | ## Job Class | | | | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | [`BasicProviderJob`](qiskit.providers.basic_provider.BasicProviderJob ""qiskit.providers.basic_provider.BasicProviderJob"")(backend, job\_id, result) | BasicProviderJob class. | ## Exceptions | | | | ------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | | [`BasicProviderError`](qiskit.providers.basic_provider.BasicProviderError ""qiskit.providers.basic_provider.BasicProviderError"")(\*message) | Base class for errors raised by the Basic Provider. | ",repo/docs/api/qiskit/1.0\providers_basic_provider.mdx "--- title: fake_provider description: API reference for qiskit.providers.fake_provider in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.providers.fake_provider --- # 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 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 ### FakeQasmBackend 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 ### FakePulseBackend 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 ",repo/docs/api/qiskit/1.0\providers_fake_provider.mdx "--- title: models description: API reference for qiskit.providers.models in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.providers.models --- # Backend Objects `qiskit.providers.models` Qiskit schema-conformant objects used by the backends and providers. ## Backend Objects | | | | -------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | [`BackendConfiguration`](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"")(backend\_name, ...\[, ...]) | Backwards compat shim representing an abstract backend configuration. | | [`BackendProperties`](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"")(backend\_name, ...) | Class representing backend properties | | [`BackendStatus`](qiskit.providers.models.BackendStatus ""qiskit.providers.models.BackendStatus"")(backend\_name, backend\_version, ...) | Class representing Backend Status. | | [`QasmBackendConfiguration`](qiskit.providers.models.QasmBackendConfiguration ""qiskit.providers.models.QasmBackendConfiguration"")(backend\_name, ...) | Class representing an OpenQASM 2.0 Backend Configuration. | | [`PulseBackendConfiguration`](qiskit.providers.models.PulseBackendConfiguration ""qiskit.providers.models.PulseBackendConfiguration"")(backend\_name, ...) | Static configuration state for an OpenPulse enabled backend. | | [`UchannelLO`](qiskit.providers.models.UchannelLO ""qiskit.providers.models.UchannelLO"")(q, scale) | Class representing a U Channel LO | | [`GateConfig`](qiskit.providers.models.GateConfig ""qiskit.providers.models.GateConfig"")(name, parameters, qasm\_def\[, ...]) | Class representing a Gate Configuration | | [`PulseDefaults`](qiskit.providers.models.PulseDefaults ""qiskit.providers.models.PulseDefaults"")(qubit\_freq\_est, meas\_freq\_est, ...) | Description of default settings for Pulse systems. | | [`Command`](qiskit.providers.models.Command ""qiskit.providers.models.Command"")(name\[, qubits, sequence]) | Class representing a Command. | | [`JobStatus`](qiskit.providers.models.JobStatus ""qiskit.providers.models.JobStatus"")(job\_id, status, status\_msg, \*\*kwargs) | Model for JobStatus. | | [`GateProperties`](qiskit.providers.models.GateProperties ""qiskit.providers.models.GateProperties"")(qubits, gate, parameters, ...) | Class representing a gate's properties | | [`Nduv`](qiskit.providers.models.Nduv ""qiskit.providers.models.Nduv"")(date, name, unit, value) | Class representing name-date-unit-value | ",repo/docs/api/qiskit/1.0\providers_models.mdx "--- title: pulse description: API reference for qiskit.pulse in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.pulse --- # Pulse `qiskit.pulse` Qiskit-Pulse is a pulse-level quantum programming kit. This lower level of programming offers the user more control than programming with [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")s. Extracting the greatest performance from quantum hardware requires real-time pulse-level instructions. Pulse answers that need: it enables the quantum physicist *user* to specify the exact time dynamics of an experiment. It is especially powerful for error mitigation techniques. The input is given as arbitrary, time-ordered signals (see: [Instructions](#pulse-insts)) scheduled in parallel over multiple virtual hardware or simulator resources (see: [Channels](#pulse-channels)). The system also allows the user to recover the time dynamics of the measured output. This is sufficient to allow the quantum physicist to explore and correct for noise in a quantum system. ## Instructions `qiskit.pulse.instructions` The `instructions` module holds the various [`Instruction`](#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.Instruction"")s which are supported by Qiskit Pulse. Instructions have operands, which typically include at least one [`Channel`](#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") specifying where the instruction will be applied. Every instruction has a duration, whether explicitly included as an operand or implicitly defined. For instance, a [`ShiftPhase`](qiskit.pulse.instructions.ShiftPhase ""qiskit.pulse.instructions.ShiftPhase"") instruction can be instantiated with operands *phase* and *channel*, for some float `phase` and a [`Channel`](#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") `channel`: ```python ShiftPhase(phase, channel) ``` The duration of this instruction is implicitly zero. On the other hand, the [`Delay`](qiskit.pulse.instructions.Delay ""qiskit.pulse.instructions.Delay"") instruction takes an explicit duration: ```python Delay(duration, channel) ``` An instruction can be added to a [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule""), which is a sequence of scheduled Pulse `Instruction` s over many channels. `Instruction` s and `Schedule` s implement the same interface. | | | | ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`Acquire`](qiskit.pulse.instructions.Acquire ""qiskit.pulse.instructions.Acquire"")(duration, channel\[, mem\_slot, ...]) | The Acquire instruction is used to trigger the ADC associated with a particular qubit; e.g. | | [`Reference`](qiskit.pulse.instructions.Reference ""qiskit.pulse.instructions.Reference"")(name, \*extra\_keys) | Pulse compiler directive that refers to a subroutine. | | [`Delay`](qiskit.pulse.instructions.Delay ""qiskit.pulse.instructions.Delay"")(duration, channel\[, name]) | A blocking instruction with no other effect. | | [`Play`](qiskit.pulse.instructions.Play ""qiskit.pulse.instructions.Play"")(pulse, channel\[, name]) | This instruction is responsible for applying a pulse on a channel. | | [`RelativeBarrier`](qiskit.pulse.instructions.RelativeBarrier ""qiskit.pulse.instructions.RelativeBarrier"")(\*channels\[, name]) | Pulse `RelativeBarrier` directive. | | [`SetFrequency`](qiskit.pulse.instructions.SetFrequency ""qiskit.pulse.instructions.SetFrequency"")(frequency, channel\[, name]) | Set the channel frequency. | | [`ShiftFrequency`](qiskit.pulse.instructions.ShiftFrequency ""qiskit.pulse.instructions.ShiftFrequency"")(frequency, channel\[, name]) | Shift the channel frequency away from the current frequency. | | [`SetPhase`](qiskit.pulse.instructions.SetPhase ""qiskit.pulse.instructions.SetPhase"")(phase, channel\[, name]) | The set phase instruction sets the phase of the proceeding pulses on that channel to `phase` radians. | | [`ShiftPhase`](qiskit.pulse.instructions.ShiftPhase ""qiskit.pulse.instructions.ShiftPhase"")(phase, channel\[, name]) | The shift phase instruction updates the modulation phase of proceeding pulses played on the same [`Channel`](#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel""). | | [`Snapshot`](qiskit.pulse.instructions.Snapshot ""qiskit.pulse.instructions.Snapshot"")(label\[, snapshot\_type, name]) | An instruction targeted for simulators, to capture a moment in the simulation. | | [`TimeBlockade`](qiskit.pulse.instructions.TimeBlockade ""qiskit.pulse.instructions.TimeBlockade"")(duration, channel\[, name]) | Pulse `TimeBlockade` directive. | These are all instances of the same base class: ### Instruction The smallest schedulable unit: a single instruction. It has a fixed duration and specified channels. Instruction initializer. **Parameters** * **operands** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – The argument list. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Optional display name for this instruction. ## Pulse Library `qiskit.pulse.library` This library provides Pulse users with convenient methods to build Pulse waveforms. A pulse programmer can choose from one of several [Pulse Models](#pulse-models) such as [`Waveform`](qiskit.pulse.library.Waveform ""qiskit.pulse.library.Waveform"") and [`SymbolicPulse`](qiskit.pulse.library.SymbolicPulse ""qiskit.pulse.library.SymbolicPulse"") to create a pulse program. The [`Waveform`](qiskit.pulse.library.Waveform ""qiskit.pulse.library.Waveform"") model directly stores the waveform data points in each class instance. This model provides the most flexibility to express arbitrary waveforms and allows a rapid prototyping of new control techniques. However, this model is typically memory inefficient and might be hard to scale to large-size quantum processors. A user can directly instantiate the [`Waveform`](qiskit.pulse.library.Waveform ""qiskit.pulse.library.Waveform"") class with `samples` argument which is usually a complex numpy array or any kind of array-like data. In contrast, the [`SymbolicPulse`](qiskit.pulse.library.SymbolicPulse ""qiskit.pulse.library.SymbolicPulse"") model only stores the function and its parameters that generate the waveform in a class instance. It thus provides greater memory efficiency at the price of less flexibility in the waveform. This model also defines a small set of pulse subclasses in [Parametric Pulse Representation](#symbolic-pulses) which are commonly used in superconducting quantum processors. An instance of these subclasses can be serialized in the [QPY Format](qpy#qpy-format) while keeping the memory-efficient parametric representation of waveforms. Note that [`Waveform`](qiskit.pulse.library.Waveform ""qiskit.pulse.library.Waveform"") object can be generated from an instance of a [`SymbolicPulse`](qiskit.pulse.library.SymbolicPulse ""qiskit.pulse.library.SymbolicPulse"") which will set values for the parameters and sample the parametric expression to create the [`Waveform`](qiskit.pulse.library.Waveform ""qiskit.pulse.library.Waveform""). ### Pulse Models | | | | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | [`Waveform`](qiskit.pulse.library.Waveform ""qiskit.pulse.library.Waveform"")(samples\[, name, epsilon, ...]) | A pulse specified completely by complex-valued samples; each sample is played for the duration of the backend cycle-time, dt. | | [`SymbolicPulse`](qiskit.pulse.library.SymbolicPulse ""qiskit.pulse.library.SymbolicPulse"")(pulse\_type, duration\[, ...]) | The pulse representation model with parameters and symbolic expressions. | ### Parametric Pulse Representation | | | | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`Constant`](qiskit.pulse.library.Constant_class.rst#qiskit.pulse.library.Constant ""qiskit.pulse.library.Constant"")(duration, amp\[, angle, name, ...]) | A simple constant pulse, with an amplitude value and a duration: | | [`Drag`](qiskit.pulse.library.Drag_class.rst#qiskit.pulse.library.Drag ""qiskit.pulse.library.Drag"")(duration, amp, sigma, beta\[, angle, ...]) | The Derivative Removal by Adiabatic Gate (DRAG) pulse is a standard Gaussian pulse with an additional Gaussian derivative component and lifting applied. | | [`Gaussian`](qiskit.pulse.library.Gaussian_class.rst#qiskit.pulse.library.Gaussian ""qiskit.pulse.library.Gaussian"")(duration, amp, sigma\[, angle, ...]) | A lifted and truncated pulse envelope shaped according to the Gaussian function whose mean is centered at the center of the pulse (duration / 2): | | [`GaussianSquare`](qiskit.pulse.library.GaussianSquare ""qiskit.pulse.library.GaussianSquare"")(duration, amp, sigma\[, ...]) | A square pulse with a Gaussian shaped risefall on both sides lifted such that its first sample is zero. | | [`GaussianSquareDrag`](qiskit.pulse.library.GaussianSquareDrag ""qiskit.pulse.library.GaussianSquareDrag"")(duration, amp, sigma, beta) | A square pulse with a Drag shaped rise and fall | | [`gaussian_square_echo`](qiskit.pulse.library.gaussian_square_echo ""qiskit.pulse.library.gaussian_square_echo"")(duration, amp, sigma\[, ...]) | An echoed Gaussian square pulse with an active tone overlaid on it. | | [`GaussianDeriv`](qiskit.pulse.library.GaussianDeriv ""qiskit.pulse.library.GaussianDeriv"")(duration, amp, sigma\[, angle, ...]) | An unnormalized Gaussian derivative pulse. | | [`Sin`](qiskit.pulse.library.Sin_class.rst#qiskit.pulse.library.Sin ""qiskit.pulse.library.Sin"")(duration, amp, phase\[, freq, angle, ...]) | A sinusoidal pulse. | | [`Cos`](qiskit.pulse.library.Cos_class.rst#qiskit.pulse.library.Cos ""qiskit.pulse.library.Cos"")(duration, amp, phase\[, freq, angle, ...]) | A cosine pulse. | | [`Sawtooth`](qiskit.pulse.library.Sawtooth_class.rst#qiskit.pulse.library.Sawtooth ""qiskit.pulse.library.Sawtooth"")(duration, amp, phase\[, freq, ...]) | A sawtooth pulse. | | [`Triangle`](qiskit.pulse.library.Triangle_class.rst#qiskit.pulse.library.Triangle ""qiskit.pulse.library.Triangle"")(duration, amp, phase\[, freq, ...]) | A triangle wave pulse. | | [`Square`](qiskit.pulse.library.Square_fun.rst#qiskit.pulse.library.Square ""qiskit.pulse.library.Square"")(duration, amp, phase\[, freq, angle, ...]) | A square wave pulse. | | [`Sech`](qiskit.pulse.library.Sech_fun.rst#qiskit.pulse.library.Sech ""qiskit.pulse.library.Sech"")(duration, amp, sigma\[, angle, name, ...]) | An unnormalized sech pulse. | | [`SechDeriv`](qiskit.pulse.library.SechDeriv ""qiskit.pulse.library.SechDeriv"")(duration, amp, sigma\[, angle, ...]) | An unnormalized sech derivative pulse. | ## Channels `qiskit.pulse.channels` Pulse is meant to be agnostic to the underlying hardware implementation, while still allowing low-level control. Therefore, our signal channels are *virtual* hardware channels. The backend which executes our programs is responsible for mapping these virtual channels to the proper physical channel within the quantum control hardware. Channels are characterized by their type and their index. Channels include: * transmit channels, which should subclass `PulseChannel` * receive channels, such as [`AcquireChannel`](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"") * non-signal “channels” such as [`SnapshotChannel`](qiskit.pulse.channels.SnapshotChannel ""qiskit.pulse.channels.SnapshotChannel""), [`MemorySlot`](qiskit.pulse.channels.MemorySlot ""qiskit.pulse.channels.MemorySlot"") and `RegisterChannel`. Novel channel types can often utilize the [`ControlChannel`](qiskit.pulse.channels.ControlChannel ""qiskit.pulse.channels.ControlChannel""), but if this is not sufficient, new channel types can be created. Then, they must be supported in the PulseQobj schema and the assembler. Channels are characterized by their type and their index. See each channel type below to learn more. | | | | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | [`DriveChannel`](qiskit.pulse.channels.DriveChannel ""qiskit.pulse.channels.DriveChannel"")(\*args, \*\*kwargs) | Drive channels transmit signals to qubits which enact gate operations. | | [`MeasureChannel`](qiskit.pulse.channels.MeasureChannel ""qiskit.pulse.channels.MeasureChannel"")(\*args, \*\*kwargs) | Measure channels transmit measurement stimulus pulses for readout. | | [`AcquireChannel`](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"")(\*args, \*\*kwargs) | Acquire channels are used to collect data. | | [`ControlChannel`](qiskit.pulse.channels.ControlChannel ""qiskit.pulse.channels.ControlChannel"")(\*args, \*\*kwargs) | Control channels provide supplementary control over the qubit to the drive channel. | | [`RegisterSlot`](qiskit.pulse.channels.RegisterSlot ""qiskit.pulse.channels.RegisterSlot"")(\*args, \*\*kwargs) | Classical resister slot channels represent classical registers (low-latency classical memory). | | [`MemorySlot`](qiskit.pulse.channels.MemorySlot ""qiskit.pulse.channels.MemorySlot"")(\*args, \*\*kwargs) | Memory slot channels represent classical memory storage. | | [`SnapshotChannel`](qiskit.pulse.channels.SnapshotChannel ""qiskit.pulse.channels.SnapshotChannel"")(\*args, \*\*kwargs) | Snapshot channels are used to specify instructions for simulators. | All channels are children of the same abstract base class: ### Channel Base class of channels. Channels provide a Qiskit-side label for typical quantum control hardware signal channels. The final label -> physical channel mapping is the responsibility of the hardware backend. For instance, `DriveChannel(0)` holds instructions which the backend should map to the signal line driving gate operations on the qubit labeled (indexed) 0. When serialized channels are identified by their serialized name ``. The type of the channel is interpreted from the prefix, and the index often (but not always) maps to the qubit index. All concrete channel classes must have a `prefix` class attribute (and instances of that class have an index attribute). Base classes which have `prefix` set to `None` are prevented from being instantiated. To implement a new channel inherit from [`Channel`](#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") and provide a unique string identifier for the `prefix` class attribute. Channel class. **Parameters** **index** – Index of channel. ## Schedules Schedules are Pulse programs. They describe instruction sequences for the control hardware. The Schedule is one of the most fundamental objects to this pulse-level programming module. A `Schedule` is a representation of a *program* in Pulse. Each schedule tracks the time of each instruction occuring in parallel over multiple signal *channels*. | | | | -------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"")(\*schedules\[, name, metadata]) | A quantum program *schedule* with exact time constraints for its instructions, operating over all input signal *channels* and supporting special syntaxes for building. | | [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"")(\[name, metadata, ...]) | Time-ordered sequence of instructions with alignment context. | ## Pulse Transforms `qiskit.pulse.transforms` The pulse transforms provide transformation routines to reallocate and optimize pulse programs for backends. ### Alignments The alignment transforms define alignment policies of instructions in [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock""). These transformations are called to create [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"")s from [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"")s. | | | | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | [`AlignEquispaced`](qiskit.pulse.transforms.AlignEquispaced ""qiskit.pulse.transforms.AlignEquispaced"")(duration) | Align instructions with equispaced interval within a specified duration. | | [`AlignFunc`](qiskit.pulse.transforms.AlignFunc ""qiskit.pulse.transforms.AlignFunc"")(duration, func) | Allocate instructions at position specified by callback function. | | [`AlignLeft`](qiskit.pulse.transforms.AlignLeft ""qiskit.pulse.transforms.AlignLeft"")() | Align instructions in as-soon-as-possible manner. | | [`AlignRight`](qiskit.pulse.transforms.AlignRight ""qiskit.pulse.transforms.AlignRight"")() | Align instructions in as-late-as-possible manner. | | [`AlignSequential`](qiskit.pulse.transforms.AlignSequential ""qiskit.pulse.transforms.AlignSequential"")() | Align instructions sequentially. | These are all subtypes of the abstract base class [`AlignmentKind`](#qiskit.pulse.transforms.AlignmentKind ""qiskit.pulse.transforms.AlignmentKind""). #### AlignmentKind An abstract class for schedule alignment. Create new context. ### Canonicalization The canonicalization transforms convert schedules to a form amenable for execution on OpenPulse backends. #### add\_implicit\_acquires Return a new schedule with implicit acquires from the measurement mapping replaced by explicit ones. Since new acquires are being added, Memory Slots will be set to match the qubit index. This may overwrite your specification. **Parameters** * **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") *|*[*Instruction*](#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"")) – Schedule to be aligned. * **meas\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – List of lists of qubits that are measured together. **Returns** A `Schedule` with the additional acquisition instructions. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") #### align\_measures Return new schedules where measurements occur at the same physical time. This transformation will align the first [`Acquire`](qiskit.pulse.instructions.Acquire ""qiskit.pulse.instructions.Acquire"") on every channel to occur at the same time. Minimum measurement wait time (to allow for calibration pulses) is enforced and may be set with `max_calibration_duration`. By default only instructions containing a [`AcquireChannel`](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"") or [`MeasureChannel`](qiskit.pulse.channels.MeasureChannel ""qiskit.pulse.channels.MeasureChannel"") will be shifted. If you wish to keep the relative timing of all instructions in the schedule set `align_all=True`. This method assumes that `MeasureChannel(i)` and `AcquireChannel(i)` correspond to the same qubit and the acquire/play instructions should be shifted together on these channels. ```python from qiskit import pulse from qiskit.pulse import transforms d0 = pulse.DriveChannel(0) m0 = pulse.MeasureChannel(0) a0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) sched = pulse.Schedule() sched.append(pulse.Play(pulse.Constant(10, 0.5), d0), inplace=True) sched.append(pulse.Play(pulse.Constant(10, 1.), m0).shift(sched.duration), inplace=True) sched.append(pulse.Acquire(20, a0, mem0).shift(sched.duration), inplace=True) sched_shifted = sched << 20 aligned_sched, aligned_sched_shifted = transforms.align_measures([sched, sched_shifted]) assert aligned_sched == aligned_sched_shifted ``` If it is desired to only shift acquisition and measurement stimulus instructions set the flag `align_all=False`: ```python aligned_sched, aligned_sched_shifted = transforms.align_measures( [sched, sched_shifted], align_all=False, ) assert aligned_sched != aligned_sched_shifted ``` **Parameters** * **schedules** (*Iterable\[ScheduleComponent]*) – Collection of schedules to be aligned together * **inst\_map** ([*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"") *| None*) – Mapping of circuit operations to pulse schedules * **cal\_gate** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the gate to inspect for the calibration time * **max\_calibration\_duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – If provided, inst\_map and cal\_gate will be ignored * **align\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – If provided, this will be used as final align time. * **align\_all** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – Shift all instructions in the schedule such that they maintain their relative alignment with the shifted acquisition instruction. If `False` only the acquisition and measurement pulse instructions will be shifted. **Returns** The input list of schedules transformed to have their measurements aligned. **Raises** [**PulseError**](#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – If the provided alignment time is negative. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"")] #### block\_to\_schedule Convert `ScheduleBlock` to `Schedule`. **Parameters** **block** ([*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"")) – A `ScheduleBlock` to convert. **Returns** Scheduled pulse program. **Raises** * [**UnassignedDurationError**](#qiskit.pulse.UnassignedDurationError ""qiskit.pulse.UnassignedDurationError"") – When any instruction duration is not assigned. * [**PulseError**](#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When the alignment context duration is shorter than the schedule duration. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") This transform may insert barriers in between contexts. #### compress\_pulses Optimization pass to replace identical pulses. **Parameters** **schedules** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*qiskit.pulse.schedule.Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"")*]*) – Schedules to compress. **Returns** Compressed schedules. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[qiskit.pulse.schedule.Schedule](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"")] #### flatten Flatten (inline) any called nodes into a Schedule tree with no nested children. **Parameters** **program** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"")) – Pulse program to remove nested structure. **Returns** Flatten pulse program. **Raises** [**PulseError**](#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When invalid data format is given. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") #### inline\_subroutines Recursively remove call instructions and inline the respective subroutine instructions. Assigned parameter values, which are stored in the parameter table, are also applied. The subroutine is copied before the parameter assignment to avoid mutation problem. **Parameters** **program** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *|*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"")) – A program which may contain the subroutine, i.e. `Call` instruction. **Returns** A schedule without subroutine. **Raises** [**PulseError**](#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When input program is not valid data format. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") | [ScheduleBlock](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") #### pad Pad the input Schedule with `Delay``s on all unoccupied timeslots until ``schedule.duration` or `until` if not `None`. **Parameters** * **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"")) – Schedule to pad. * **channels** (*Iterable\[chans.Channel] | None*) – Channels to pad. Defaults to all channels in `schedule` if not provided. If the supplied channel is not a member of `schedule` it will be added. * **until** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Time to pad until. Defaults to `schedule.duration` if not provided. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Pad this schedule by mutating rather than returning a new schedule. * **pad\_with** ([*Type*](circuit_classical#qiskit.circuit.classical.types.Type ""qiskit.circuit.classical.types.Type"")*\[*[*instructions.Instruction*](#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.Instruction"")*] | None*) – Pulse `Instruction` subclass to be used for padding. Default to [`Delay`](qiskit.pulse.instructions.Delay ""qiskit.pulse.instructions.Delay"") instruction. **Returns** The padded schedule. **Raises** [**PulseError**](#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When non pulse instruction is set to pad\_with. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") #### remove\_directives Remove directives. **Parameters** **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"")) – A schedule to remove compiler directives. **Returns** A schedule without directives. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") #### remove\_trivial\_barriers Remove trivial barriers with 0 or 1 channels. **Parameters** **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"")) – A schedule to remove trivial barriers. **Returns** A schedule without trivial barriers **Return type** schedule ### DAG The DAG transforms create DAG representation of input program. This can be used for optimization of instructions and equality checks. #### block\_to\_dag Convert schedule block instruction into DAG. `ScheduleBlock` can be represented as a DAG as needed. For example, equality of two programs are efficiently checked on DAG representation. ```python with pulse.build() as sched1: with pulse.align_left(): pulse.play(my_gaussian0, pulse.DriveChannel(0)) pulse.shift_phase(1.57, pulse.DriveChannel(2)) pulse.play(my_gaussian1, pulse.DriveChannel(1)) with pulse.build() as sched2: with pulse.align_left(): pulse.shift_phase(1.57, pulse.DriveChannel(2)) pulse.play(my_gaussian1, pulse.DriveChannel(1)) pulse.play(my_gaussian0, pulse.DriveChannel(0)) ``` Here the `sched1 `` and ``sched2` are different implementations of the same program, but it is difficult to confirm on the list representation. Another example is instruction optimization. ```python with pulse.build() as sched: with pulse.align_left(): pulse.shift_phase(1.57, pulse.DriveChannel(1)) pulse.play(my_gaussian0, pulse.DriveChannel(0)) pulse.shift_phase(-1.57, pulse.DriveChannel(1)) ``` In above program two `shift_phase` instructions can be cancelled out because they are consecutive on the same drive channel. This can be easily found on the DAG representation. **Parameters** **block** (*""ScheduleBlock""*) – A schedule block to be converted. **Returns** Instructions in DAG representation. **Raises** [**PulseError**](#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When the context is invalid subclass. **Return type** rx.PyDAG ### Composite transform A sequence of transformations to generate a target code. #### target\_qobj\_transform A basic pulse program transformation for OpenPulse API execution. **Parameters** * **sched** ([*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"") *|*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") *|*[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*,* [*Instruction*](#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"")*] |* [*Instruction*](#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"") *|*[*Iterable*](https://docs.python.org/3/library/typing.html#typing.Iterable ""(in Python v3.12)"")*\[*[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*,* [*Instruction*](#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"")*] |* [*Instruction*](#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"")*]*) – Input program to transform. * **remove\_directives** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Set True to remove compiler directives. **Returns** Transformed program for execution. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") ## Pulse Builder Use the pulse builder DSL to write pulse programs with an imperative syntax. The pulse builder interface is still in active development. It may have breaking API changes without deprecation warnings in future releases until otherwise indicated. The pulse builder provides an imperative API for writing pulse programs with less difficulty than the [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") API. It contextually constructs a pulse schedule and then emits the schedule for execution. For example, to play a series of pulses on channels is as simple as: ```python from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw() ``` ![../\_images/pulse-1.png](/images/api/qiskit/1.0/pulse-1.png) To begin pulse programming we must first initialize our program builder context with [`build()`](#qiskit.pulse.builder.build ""qiskit.pulse.builder.build""), after which we can begin adding program statements. For example, below we write a simple program that [`play()`](#qiskit.pulse.builder.play ""qiskit.pulse.builder.play"")s a pulse: ```python from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw() ``` ![../\_images/pulse-2.png](/images/api/qiskit/1.0/pulse-2.png) The builder initializes a [`pulse.Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule""), `pulse_prog` and then begins to construct the program within the context. The output pulse schedule will survive after the context is exited and can be transpiled and executed like a normal Qiskit schedule using `backend.run(transpile(pulse_prog, backend))`. Pulse programming has a simple imperative style. This leaves the programmer to worry about the raw experimental physics of pulse programming and not constructing cumbersome data structures. We can optionally pass a [`Backend`](qiskit.providers.Backend ""qiskit.providers.Backend"") to [`build()`](#qiskit.pulse.builder.build ""qiskit.pulse.builder.build"") to enable enhanced functionality. Below, we prepare a Bell state by automatically compiling the required pulses from their gate-level representations, while simultaneously applying a long decoupling pulse to a neighboring qubit. We terminate the experiment with a measurement to observe the state we prepared. This program which mixes circuits and pulses will be automatically lowered to be run as a pulse program: ```python from math import pi from qiskit.compiler import schedule from qiskit.circuit import QuantumCircuit from qiskit import pulse from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(num_qubits=5, calibrate_instructions=True) d2 = pulse.DriveChannel(2) qc = QuantumCircuit(2) # Hadamard qc.rz(pi/2, 0) qc.sx(0) qc.rz(pi/2, 0) qc.cx(0, 1) bell_sched = schedule(qc, backend) with pulse.build(backend) as decoupled_bell_prep_and_measure: # We call our bell state preparation schedule constructed above. with pulse.align_right(): pulse.call(bell_sched) pulse.play(pulse.Constant(bell_sched.duration, 0.02), d2) pulse.barrier(0, 1, 2) registers = pulse.measure_all() decoupled_bell_prep_and_measure.draw() ``` ![../\_images/pulse-3.png](/images/api/qiskit/1.0/pulse-3.png) With the pulse builder we are able to blend programming on qubits and channels. While the pulse schedule is based on instructions that operate on channels, the pulse builder automatically handles the mapping from qubits to channels for you. In the example below we demonstrate some more features of the pulse builder: ```python import math from qiskit.compiler import schedule from qiskit import pulse, QuantumCircuit from qiskit.pulse import library from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() qc = QuantumCircuit(2, 2) qc.cx(0, 1) with pulse.build(backend) as pulse_prog: # Create a pulse. gaussian_pulse = library.gaussian(10, 1.0, 2) # Get the qubit's corresponding drive channel from the backend. d0 = pulse.drive_channel(0) d1 = pulse.drive_channel(1) # Play a pulse at t=0. pulse.play(gaussian_pulse, d0) # Play another pulse directly after the previous pulse at t=10. pulse.play(gaussian_pulse, d0) # The default scheduling behavior is to schedule pulses in parallel # across channels. For example, the statement below # plays the same pulse on a different channel at t=0. pulse.play(gaussian_pulse, d1) # We also provide pulse scheduling alignment contexts. # The default alignment context is align_left. # The sequential context schedules pulse instructions sequentially in time. # This context starts at t=10 due to earlier pulses above. with pulse.align_sequential(): pulse.play(gaussian_pulse, d0) # Play another pulse after at t=20. pulse.play(gaussian_pulse, d1) # We can also nest contexts as each instruction is # contained in its local scheduling context. # The output of a child context is a context-schedule # with the internal instructions timing fixed relative to # one another. This is schedule is then called in the parent context. # Context starts at t=30. with pulse.align_left(): # Start at t=30. pulse.play(gaussian_pulse, d0) # Start at t=30. pulse.play(gaussian_pulse, d1) # Context ends at t=40. # Alignment context where all pulse instructions are # aligned to the right, ie., as late as possible. with pulse.align_right(): # Shift the phase of a pulse channel. pulse.shift_phase(math.pi, d1) # Starts at t=40. pulse.delay(100, d0) # Ends at t=140. # Starts at t=130. pulse.play(gaussian_pulse, d1) # Ends at t=140. # Acquire data for a qubit and store in a memory slot. pulse.acquire(100, 0, pulse.MemorySlot(0)) # We also support a variety of macros for common operations. # Measure all qubits. pulse.measure_all() # Delay on some qubits. # This requires knowledge of which channels belong to which qubits. # delay for 100 cycles on qubits 0 and 1. pulse.delay_qubits(100, 0, 1) # Call a schedule for a quantum circuit thereby inserting into # the pulse schedule. qc = QuantumCircuit(2, 2) qc.cx(0, 1) qc_sched = schedule(qc, backend) pulse.call(qc_sched) # It is also be possible to call a preexisting schedule tmp_sched = pulse.Schedule() tmp_sched += pulse.Play(gaussian_pulse, d0) pulse.call(tmp_sched) # We also support: # frequency instructions pulse.set_frequency(5.0e9, d0) # phase instructions pulse.shift_phase(0.1, d0) # offset contexts with pulse.phase_offset(math.pi, d0): pulse.play(gaussian_pulse, d0) ``` The above is just a small taste of what is possible with the builder. See the rest of the module documentation for more information on its capabilities. ### build Create a context manager for launching the imperative pulse builder DSL. To enter a building context and starting building a pulse program: ```python from qiskit import transpile, pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 0.5), d0) ``` While the output program `pulse_prog` cannot be executed as we are using a mock backend. If a real backend is being used, executing the program is done with: ```python backend.run(transpile(pulse_prog, backend)) ``` **Parameters** * **backend** ([*Backend*](qiskit.providers.Backend ""qiskit.providers.Backend"")) – A Qiskit backend. If not supplied certain builder functionality will be unavailable. * **schedule** ([*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") *| None*) – A pulse `ScheduleBlock` in which your pulse program will be built. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of pulse program to be built. * **default\_alignment** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*AlignmentKind*](#qiskit.pulse.transforms.AlignmentKind ""qiskit.pulse.transforms.AlignmentKind"") *| None*) – Default scheduling alignment for builder. One of `left`, `right`, `sequential` or an alignment context. **Returns** A new builder context which has the active builder initialized. **Return type** ContextManager\[[ScheduleBlock](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"")] ### Channels Methods to return the correct channels for the respective qubit indices. ```python from qiskit import pulse from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(num_qubits=2, calibrate_instructions=True) with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) print(d0) ``` ```python DriveChannel(0) ``` #### acquire\_channel Return `AcquireChannel` for `qubit` on the active builder backend. Examples: ```python from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.acquire_channel(0) == pulse.AcquireChannel(0) ``` Requires the active builder context to have a backend set. **Return type** [*AcquireChannel*](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"") #### control\_channels Return `ControlChannel` for `qubit` on the active builder backend. Return the secondary drive channel for the given qubit – typically utilized for controlling multi-qubit interactions. Examples: ```python from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)] ``` Requires the active builder context to have a backend set. **Parameters** **qubits** ([*Iterable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – Tuple or list of ordered qubits of the form (control\_qubit, target\_qubit). **Returns** List of control channels associated with the supplied ordered list of qubits. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[qiskit.pulse.channels.ControlChannel](qiskit.pulse.channels.ControlChannel ""qiskit.pulse.channels.ControlChannel"")] #### drive\_channel Return `DriveChannel` for `qubit` on the active builder backend. Examples: ```python from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.drive_channel(0) == pulse.DriveChannel(0) ``` Requires the active builder context to have a backend set. **Return type** [*DriveChannel*](qiskit.pulse.channels.DriveChannel ""qiskit.pulse.channels.DriveChannel"") #### measure\_channel Return `MeasureChannel` for `qubit` on the active builder backend. Examples: ```python from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.measure_channel(0) == pulse.MeasureChannel(0) ``` Requires the active builder context to have a backend set. **Return type** [*MeasureChannel*](qiskit.pulse.channels.MeasureChannel ""qiskit.pulse.channels.MeasureChannel"") ### Instructions Pulse instructions are available within the builder interface. Here’s an example: ```python from qiskit import pulse from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(num_qubits=2, calibrate_instructions=True) with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw() ``` ![../\_images/pulse-4.png](/images/api/qiskit/1.0/pulse-4.png) #### acquire Acquire for a `duration` on a `channel` and store the result in a `register`. Examples: ```python from qiskit import pulse acq0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) with pulse.build() as pulse_prog: pulse.acquire(100, acq0, mem0) # measurement metadata kernel = pulse.configuration.Kernel('linear_discriminator') pulse.acquire(100, acq0, mem0, kernel=kernel) ``` The type of data acquire will depend on the execution `meas_level`. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Duration to acquire data for * **qubit\_or\_channel** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| chans.AcquireChannel*) – Either the qubit to acquire data for or the specific [`AcquireChannel`](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"") to acquire on. * **register** (*StorageLocation*) – Location to store measured result. * **metadata** (*Unpack\[\_MetaDataType]*) – Additional metadata for measurement. See [`Acquire`](qiskit.pulse.instructions.Acquire ""qiskit.pulse.instructions.Acquire"") for more information. **Raises** [**exceptions.PulseError**](#qiskit.pulse.PulseError ""qiskit.pulse.exceptions.PulseError"") – If the register type is not supported. #### barrier Barrier directive for a set of channels and qubits. This directive prevents the compiler from moving instructions across the barrier. Consider the case where we want to enforce that one pulse happens after another on separate channels, this can be done with: ```python from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build(backend) as barrier_pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) pulse.barrier(d0, d1) pulse.play(pulse.Constant(10, 1.0), d1) ``` Of course this could have been accomplished with: ```python from qiskit.pulse import transforms with pulse.build(backend) as aligned_pulse_prog: with pulse.align_sequential(): pulse.play(pulse.Constant(10, 1.0), d0) pulse.play(pulse.Constant(10, 1.0), d1) barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog) aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog) assert barrier_pulse_prog == aligned_pulse_prog ``` The barrier allows the pulse compiler to take care of more advanced scheduling alignment operations across channels. For example in the case where we are calling an outside circuit or schedule and want to align a pulse at the end of one call: ```python import math d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: with pulse.align_right(): pulse.call(backend.defaults.instruction_schedule_map.get('x', (1,))) # Barrier qubit 1 and d0. pulse.barrier(1, d0) # Due to barrier this will play before the gate on qubit 1. pulse.play(pulse.Constant(10, 1.0), d0) # This will end at the same time as the pulse above due to # the barrier. pulse.call(backend.defaults.instruction_schedule_map.get('x', (1,))) ``` Requires the active builder context to have a backend set if qubits are barriered on. **Parameters** * **channels\_or\_qubits** (*chans.Channel |* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Channels or qubits to barrier. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name for the barrier #### call Call the subroutine within the currently active builder context with arbitrary parameters which will be assigned to the target program. If the `target` program is a [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock""), then a [`Reference`](qiskit.pulse.instructions.Reference ""qiskit.pulse.instructions.Reference"") instruction will be created and appended to the current context. The `target` program will be immediately assigned to the current scope as a subroutine. If the `target` program is [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule""), it will be wrapped by the `Call` instruction and appended to the current context to avoid a mixed representation of [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") and [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule""). If the `target` program is a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") it will be scheduled and the new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") will be added as a `Call` instruction. **Examples** 1. Calling a schedule block (recommended) ```python from qiskit import circuit, pulse from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(num_qubits=5, calibrate_instructions=True) with pulse.build() as x_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(x_sched) print(pulse_prog) ``` ```python ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name=""block0"", transform=AlignLeft() ), name=""block1"", transform=AlignLeft() ) ``` The actual program is stored in the reference table attached to the schedule. ```python print(pulse_prog.references) ``` ```python ReferenceManager: - ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(... ``` In addition, you can call a parameterized target program with parameter assignment. ```python amp = circuit.Parameter(""amp"") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(subroutine, amp=0.1) pulse.call(subroutine, amp=0.3) print(pulse_prog) ``` ```python ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name=""block2"", transform=AlignLeft() ), ScheduleBlock( Play( Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(0) ), name=""block2"", transform=AlignLeft() ), name=""block3"", transform=AlignLeft() ) ``` If there is a name collision between parameters, you can distinguish them by specifying each parameter object in a python dictionary. For example, ```python amp1 = circuit.Parameter('amp') amp2 = circuit.Parameter('amp') with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1)) with pulse.build() as pulse_prog: pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3}) print(pulse_prog) ``` ```python ScheduleBlock( ScheduleBlock( Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)), Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)), name=""block4"", transform=AlignLeft() ), name=""block5"", transform=AlignLeft() ) ``` 2. Calling a schedule ```python x_sched = backend.instruction_schedule_map.get(""x"", (0,)) with pulse.build(backend) as pulse_prog: pulse.call(x_sched) print(pulse_prog) ``` ```python ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name=""x"" ), name='x' ), name=""block6"", transform=AlignLeft() ) ``` Currently, the backend calibrated gates are provided in the form of [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule""). The parameter assignment mechanism is available also for schedules. However, the called schedule is not treated as a reference. **Parameters** * **target** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *|*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") *| None*) – Target circuit or pulse schedule to call. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Optional. A unique name of subroutine if defined. When the name is explicitly provided, one cannot call different schedule blocks with the same name. * **value\_dict** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[ParameterValueType, ParameterValueType] | None*) – Optional. Parameters assigned to the `target` program. If this dictionary is provided, the `target` program is copied and then stored in the main built schedule and its parameters are assigned to the given values. This dictionary is keyed on [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") objects, allowing parameter name collision to be avoided. * **kw\_params** (*ParameterValueType*) – Alternative way to provide parameters. Since this is keyed on the string parameter name, the parameters having the same name are all updated together. If you want to avoid name collision, use `value_dict` with [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") objects instead. #### delay Delay on a `channel` for a `duration`. Examples: ```python from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.delay(10, d0) ``` **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of cycles to delay for on `channel`. * **channel** (*chans.Channel*) – Channel to delay on. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the instruction. #### play Play a `pulse` on a `channel`. Examples: ```python from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) ``` **Parameters** * **pulse** (*library.Pulse | np.ndarray*) – Pulse to play. * **channel** (*chans.PulseChannel*) – Channel to play pulse on. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the pulse. #### reference Refer to undefined subroutine by string keys. A [`Reference`](qiskit.pulse.instructions.Reference ""qiskit.pulse.instructions.Reference"") instruction is implicitly created and a schedule can be separately registered to the reference at a later stage. ```python from qiskit import pulse with pulse.build() as main_prog: pulse.reference(""x_gate"", ""q0"") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) main_prog.assign_references(subroutine_dict={(""x_gate"", ""q0""): subroutine}) ``` **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of subroutine. * **extra\_keys** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Helper keys to uniquely specify the subroutine. #### set\_frequency Set the `frequency` of a pulse `channel`. Examples: ```python from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_frequency(1e9, d0) ``` **Parameters** * **frequency** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Frequency in Hz to set channel to. * **channel** (*chans.PulseChannel*) – Channel to set frequency of. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the instruction. #### set\_phase Set the `phase` of a pulse `channel`. Examples: ```python import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_phase(math.pi, d0) ``` **Parameters** * **phase** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Phase in radians to set channel carrier signal to. * **channel** (*chans.PulseChannel*) – Channel to set phase of. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the instruction. #### shift\_frequency Shift the `frequency` of a pulse `channel`. Examples: ```python from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_frequency(1e9, d0) ``` **Parameters** * **frequency** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Frequency in Hz to shift channel frequency by. * **channel** (*chans.PulseChannel*) – Channel to shift frequency of. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the instruction. #### shift\_phase Shift the `phase` of a pulse `channel`. Examples: ```python import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_phase(math.pi, d0) ``` **Parameters** * **phase** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Phase in radians to shift channel carrier signal by. * **channel** (*chans.PulseChannel*) – Channel to shift phase of. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the instruction. #### snapshot Simulator snapshot. Examples: ```python from qiskit import pulse with pulse.build() as pulse_prog: pulse.snapshot('first', 'statevector') ``` **Parameters** * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Label for snapshot. * **snapshot\_type** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Type of snapshot. ### Contexts Builder aware contexts that modify the construction of a pulse program. For example an alignment context like [`align_right()`](#qiskit.pulse.builder.align_right ""qiskit.pulse.builder.align_right"") may be used to align all pulses as late as possible in a pulse program. ```python from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw() ``` ![../\_images/pulse-5.png](/images/api/qiskit/1.0/pulse-5.png) #### align\_equispaced Equispaced alignment pulse scheduling context. Pulse instructions within this context are scheduled with the same interval spacing such that the total length of the context block is `duration`. If the total free `duration` cannot be evenly divided by the number of instructions within the context, the modulo is split and then prepended and appended to the returned schedule. Delay instructions are automatically inserted in between pulses. This context is convenient to write a schedule for periodical dynamic decoupling or the Hahn echo sequence. Examples: ```python from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw() ``` ![../\_images/pulse-6.png](/images/api/qiskit/1.0/pulse-6.png) **Parameters** **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Duration of this context. This should be larger than the schedule duration. **Yields** None **Return type** Generator\[None, None, None] **Notes** The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the equispaced context for each channel, you should use the context independently for channels. #### align\_func Callback defined alignment pulse scheduling context. Pulse instructions within this context are scheduled at the location specified by arbitrary callback function position that takes integer index and returns the associated fractional location within \[0, 1]. Delay instruction is automatically inserted in between pulses. This context may be convenient to write a schedule of arbitrary dynamical decoupling sequences such as Uhrig dynamical decoupling. Examples: ```python import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw() ``` ![../\_images/pulse-7.png](/images/api/qiskit/1.0/pulse-7.png) **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Duration of context. This should be larger than the schedule duration. * **func** (*Callable\[\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*],* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – A function that takes an index of sub-schedule and returns the fractional coordinate of of that sub-schedule. The returned value should be defined within \[0, 1]. The pulse index starts from 1. **Yields** None **Return type** Generator\[None, None, None] **Notes** The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the numerical context for each channel, you need to apply the context independently to channels. #### align\_left Left alignment pulse scheduling context. Pulse instructions within this context are scheduled as early as possible by shifting them left to the earliest available time. Examples: ```python from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_left(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=0 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1) ``` **Yields** None **Return type** [*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator ""(in Python v3.12)"")\[None, None, None] #### align\_right Right alignment pulse scheduling context. Pulse instructions within this context are scheduled as late as possible by shifting them right to the latest available time. Examples: ```python from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1) ``` **Yields** None **Return type** [*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator ""(in Python v3.12)"")\[None, None, None] #### align\_sequential Sequential alignment pulse scheduling context. Pulse instructions within this context are scheduled sequentially in time such that no two instructions will be played at the same time. Examples: ```python from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_sequential(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will also start at t=100 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1) ``` **Yields** None **Return type** [*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator ""(in Python v3.12)"")\[None, None, None] #### frequency\_offset Shift the frequency of inputs channels on entry into context and undo on exit. Examples: ```python from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: # shift frequency by 1GHz with pulse.frequency_offset(1e9, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 with pulse.build(backend) as pulse_prog: # Shift frequency by 1GHz. # Undo accumulated phase in the shifted frequency frame # when exiting the context. with pulse.frequency_offset(1e9, d0, compensate_phase=True): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 4 ``` **Parameters** * **frequency** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Amount of frequency offset in Hz. * **channels** (*PulseChannel*) – Channels to offset frequency of. * **compensate\_phase** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Compensate for accumulated phase accumulated with respect to the channels’ frame at its initial frequency. **Yields** None **Return type** [*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator ""(in Python v3.12)"")\[None, None, None] #### phase\_offset Shift the phase of input channels on entry into context and undo on exit. Examples: ```python import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: with pulse.phase_offset(math.pi, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 ``` **Parameters** * **phase** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Amount of phase offset in radians. * **channels** (*PulseChannel*) – Channels to offset phase of. **Yields** None **Return type** [*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator ""(in Python v3.12)"")\[None, None, None] ### Macros Macros help you add more complex functionality to your pulse program. ```python from qiskit import pulse from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(num_qubits=2, calibrate_instructions=True) with pulse.build(backend) as measure_sched: mem_slot = pulse.measure(0) print(mem_slot) ``` ```python MemorySlot(0) ``` #### measure Measure a qubit within the currently active builder context. At the pulse level a measurement is composed of both a stimulus pulse and an acquisition instruction which tells the systems measurement unit to acquire data and process it. We provide this measurement macro to automate the process for you, but if desired full control is still available with [`acquire()`](#qiskit.pulse.builder.acquire ""qiskit.pulse.builder.acquire"") and [`play()`](#qiskit.pulse.builder.play ""qiskit.pulse.builder.play""). To use the measurement it is as simple as specifying the qubit you wish to measure: ```python from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() qubit = 0 with pulse.build(backend) as pulse_prog: # Do something to the qubit. qubit_drive_chan = pulse.drive_channel(0) pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. reg = pulse.measure(qubit) ``` For now it is not possible to do much with the handle to `reg` but in the future we will support using this handle to a result register to build up ones program. It is also possible to supply this register: ```python with pulse.build(backend) as pulse_prog: pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. mem0 = pulse.MemorySlot(0) reg = pulse.measure(qubit, mem0) assert reg == mem0 ``` Requires the active builder context to have a backend set. **Parameters** * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] |* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Physical qubit to measure. * **registers** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[StorageLocation] | StorageLocation*) – Register to store result in. If not selected the current behavior is to return the `MemorySlot` with the same index as `qubit`. This register will be returned. **Returns** The `register` the qubit measurement result will be stored in. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[StorageLocation] | StorageLocation #### measure\_all Measure all qubits within the currently active builder context. A simple macro function to measure all of the qubits in the device at the same time. This is useful for handling device `meas_map` and single measurement constraints. Examples: ```python from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Measure all qubits and return associated registers. regs = pulse.measure_all() ``` Requires the active builder context to have a backend set. **Returns** The `register`s the qubit measurement results will be stored in. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[qiskit.pulse.channels.MemorySlot](qiskit.pulse.channels.MemorySlot ""qiskit.pulse.channels.MemorySlot"")] #### delay\_qubits Insert delays on all the `channels.Channel`s that correspond to the input `qubits` at the same time. Examples: ```python from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q backend = FakeOpenPulse3Q() with pulse.build(backend) as pulse_prog: # Delay for 100 cycles on qubits 0, 1 and 2. regs = pulse.delay_qubits(100, 0, 1, 2) ``` Requires the active builder context to have a backend set. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Duration to delay for. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Physical qubits to delay on. Delays will be inserted based on the channels returned by `pulse.qubit_channels()`. ### Utilities The utility functions can be used to gather attributes about the backend and modify how the program is built. ```python from qiskit import pulse from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(num_qubits=2, calibrate_instructions=True) with pulse.build(backend) as u3_sched: print('Number of qubits in backend: {}'.format(pulse.num_qubits())) samples = 160 print('There are {} samples in {} seconds'.format( samples, pulse.samples_to_seconds(160))) seconds = 1e-6 print('There are {} seconds in {} samples.'.format( seconds, pulse.seconds_to_samples(1e-6))) ``` ```python Number of qubits in backend: 1 There are 160 samples in 3.5555555555555554e-08 seconds There are 1e-06 seconds in 4500 samples. ``` #### active\_backend Get the backend of the currently active builder context. **Returns** **The active backend in the currently active** builder context. **Return type** [Backend](qiskit.providers.Backend ""qiskit.providers.Backend"") **Raises** [**exceptions.BackendNotSet**](#qiskit.pulse.BackendNotSet ""qiskit.pulse.exceptions.BackendNotSet"") – If the builder does not have a backend set. #### num\_qubits Return number of qubits in the currently active backend. Examples: ```python from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.num_qubits()) ``` ```python 2 ``` Requires the active builder context to have a backend set. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") #### qubit\_channels Returns the set of channels associated with a qubit. Examples: ```python from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.qubit_channels(0)) ``` ```python {MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)} ``` Requires the active builder context to have a backend set. A channel may still be associated with another qubit in this list such as in the case where significant crosstalk exists. **Return type** [set](https://docs.python.org/3/library/stdtypes.html#set ""(in Python v3.12)"")\[[qiskit.pulse.channels.Channel](#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")] #### samples\_to\_seconds Obtain the time in seconds that will elapse for the input number of samples on the active backend. **Parameters** **samples** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| np.ndarray*) – Number of samples to convert to time in seconds. **Returns** The time that elapses in `samples`. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") | np.ndarray #### seconds\_to\_samples Obtain the number of samples that will elapse in `seconds` on the active backend. Rounds down. **Parameters** **seconds** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| np.ndarray*) – Time in seconds to convert to samples. **Returns** The number of samples for the time to elapse **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") | np.ndarray ## Configuration | | | | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`InstructionScheduleMap`](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"")() | Mapping from [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") [`qiskit.circuit.Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") names and qubits to [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") s. In particular, the mapping is formatted as type::. | ## Exceptions ### PulseError Errors raised by the pulse module. Set the error message. ### BackendNotSet Raised if the builder context does not have a backend. Set the error message. ### NoActiveBuilder Raised if no builder context is active. Set the error message. ### UnassignedDurationError Raised if instruction duration is unassigned. Set the error message. ### UnassignedReferenceError Raised if subroutine is unassigned. Set the error message. ",repo/docs/api/qiskit/1.0\pulse.mdx "--- title: qasm2 description: API reference for qiskit.qasm2 in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.qasm2 --- # OpenQASM 2 `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). 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. ## 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 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"") ### loads 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"") 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. ### 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 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. 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. ### 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 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. ### 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`. ## 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 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. ### dumps 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)"") ## 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 A general error raised by the OpenQASM 2 interoperation layer. Set the error message. 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 An error raised because of a failure to parse an OpenQASM 2 file. Set the error message. 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 An error raised because of a failure to convert a Qiskit object to an OpenQASM 2 form. Set the error message. ## 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) ``` ## OpenQASM 2 Phase Conventions As a language, OpenQASM 2 does not have a way to specify the global phase of a complete program, nor of particular gate definitions. This means that parsers of the language may interpret particular gates with a different global phase than what you might expect. For example, the *de facto* standard library of OpenQASM 2 `qelib1.inc` contains definitions of `u1` and `rz` as follows: ```python gate u1(lambda) q { U(0, 0, lambda) q; } gate rz(phi) a { u1(phi) a; } ``` In other words, `rz` appears to be a direct alias for `u1`. However, the interpretation of `u1` is specified in [equation (3) of the paper describing the language](https://arxiv.org/abs/1707.03429) as $$ u_1(\lambda) = \operatorname{diag}\bigl(1, e^{i\lambda}\bigr) \sim R_z(\lambda) $$ where the $\sim$ symbol denotes equivalence only up to a global phase. When parsing OpenQASM 2, we need to choose how to handle a distinction between such gates; `u1` is defined in the prose to be different by a phase to `rz`, but the language is not designed to represent this. Qiskit’s default position is to interpret a usage of the standard-library `rz` using [`RZGate`](qiskit.circuit.library.RZGate ""qiskit.circuit.library.RZGate""), and a usage of `u1` as using the phase-distinct [`U1Gate`](qiskit.circuit.library.U1Gate ""qiskit.circuit.library.U1Gate""). If you wish to use the phase conventions more implied by a direct interpretation of the `gate` statements in the header file, you can use [`CustomInstruction`](#qiskit.qasm2.CustomInstruction ""qiskit.qasm2.CustomInstruction"") to override how Qiskit builds the circuit. For the standard `qelib1.inc` include there is only one point of difference, and so the override needed to switch its phase convention is: ```python from qiskit import qasm2 from qiskit.circuit.library import PhaseGate from qiskit.quantum_info import Operator program = """""" OPENQASM 2.0; include ""qelib1.inc""; qreg q[1]; rz(pi / 2) q[0]; """""" custom = [ qasm2.CustomInstruction(""rz"", 1, 1, PhaseGate), ] ``` This will use Qiskit’s [`PhaseGate`](qiskit.circuit.library.PhaseGate ""qiskit.circuit.library.PhaseGate"") class to represent the `rz` instruction, which is equal (including the phase) to [`U1Gate`](qiskit.circuit.library.U1Gate ""qiskit.circuit.library.U1Gate""): ```python Operator(qasm2.loads(program, custom_instructions=custom)) ``` ```python Operator([[1.000000e+00+0.j, 0.000000e+00+0.j], [0.000000e+00+0.j, 6.123234e-17+1.j]], input_dims=(2,), output_dims=(2,)) ``` ## 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. `/qasm/libs`, where `` is the root of the installed `qiskit` package; 2. the current working directory. * **there are additional instructions defined in `qelib1.inc`:** **`csx a, b`** Controlled $\sqrt X$ gate, corresponding to [`CSXGate`](qiskit.circuit.library.CSXGate ""qiskit.circuit.library.CSXGate""). **`cu(theta, phi, lambda, gamma) c, t`** The four-parameter version of a controlled-$U$, corresponding to [`CUGate`](qiskit.circuit.library.CUGate ""qiskit.circuit.library.CUGate""). **`rxx(theta) a, b`** Two-qubit rotation around the $XX$ axis, corresponding to [`RXXGate`](qiskit.circuit.library.RXXGate ""qiskit.circuit.library.RXXGate""). **`rzz(theta) a, b`** Two-qubit rotation around the $ZZ$ axis, corresponding to [`RZZGate`](qiskit.circuit.library.RZZGate ""qiskit.circuit.library.RZZGate""). **`rccx a, b, c`** The double-controlled $X$ gate, but with relative phase differences over the standard Toffoli gate. This *should* correspond to the Qiskit gate [`RCCXGate`](qiskit.circuit.library.RCCXGate ""qiskit.circuit.library.RCCXGate""), but the legacy converter wouldn’t actually output this type. **`rc3x a, b, c, d`** The triple-controlled $X$ gate, but with relative phase differences over the standard definition. Corresponds to [`RC3XGate`](qiskit.circuit.library.RC3XGate ""qiskit.circuit.library.RC3XGate""). **`c3x a, b, c, d`** The triple-controlled $X$ gate, corresponding to [`C3XGate`](qiskit.circuit.library.C3XGate ""qiskit.circuit.library.C3XGate""). **`c3sqrtx a, b, c, d`** The triple-controlled $\sqrt X$ gate, corresponding to [`C3SXGate`](qiskit.circuit.library.C3SXGate ""qiskit.circuit.library.C3SXGate""). **`c4x a, b, c, d, e`** The quadruple-controlled $X$ gate., corresponding to [`C4XGate`](qiskit.circuit.library.C4XGate ""qiskit.circuit.library.C4XGate""). * if *any* `opaque` or `gate` definition was given for the name `delay`, they attempt to output a [`Delay`](qiskit.circuit.Delay ""qiskit.circuit.Delay"") instruction at each call. To function, this expects a definition compatible with `opaque delay(t) q;`, where the time `t` is given in units of `dt`. The importer will raise errors on construction if there was not exactly one parameter and one qubit, or if the parameter is not integer-valued. * the additional scientific-calculator functions `asin`, `acos` and `atan` are available. * the parsed grammar is effectively the same as [the strict mode of the new importers](#qasm2-strict-mode). You can emulate this behaviour in [`load()`](#qiskit.qasm2.load ""qiskit.qasm2.load"") and [`loads()`](#qiskit.qasm2.loads ""qiskit.qasm2.loads"") by setting include\_path appropriately (try inspecting the variable `qiskit.__file__` to find the installed location), and by passing a list of [`CustomInstruction`](#qiskit.qasm2.CustomInstruction ""qiskit.qasm2.CustomInstruction"") instances for each of the custom gates you care about. To make things easier we make three tuples available, which each contain one component of a configuration that is equivalent to Qiskit’s legacy converter behaviour. **qiskit.qasm2.LEGACY\_CUSTOM\_INSTRUCTIONS** A tuple containing the extra custom\_instructions that Qiskit’s legacy built-in converters used if `qelib1.inc` is included, and there is any definition of a `delay` instruction. The gates in the paper version of `qelib1.inc` and `delay` all require a compatible declaration statement to be present within the OpenQASM 2 program, but Qiskit’s legacy additions are all marked as builtins since they are not actually present in any include file this parser sees. **qiskit.qasm2.LEGACY\_CUSTOM\_CLASSICAL** A tuple containing the extra custom\_classical functions that Qiskit’s legacy built-in converters use beyond those specified by the paper. This is the three basic inverse trigonometric functions: $\asin$, $\acos$ and $\atan$. **qiskit.qasm2.LEGACY\_INCLUDE\_PATH** A tuple containing the exact include\_path used by the legacy Qiskit converter. On *all* the gates defined in Qiskit’s legacy version of `qelib1.inc` and the `delay` instruction, it does not matter how the gates are actually defined and used, the legacy importer will always attempt to output its custom objects for them. This can result in errors during the circuit construction, even after a successful parse. There is no way to emulate this buggy behaviour with [`qiskit.qasm2`](#module-qiskit.qasm2 ""qiskit.qasm2""); only an `include ""qelib1.inc"";` statement or the custom\_instructions argument can cause built-in Qiskit instructions to be used, and the signatures of these match each other. Circuits imported with [`load()`](#qiskit.qasm2.load ""qiskit.qasm2.load"") and [`loads()`](#qiskit.qasm2.loads ""qiskit.qasm2.loads"") with the above legacy-compatibility settings should compare equal to those created by Qiskit’s legacy importer, provided no non-`qelib1.inc` user gates are defined. User-defined gates are handled slightly differently in the new importer, and while they should have equivalent [`definition`](qiskit.circuit.Instruction#definition ""qiskit.circuit.Instruction.definition"") fields on inspection, this module uses a custom class to lazily load the definition when it is requested (like most Qiskit objects), rather than eagerly creating it during the parse. Qiskit’s comparison rules for gates will see these two objects as unequal, although any pass through [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") for a particular backend should produce the same output circuits. ## Alternatives The parser components of this module started off as a separate PyPI package: [qiskit-qasm2](https://pypi.org/project/qiskit-qasm2/). This package at version 0.5.3 was vendored into Qiskit Terra 0.24. Any subsequent changes between the two packages may not necessarily be kept in sync. There is a newer version of the OpenQASM specification, version 3.0, which is described at [https://openqasm.com](https://openqasm.com). This includes far more facilities for high-level classical programming. Qiskit has some rudimentary support for OpenQASM 3 already; see [`qiskit.qasm3`](qasm3#module-qiskit.qasm3 ""qiskit.qasm3"") for that. OpenQASM 2 is not a suitable serialization language for Qiskit’s [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). This module is provided for interoperability purposes, not as a general serialization format. If that is what you need, consider using [`qiskit.qpy`](qpy#module-qiskit.qpy ""qiskit.qpy"") instead. ",repo/docs/api/qiskit/1.0\qasm2.mdx "--- title: qasm3 description: API reference for qiskit.qasm3 in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.qasm3 --- # OpenQASM 3 `qiskit.qasm3` Qiskit provides some tools for converting between [OpenQASM 3](https://openqasm.com) representations of quantum programs, and the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") class. These will continue to evolve as Qiskit’s support for the dynamic-circuit capabilities expressed by OpenQASM 3 increases. ## Exporting to OpenQASM 3 The high-level functions are simply [`dump()`](#qiskit.qasm3.dump ""qiskit.qasm3.dump"") and [`dumps()`](#qiskit.qasm3.dumps ""qiskit.qasm3.dumps""), which respectively export to a file (given as a filename) and to a Python string. ### dump 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. ### dumps 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)"") 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 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. **Parameter `allow_aliasing`** A value for `allow_aliasing` overrides any value given here, and supersedes this parameter. * **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 Convert the circuit to OpenQASM 3, dumping the result to a file or text stream. #### dumps Convert the circuit to OpenQASM 3, returning the result as a string. All of these interfaces will raise [`QASM3ExporterError`](#qiskit.qasm3.QASM3ExporterError ""qiskit.qasm3.QASM3ExporterError"") on failure. ### QASM3ExporterError An error raised during running the OpenQASM 3 exporter. Set the error message. ### 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 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 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; } } ``` 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) ``` 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. ## 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. 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. ### load 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""). ### loads 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""). Both of these two functions raise [`QASM3ImporterError`](#qiskit.qasm3.QASM3ImporterError ""qiskit.qasm3.QASM3ImporterError"") on failure. ### QASM3ImporterError An error raised during the OpenQASM 3 importer. Set the error message. 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 Load an OpenQASM 3 program from a source file into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). 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. **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. #### loads\_experimental Load an OpenQASM 3 program from a string into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). 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. **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. 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 Information received from Python space about how to construct a Python-space object to represent a given gate that might be declared. In `custom_gates` is not given, Qiskit will attempt to use its standard-library gate objects for the gates defined in OpenQASM 3 standard library file `stdgates.inc`. This sequence of gates is available on this module, if you wish to build on top of it: **qiskit.qasm3.STDGATES\_INC\_GATES** A tuple of [`CustomGate`](#qiskit.qasm3.CustomGate ""qiskit.qasm3.CustomGate"") objects specifying the Qiskit constructors to use for the `stdgates.inc` include file. ",repo/docs/api/qiskit/1.0\qasm3.mdx "--- title: RunConfig description: API reference for qiskit.assembler.RunConfig in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.assembler.RunConfig --- # RunConfig Bases: [`SimpleNamespace`](https://docs.python.org/3/library/types.html#types.SimpleNamespace ""(in Python v3.12)"") Class for Run Configuration. ### shots the number of shots **Type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### seed\_simulator the seed to use in the simulator **Type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### 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)"") ### 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)"")] 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 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"") ### 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)"") ",repo/docs/api/qiskit/1.0\qiskit.assembler.RunConfig.mdx "--- title: AncillaQubit description: API reference for qiskit.circuit.AncillaQubit in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.AncillaQubit --- # AncillaQubit Bases: [`Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") A qubit used as ancillary qubit. Creates a qubit. **Parameters** * **register** ([*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.QuantumRegister"")) – Optional. A quantum register containing the bit. * **index** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional. The index of the bit in its containing register. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if the provided register is not a valid [`QuantumRegister`](qiskit.circuit.QuantumRegister ""qiskit.circuit.QuantumRegister"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.AncillaQubit.mdx "--- title: AncillaRegister description: API reference for qiskit.circuit.AncillaRegister in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.AncillaRegister --- # AncillaRegister Bases: [`QuantumRegister`](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") Implement an ancilla register. Create a new generic register. Either the `size` or the `bits` argument must be provided. If `size` is not None, the register will be pre-populated with bits of the correct type. **Parameters** * **size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional. The number of bits to include in the register. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Optional. The name of the register. If not provided, a unique name will be auto-generated from the register type. * **bits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")*]*) – Optional. A list of Bit() instances to be used to populate the register. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if both the `size` and `bits` arguments are provided, or if neither are. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `size` is not valid. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `name` is not a valid name according to the OpenQASM spec. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `bits` contained duplicated bits. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `bits` contained bits of an incorrect type. ## Attributes ### instances\_counter ### name Get the register name. ### prefix ### size Get the register size. ## Methods ### index Find the index of the provided bit within this register. ",repo/docs/api/qiskit/1.0\qiskit.circuit.AncillaRegister.mdx "--- title: AnnotatedOperation description: API reference for qiskit.circuit.AnnotatedOperation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.AnnotatedOperation --- # AnnotatedOperation 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 Unique string identifier for operation type. ### num\_clbits Number of classical bits. ### num\_qubits Number of qubits. ## Methods ### control 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"") ### copy Return a copy of the [`AnnotatedOperation`](#qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation""). **Return type** [*AnnotatedOperation*](#qiskit.circuit.AnnotatedOperation ""qiskit.circuit.annotated_operation.AnnotatedOperation"") ### inverse 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. ### to\_matrix Return a matrix representation (allowing to construct Operator). ",repo/docs/api/qiskit/1.0\qiskit.circuit.AnnotatedOperation.mdx "--- title: Bit description: API reference for qiskit.circuit.Bit in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.Bit --- # Bit Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Implement a generic bit. This class should not be instantiated directly. This is just a superclass for [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"") and [`Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.Qubit""). Create a new generic bit. ",repo/docs/api/qiskit/1.0\qiskit.circuit.Bit.mdx "--- title: BreakLoopOp description: API reference for qiskit.circuit.BreakLoopOp in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.BreakLoopOp --- # BreakLoopOp Bases: [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"") A circuit operation which, when encountered, jumps to the end of the nearest enclosing loop. **Circuit symbol:** ```python ┌──────────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 ├ │ break_loop │ q_2: ┤2 ├ │ │ c_0: ╡0 ╞ └──────────────┘ ``` Create a new instruction. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – instruction name * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s qubit width * **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s clbit width * **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")*]*) – list of parameters * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – instruction’s duration. it must be integer if `unit` is ‘dt’ * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – time unit of duration * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or None*) – An optional label for identifying the instruction. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – when the register is not in the correct format. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – when the optional label is provided, but it is not a string. ## Attributes ### base\_class 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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. ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### 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"") ### soft\_compare 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)"") ### 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. ### validate\_parameter Instruction parameters has no validation or normalization. ",repo/docs/api/qiskit/1.0\qiskit.circuit.BreakLoopOp.mdx "--- title: CircuitInstruction description: API reference for qiskit.circuit.CircuitInstruction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.CircuitInstruction --- # CircuitInstruction 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. There is some possible confusion in the names of this class, [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction""), and [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation""), and this class’s attribute [`operation`](#qiskit.circuit.CircuitInstruction.operation ""qiskit.circuit.CircuitInstruction.operation""). Our preferred terminology is by analogy to assembly languages, where an “instruction” is made up of an “operation” and its “operands”. Historically, [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") came first, and originally contained the qubits it operated on and any parameters, so it was a true “instruction”. Over time, [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") became responsible for tracking qubits and clbits, and the class became better described as an “operation”. Changing the name of such a core object would be a very unpleasant API break for users, and so we have stuck with it. This class was created to provide a formal “instruction” context object in `QuantumCircuit.data`, which had long been made of ad-hoc tuples. With this, and the advent of the [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation"") interface for adding more complex objects to circuits, we took the opportunity to correct the historical naming. For the time being, this leads to an awkward case where [`CircuitInstruction.operation`](#qiskit.circuit.CircuitInstruction.operation ""qiskit.circuit.CircuitInstruction.operation"") is often an [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") instance ([`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") implements the [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation"") interface), but as the [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation"") interface gains more use, this confusion will hopefully abate. This is a lightweight internal class and there is minimal error checking; you must respect the type hints when using it. It is the user’s responsibility to ensure that direct mutations of the object do not invalidate the types, nor the restrictions placed on it by its context. Typically this will mean, for example, that [`qubits`](#qiskit.circuit.CircuitInstruction.qubits ""qiskit.circuit.CircuitInstruction.qubits"") must be a sequence of distinct items, with no duplicates. ## Attributes ### clbits A sequence of the classical bits that this operation reads from or writes to. ### operation The logical operation that this instruction represents an execution of. ### qubits A sequence of the qubits that the operation is applied to. ## Methods ### copy Returns a shallow copy. **Returns** The shallow copy. **Return type** [CircuitInstruction](#qiskit.circuit.CircuitInstruction ""qiskit.circuit.CircuitInstruction"") ### replace 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"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.CircuitInstruction.mdx "--- title: BooleanExpression description: API reference for qiskit.circuit.classicalfunction.BooleanExpression in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.classicalfunction.BooleanExpression --- # BooleanExpression 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 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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)"")]] ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### control 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 ### copy 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"") ### from\_dimacs\_file 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. ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### power 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 ### repeat 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. ### 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"") ### simulate 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)"") ### soft\_compare 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)"") ### synth 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"") ### 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. ### 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. ### validate\_parameter Gate parameters should be int, float, or ParameterExpression ",repo/docs/api/qiskit/1.0\qiskit.circuit.classicalfunction.BooleanExpression.mdx "--- title: ClassicalFunction description: API reference for qiskit.circuit.classicalfunction.ClassicalFunction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.classicalfunction.ClassicalFunction --- # ClassicalFunction 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 Returns the classicalfunction arguments ### 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### network Returns the logical network ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### qregs The list of qregs used by the classicalfunction ### scopes Returns the scope dict ### truth\_table Returns (and computes) the truth table ### 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)"")) ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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)"")]] ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### compile Parses and creates the logical circuit ### control 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 ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### power 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 ### repeat 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. ### 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"") ### simulate 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)"") ### 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)"") ### soft\_compare 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)"") ### synth Synthesis the logic network into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). **Parameters** * **registerless** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Default `True`. If `False` uses the parameter names to create * **Otherwise** (*registers with those names.*) – * **register.** (*creates a circuit with a flat quantum*) – * **synthesizer** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[ClassicalElement],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")*] | None*) – Optional. If None tweedledum’s pkrm\_synth is used. **Returns** A circuit implementing the logic network. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### 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. ### 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. ### validate\_parameter Gate parameters should be int, float, or ParameterExpression ",repo/docs/api/qiskit/1.0\qiskit.circuit.classicalfunction.ClassicalFunction.mdx "--- title: ClassicalFunctionCompilerTypeError description: API reference for qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError --- # qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError ClassicalFunction compiler type error. The classicalfunction function fails at type checking time. Set the error message. ",repo/docs/api/qiskit/1.0\qiskit.circuit.classicalfunction.ClassicalFunctionCompilerTypeError.mdx "--- title: ClassicalFunctionParseError description: API reference for qiskit.circuit.classicalfunction.ClassicalFunctionParseError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit.circuit.classicalfunction.ClassicalFunctionParseError --- # qiskit.circuit.classicalfunction.ClassicalFunctionParseError ClassicalFunction compiler parse error. The classicalfunction function fails at parsing time. Set the error message. ",repo/docs/api/qiskit/1.0\qiskit.circuit.classicalfunction.ClassicalFunctionParseError.mdx "--- title: ClassicalRegister description: API reference for qiskit.circuit.ClassicalRegister in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.ClassicalRegister --- # ClassicalRegister Bases: [`Register`](qiskit.circuit.Register ""qiskit.circuit.register.Register"") Implement a classical register. Create a new generic register. Either the `size` or the `bits` argument must be provided. If `size` is not None, the register will be pre-populated with bits of the correct type. **Parameters** * **size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional. The number of bits to include in the register. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Optional. The name of the register. If not provided, a unique name will be auto-generated from the register type. * **bits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")*]*) – Optional. A list of Bit() instances to be used to populate the register. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if both the `size` and `bits` arguments are provided, or if neither are. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `size` is not valid. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `name` is not a valid name according to the OpenQASM spec. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `bits` contained duplicated bits. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `bits` contained bits of an incorrect type. ## Attributes ### instances\_counter ### name Get the register name. ### prefix ### size Get the register size. ## Methods ### index Find the index of the provided bit within this register. ",repo/docs/api/qiskit/1.0\qiskit.circuit.ClassicalRegister.mdx "--- title: Clbit description: API reference for qiskit.circuit.Clbit in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.Clbit --- # Clbit Bases: [`Bit`](qiskit.circuit.Bit ""qiskit.circuit.bit.Bit"") Implement a classical bit. Creates a classical bit. **Parameters** * **register** ([*ClassicalRegister*](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"")) – Optional. A classical register containing the bit. * **index** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional. The index of the bit in its containing register. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if the provided register is not a valid [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.Clbit.mdx "--- title: CommutationChecker description: API reference for qiskit.circuit.CommutationChecker in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.CommutationChecker --- # CommutationChecker Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") This code is essentially copy-pasted from commutative\_analysis.py. This code cleverly hashes commutativity and non-commutativity results between DAG nodes and seems quite efficient for large Clifford circuits. They may be other possible efficiency improvements: using rule-based commutativity analysis, evicting from the cache less useful entries, etc. ## Methods ### check\_commutation\_entries Returns stored commutation relation if any **Parameters** * **first\_op** ([*Operation*](qiskit.circuit.Operation ""qiskit.circuit.operation.Operation"")) – first operation. * **first\_qargs** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")) – first operation’s qubits. * **second\_op** ([*Operation*](qiskit.circuit.Operation ""qiskit.circuit.operation.Operation"")) – second operation. * **second\_qargs** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")) – second operation’s qubits. **Returns** True if the gates commute and false if it is not the case. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### clear\_cached\_commutations Clears the dictionary holding cached commutations ### commute Checks if two Operations commute. The return value of True means that the operations truly commute, and the return value of False means that either the operations do not commute or that the commutation check was skipped (for example, when the operations have conditions or have too many qubits). **Parameters** * **op1** ([*Operation*](qiskit.circuit.Operation ""qiskit.circuit.operation.Operation"")) – first operation. * **qargs1** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")) – first operation’s qubits. * **cargs1** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")) – first operation’s clbits. * **op2** ([*Operation*](qiskit.circuit.Operation ""qiskit.circuit.operation.Operation"")) – second operation. * **qargs2** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")) – second operation’s qubits. * **cargs2** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")) – second operation’s clbits. * **max\_num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the maximum number of qubits to consider, the check may be skipped if the number of qubits for either operation exceeds this amount. **Returns** whether two operations commute. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### num\_cached\_entries Returns number of cached entries ",repo/docs/api/qiskit/1.0\qiskit.circuit.CommutationChecker.mdx "--- title: ContinueLoopOp description: API reference for qiskit.circuit.ContinueLoopOp in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.ContinueLoopOp --- # ContinueLoopOp 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. Can be inserted only within the body of a loop op, and must span the full width of that block. **Circuit symbol:** ```python ┌─────────────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 ├ │ continue_loop │ q_2: ┤2 ├ │ │ c_0: ╡0 ╞ └─────────────────┘ ``` Create a new instruction. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – instruction name * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s qubit width * **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s clbit width * **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")*]*) – list of parameters * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – instruction’s duration. it must be integer if `unit` is ‘dt’ * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – time unit of duration * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or None*) – An optional label for identifying the instruction. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – when the register is not in the correct format. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – when the optional label is provided, but it is not a string. ## Attributes ### base\_class 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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. ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### 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"") ### soft\_compare 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)"") ### 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. ### validate\_parameter Instruction parameters has no validation or normalization. ",repo/docs/api/qiskit/1.0\qiskit.circuit.ContinueLoopOp.mdx "--- title: ControlFlowOp description: API reference for qiskit.circuit.ControlFlowOp in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.ControlFlowOp --- # ControlFlowOp Bases: [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction""), [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Abstract class to encapsulate all control flow operations. Create a new instruction. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – instruction name * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s qubit width * **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s clbit width * **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")*]*) – list of parameters * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – instruction’s duration. it must be integer if `unit` is ‘dt’ * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – time unit of duration * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or None*) – An optional label for identifying the instruction. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – when the register is not in the correct format. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – when the optional label is provided, but it is not a string. ## Attributes ### base\_class 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. ### 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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. ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### replace\_blocks 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"") ### 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"") ### soft\_compare 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)"") ### 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. ### validate\_parameter Instruction parameters has no validation or normalization. ",repo/docs/api/qiskit/1.0\qiskit.circuit.ControlFlowOp.mdx "--- title: ControlledGate description: API reference for qiskit.circuit.ControlledGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.ControlledGate --- # ControlledGate 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 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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)"")]] ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### control 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 ### copy 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"") ### inverse Invert this gate by calling inverse on the base gate. **Return type** ControlledGate’ | ‘AnnotatedOperation ### is\_parameterized Return True .IFF. instruction is parameterized else False ### power 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 ### repeat 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. ### 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"") ### soft\_compare 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)"") ### 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. ### 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. ### validate\_parameter Gate parameters should be int, float, or ParameterExpression ",repo/docs/api/qiskit/1.0\qiskit.circuit.ControlledGate.mdx "--- title: ControlModifier description: API reference for qiskit.circuit.ControlModifier in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.ControlModifier --- # ControlModifier Bases: `Modifier` Control modifier: specifies that the operation is controlled by `num_ctrl_qubits` and has control state `ctrl_state`. ## Attributes ### ctrl\_state ### num\_ctrl\_qubits ",repo/docs/api/qiskit/1.0\qiskit.circuit.ControlModifier.mdx "--- title: Delay description: API reference for qiskit.circuit.Delay in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.Delay --- # Delay Bases: [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"") Do nothing and just delay/wait/idle for a specified duration. Create new delay instruction. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.Delay.base_class ""qiskit.circuit.Delay.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that [`Instruction.name`](qiskit.circuit.Instruction#name ""qiskit.circuit.Instruction.name"") should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration of this delay. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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)"")]] ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### copy 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"") ### inverse Special case. Return self. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### 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"") ### soft\_compare 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)"") ### to\_matrix Return a Numpy.array for the unitary matrix. This has been added to enable simulation without making delay a full Gate type. **Returns** matrix representation. **Return type** np.ndarray ### 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. ### validate\_parameter Delay parameter (i.e. duration) must be int, float or ParameterExpression. ",repo/docs/api/qiskit/1.0\qiskit.circuit.Delay.mdx "--- title: EquivalenceLibrary description: API reference for qiskit.circuit.EquivalenceLibrary in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.EquivalenceLibrary --- # EquivalenceLibrary 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 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 ## Methods ### add\_equivalence 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. ### draw 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. ### get\_entry 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"")] ### has\_entry 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"") ### keys Return list of keys to key to node index map. **Returns** Keys to the key to node index map. **Return type** List ### node\_index 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 ### set\_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. ",repo/docs/api/qiskit/1.0\qiskit.circuit.EquivalenceLibrary.mdx "--- title: ForLoopOp description: API reference for qiskit.circuit.ForLoopOp in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.ForLoopOp --- # ForLoopOp Bases: [`ControlFlowOp`](qiskit.circuit.ControlFlowOp ""qiskit.circuit.controlflow.control_flow.ControlFlowOp"") A circuit operation which repeatedly executes a subcircuit (`body`) parameterized by a parameter `loop_parameter` through the set of integer values provided in `indexset`. **Parameters** * **indexset** (*Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – A collection of integers to loop over. * **loop\_parameter** (*Union\[*[*Parameter*](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")*, None]*) – The placeholder parameterizing `body` to which the values from `indexset` will be assigned. * **body** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – The loop body to be repeatedly executed. * **label** (*Optional\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – An optional label for identifying the instruction. **Circuit symbol:** ```python ┌───────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 ├ │ for_loop │ q_2: ┤2 ├ │ │ c_0: ╡0 ╞ └───────────┘ ``` Create a new instruction. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – instruction name * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s qubit width * **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s clbit width * **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")*]*) – list of parameters * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – instruction’s duration. it must be integer if `unit` is ‘dt’ * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – time unit of duration * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or None*) – An optional label for identifying the instruction. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – when the register is not in the correct format. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – when the optional label is provided, but it is not a string. ## Attributes ### base\_class 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. ### blocks ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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. ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### replace\_blocks Replace blocks and return new instruction. :param blocks: Tuple of QuantumCircuits to replace in instruction. **Returns** New ControlFlowOp with replaced blocks. ### 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"") ### soft\_compare 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)"") ### 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. ### validate\_parameter Instruction parameters has no validation or normalization. ",repo/docs/api/qiskit/1.0\qiskit.circuit.ForLoopOp.mdx "--- title: Gate description: API reference for qiskit.circuit.Gate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.Gate --- # Gate 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 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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)"")]] ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### control 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 ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### power 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 ### repeat 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. ### 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"") ### soft\_compare 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)"") ### 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. ### 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. ### validate\_parameter Gate parameters should be int, float, or ParameterExpression ",repo/docs/api/qiskit/1.0\qiskit.circuit.Gate.mdx "--- title: IfElseOp description: API reference for qiskit.circuit.IfElseOp in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.IfElseOp --- # IfElseOp Bases: [`ControlFlowOp`](qiskit.circuit.ControlFlowOp ""qiskit.circuit.controlflow.control_flow.ControlFlowOp"") A circuit operation which executes a program (`true_body`) if a provided condition (`condition`) evaluates to true, and optionally evaluates another program (`false_body`) otherwise. **Parameters** * **condition** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*ClassicalRegister*](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] |* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] |* [*expr.Expr*](circuit_classical#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.Expr"")) – A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of `true_body`. Can be specified as either a tuple of a `ClassicalRegister` to be tested for equality with a given `int`, or as a tuple of a `Clbit` to be compared to either a `bool` or an `int`. * **true\_body** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – A program to be executed if `condition` evaluates to true. * **false\_body** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *| None*) – A optional program to be executed if `condition` evaluates to false. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for identifying the instruction. If provided, `false_body` must be of the same `num_qubits` and `num_clbits` as `true_body`. The classical bits used in `condition` must be a subset of those attached to the circuit on which this `IfElseOp` will be appended. **Circuit symbol:** ```python ┌───────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 ├ │ if_else │ q_2: ┤2 ├ │ │ c_0: ╡0 ╞ └───────────┘ ``` Create a new instruction. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – instruction name * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s qubit width * **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s clbit width * **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")*]*) – list of parameters * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – instruction’s duration. it must be integer if `unit` is ‘dt’ * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – time unit of duration * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or None*) – An optional label for identifying the instruction. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – when the register is not in the correct format. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – when the optional label is provided, but it is not a string. ## Attributes ### base\_class 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. ### blocks ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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. ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### replace\_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"") ### 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"") ### soft\_compare 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)"") ### 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. ### validate\_parameter Instruction parameters has no validation or normalization. ",repo/docs/api/qiskit/1.0\qiskit.circuit.IfElseOp.mdx "--- title: Instruction description: API reference for qiskit.circuit.Instruction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.Instruction --- # Instruction Bases: [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.operation.Operation"") Generic quantum instruction. Create a new instruction. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – instruction name * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s qubit width * **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s clbit width * **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")*]*) – list of parameters * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – instruction’s duration. it must be integer if `unit` is ‘dt’ * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – time unit of duration * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or None*) – An optional label for identifying the instruction. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – when the register is not in the correct format. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – when the optional label is provided, but it is not a string. ## Attributes ### base\_class 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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. ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### 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"") ### soft\_compare 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)"") ### 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. ### validate\_parameter Instruction parameters has no validation or normalization. ",repo/docs/api/qiskit/1.0\qiskit.circuit.Instruction.mdx "--- title: InstructionSet description: API reference for qiskit.circuit.InstructionSet in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.InstructionSet --- # InstructionSet 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. 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. ## Attributes ### cargs Legacy getter for the cargs components of an instruction set. This does not support mutation. ### instructions Legacy getter for the instruction components of an instruction set. This does not support mutation. ### qargs Legacy getter for the qargs components of an instruction set. This does not support mutation. ## Methods ### add Add an instruction and its context (where it is attached). ### c\_if 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`. 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. **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) ### inverse Invert all instructions. ",repo/docs/api/qiskit/1.0\qiskit.circuit.InstructionSet.mdx "--- title: InverseModifier description: API reference for qiskit.circuit.InverseModifier in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.InverseModifier --- # InverseModifier Bases: `Modifier` Inverse modifier: specifies that the operation is inverted. ",repo/docs/api/qiskit/1.0\qiskit.circuit.InverseModifier.mdx "--- title: AND description: API reference for qiskit.circuit.library.AND in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.AND --- # AND 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 Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.AND.mdx "--- title: Barrier description: API reference for qiskit.circuit.library.Barrier in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.Barrier --- # Barrier Bases: [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"") Barrier instruction. A barrier is a visual indicator of the grouping of a circuit section. It also acts as a directive for circuit compilation to separate pieces of a circuit so that any optimizations or re-writes are constrained to only act between barriers. Create new barrier instruction. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of qubits for the barrier type \[Default: 0]. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – the barrier label **Raises** [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – if barrier label is invalid. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.Barrier.base_class ""qiskit.circuit.library.Barrier.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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. ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### copy 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"") ### inverse Special case. Return self. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### 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"") ### soft\_compare 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)"") ### 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. ### validate\_parameter Instruction parameters has no validation or normalization. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.Barrier.mdx "--- title: C3SXGate description: API reference for qiskit.circuit.library.C3SXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.C3SXGate --- # C3SXGate 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 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.C3SXGate.mdx "--- title: C3XGate description: API reference for qiskit.circuit.library.C3XGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.C3XGate --- # C3XGate 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 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### control 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"") ### inverse 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"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.C3XGate.mdx "--- title: C4XGate description: API reference for qiskit.circuit.library.C4XGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.C4XGate --- # C4XGate 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 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### control 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"") ### inverse 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"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.C4XGate.mdx "--- title: CCXGate description: API reference for qiskit.circuit.library.CCXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CCXGate --- # CCXGate 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} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_2 and q\_1. Thus a textbook matrix for this gate will be: ```python ┌───┐ q_0: ┤ X ├ └─┬─┘ q_1: ──■── │ q_2: ──■── ``` $$ CCX\ q_2, q_1, q_0 = |0 \rangle \langle 0| \otimes I \otimes I + |1 \rangle \langle 1| \otimes CX = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1\\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \end{pmatrix} $$ Create new CCX gate. ## Attributes ### 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### control 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"") ### inverse 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"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CCXGate.mdx "--- title: CCZGate description: API reference for qiskit.circuit.library.CCZGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CCZGate --- # CCZGate 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 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse 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"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CCZGate.mdx "--- title: CDKMRippleCarryAdder description: API reference for qiskit.circuit.library.CDKMRippleCarryAdder in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CDKMRippleCarryAdder --- # CDKMRippleCarryAdder Bases: `Adder` A ripple-carry circuit to perform in-place addition on two qubit registers. As an example, a ripple-carry adder circuit that performs addition on two 3-qubit sized registers with a carry-in bit (`kind=""full""`) is as follows: ```python ┌──────┐ ┌──────┐ cin_0: ┤2 ├─────────────────────────────────────┤2 ├ │ │┌──────┐ ┌──────┐│ │ a_0: ┤0 ├┤2 ├─────────────────────┤2 ├┤0 ├ │ ││ │┌──────┐ ┌──────┐│ ││ │ a_1: ┤ MAJ ├┤0 ├┤2 ├─────┤2 ├┤0 ├┤ UMA ├ │ ││ ││ │ │ ││ ││ │ a_2: ┤ ├┤ MAJ ├┤0 ├──■──┤0 ├┤ UMA ├┤ ├ │ ││ ││ │ │ │ ││ ││ │ b_0: ┤1 ├┤ ├┤ MAJ ├──┼──┤ UMA ├┤ ├┤1 ├ └──────┘│ ││ │ │ │ ││ │└──────┘ b_1: ────────┤1 ├┤ ├──┼──┤ ├┤1 ├──────── └──────┘│ │ │ │ │└──────┘ b_2: ────────────────┤1 ├──┼──┤1 ├──────────────── └──────┘┌─┴─┐└──────┘ cout_0: ────────────────────────┤ X ├──────────────────────── └───┘ ``` Here *MAJ* and *UMA* gates correspond to the gates introduced in \[1]. Note that in this implementation the input register qubits are ordered as all qubits from the first input register, followed by all qubits from the second input register. Two different kinds of adders are supported. By setting the `kind` argument, you can also choose a half-adder, which doesn’t have a carry-in, and a fixed-sized-adder, which has neither carry-in nor carry-out, and thus acts on fixed register sizes. Unlike the full-adder, these circuits need one additional helper qubit. The circuit diagram for the fixed-point adder (`kind=""fixed""`) on 3-qubit sized inputs is ```python ┌──────┐┌──────┐ ┌──────┐┌──────┐ a_0: ┤0 ├┤2 ├────────────────┤2 ├┤0 ├ │ ││ │┌──────┐┌──────┐│ ││ │ a_1: ┤ ├┤0 ├┤2 ├┤2 ├┤0 ├┤ ├ │ ││ ││ ││ ││ ││ │ a_2: ┤ ├┤ MAJ ├┤0 ├┤0 ├┤ UMA ├┤ ├ │ ││ ││ ││ ││ ││ │ b_0: ┤1 MAJ ├┤ ├┤ MAJ ├┤ UMA ├┤ ├┤1 UMA ├ │ ││ ││ ││ ││ ││ │ b_1: ┤ ├┤1 ├┤ ├┤ ├┤1 ├┤ ├ │ │└──────┘│ ││ │└──────┘│ │ b_2: ┤ ├────────┤1 ├┤1 ├────────┤ ├ │ │ └──────┘└──────┘ │ │ help_0: ┤2 ├────────────────────────────────┤2 ├ └──────┘ └──────┘ ``` It has one less qubit than the full-adder since it doesn’t have the carry-out, but uses a helper qubit instead of the carry-in, so it only has one less qubit, not two. **References:** \[1] Cuccaro et al., A new quantum ripple-carry addition circuit, 2004. [arXiv:quant-ph/0410184](https://arxiv.org/pdf/quant-ph/0410184.pdf) \[2] Vedral et al., Quantum Networks for Elementary Arithmetic Operations, 1995. [arXiv:quant-ph/9511018](https://arxiv.org/pdf/quant-ph/9511018.pdf) **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits in either input register for state $|a\rangle$ or $|b\rangle$. The two input registers must have the same number of qubits. * **kind** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The kind of adder, can be `'full'` for a full adder, `'half'` for a half adder, or `'fixed'` for a fixed-sized adder. A full adder includes both carry-in and carry-out, a half only carry-out, and a fixed-sized adder neither carry-in nor carry-out. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit object. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If `num_state_qubits` is lower than 1. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### num\_state\_qubits The number of state qubits, i.e. the number of bits in each input register. **Returns** The number of state qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CDKMRippleCarryAdder.mdx "--- title: CHGate description: API reference for qiskit.circuit.library.CHGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CHGate --- # CHGate 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} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be: ```python ┌───┐ q_0: ┤ H ├ └─┬─┘ q_1: ──■── ``` $$ CH\ q_1, q_0 = |0\rangle\langle 0| \otimes I + |1\rangle\langle 1| \otimes H = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\ 0 & 0 & \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}} \end{pmatrix} $$ Create new CH gate. ## Attributes ### 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse Return inverted CH gate (itself). ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CHGate.mdx "--- title: CPhaseGate description: API reference for qiskit.circuit.library.CPhaseGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CPhaseGate --- # CPhaseGate 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} $$ `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. Create new CPhase gate. ## Attributes ### 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### control 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"") ### inverse Return inverted CPhase gate ($CPhase(\lambda)^{\dagger} = CPhase(-\lambda)$) ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CPhaseGate.mdx "--- title: CRXGate description: API reference for qiskit.circuit.library.CRXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CRXGate --- # CRXGate 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} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be: ```python ┌───────┐ q_0: ┤ Rx(ϴ) ├ └───┬───┘ q_1: ────■──── ``` $$ \newcommand{\rotationangle}{\frac{\theta}{2}} CRX(\theta)\ q_1, q_0 = |0\rangle\langle0| \otimes I + |1\rangle\langle1| \otimes RX(\theta) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \cos\left(\rotationangle\right) & -i\sin\left(\rotationangle\right) \\ 0 & 0 & -i\sin\left(\rotationangle\right) & \cos\left(\rotationangle\right) \end{pmatrix} $$ Create new CRX gate. ## Attributes ### 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse 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"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CRXGate.mdx "--- title: CRYGate description: API reference for qiskit.circuit.library.CRYGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CRYGate --- # CRYGate 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} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be: ```python ┌───────┐ q_0: ┤ Ry(ϴ) ├ └───┬───┘ q_1: ────■──── ``` $$ \newcommand{\rotationangle}{\frac{\theta}{2}} CRY(\theta)\ q_1, q_0 = |0\rangle\langle 0| \otimes I + |1\rangle\langle 1| \otimes RY(\theta) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \cos\left(\rotationangle\right) & -\sin\left(\rotationangle\right) \\ 0 & 0 & \sin\left(\rotationangle\right) & \cos\left(\rotationangle\right) \end{pmatrix} $$ Create new CRY gate. ## Attributes ### 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse 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"") . ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CRYGate.mdx "--- title: CRZGate description: API reference for qiskit.circuit.library.CRZGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CRZGate --- # CRZGate 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} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be: ```python ┌───────┐ q_0: ┤ Rz(λ) ├ └───┬───┘ q_1: ────■──── ``` $$ CRZ(\lambda)\ q_1, q_0 = |0\rangle\langle 0| \otimes I + |1\rangle\langle 1| \otimes RZ(\lambda) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & e^{-i\frac{\lambda}{2}} & 0 \\ 0 & 0 & 0 & e^{i\frac{\lambda}{2}} \end{pmatrix} $$ `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. Create new CRZ gate. ## Attributes ### 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse 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. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CRZGate.mdx "--- title: CSdgGate description: API reference for qiskit.circuit.library.CSdgGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CSdgGate --- # CSdgGate 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 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse 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"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CSdgGate.mdx "--- title: CSGate description: API reference for qiskit.circuit.library.CSGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CSGate --- # CSGate 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 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse 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"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CSGate.mdx "--- title: CSwapGate description: API reference for qiskit.circuit.library.CSwapGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CSwapGate --- # CSwapGate 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} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_2. Thus a textbook matrix for this gate will be: ```python q_0: ─X─ │ q_1: ─X─ │ q_2: ─■─ ``` $$ CSWAP\ q_2, q_1, q_0 = |0 \rangle \langle 0| \otimes I \otimes I + |1 \rangle \langle 1| \otimes SWAP = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ \end{pmatrix} $$ 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 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse 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"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CSwapGate.mdx "--- title: CSXGate description: API reference for qiskit.circuit.library.CSXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CSXGate --- # CSXGate 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} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be: ```python ┌────┐ q_0: ┤ √X ├ └─┬──┘ q_1: ──■── ``` $$ C\sqrt{X}\ q_1, q_0 = |0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes \sqrt{X} = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & (1 + i) / 2 & (1 - i) / 2 \\ 0 & 0 & (1 - i) / 2 & (1 + i) / 2 \end{pmatrix} $$ Create new CSX gate. ## Attributes ### 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CSXGate.mdx "--- title: CU1Gate description: API reference for qiskit.circuit.library.CU1Gate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CU1Gate --- # CU1Gate 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} $$ `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. Create new CU1 gate. ## Attributes ### 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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### control 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"") ### inverse 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"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CU1Gate.mdx "--- title: CU3Gate description: API reference for qiskit.circuit.library.CU3Gate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CU3Gate --- # CU3Gate Bases: [`ControlledGate`](qiskit.circuit.ControlledGate ""qiskit.circuit.controlledgate.ControlledGate"") Controlled-U3 gate (3-parameter two-qubit gate). This is a controlled version of the U3 gate (generic single qubit rotation). It is restricted to 3 parameters, and so cannot cover generic two-qubit controlled gates). **Circuit symbol:** ```python q_0: ──────■────── ┌─────┴─────┐ q_1: ┤ U3(ϴ,φ,λ) ├ └───────────┘ ``` **Matrix representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} CU3(\theta, \phi, \lambda)\ q_0, q_1 = I \otimes |0\rangle\langle 0| + U3(\theta,\phi,\lambda) \otimes |1\rangle\langle 1| = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos(\rotationangle) & 0 & -e^{i\lambda}\sin(\rotationangle) \\ 0 & 0 & 1 & 0 \\ 0 & e^{i\phi}\sin(\rotationangle) & 0 & e^{i(\phi+\lambda)}\cos(\rotationangle) \end{pmatrix} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be: ```python ┌───────────┐ q_0: ┤ U3(ϴ,φ,λ) ├ └─────┬─────┘ q_1: ──────■────── ``` $$ \newcommand{\rotationangle}{\frac{\theta}{2}} CU3(\theta, \phi, \lambda)\ q_1, q_0 = |0\rangle\langle 0| \otimes I + |1\rangle\langle 1| \otimes U3(\theta,\phi,\lambda) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \cos(\rotationangle) & -e^{i\lambda}\sin(\rotationangle) \\ 0 & 0 & e^{i\phi}\sin(\rotationangle) & e^{i(\phi+\lambda)}\cos(\rotationangle) \end{pmatrix} $$ Create new CU3 gate. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CU3Gate.base_class ""qiskit.circuit.library.CU3Gate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse Return inverted CU3 gate. $CU3(\theta,\phi,\lambda)^{\dagger} =CU3(-\theta,-\phi,-\lambda))$ **Parameters** **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). However, for this class this argument is ignored as the inverse of this gate is always a [`CU3Gate`](#qiskit.circuit.library.CU3Gate ""qiskit.circuit.library.CU3Gate"") with inverse parameter values. **Returns** inverse gate. **Return type** [CU3Gate](#qiskit.circuit.library.CU3Gate ""qiskit.circuit.library.CU3Gate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CU3Gate.mdx "--- title: CUGate description: API reference for qiskit.circuit.library.CUGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CUGate --- # CUGate Bases: [`ControlledGate`](qiskit.circuit.ControlledGate ""qiskit.circuit.controlledgate.ControlledGate"") Controlled-U gate (4-parameter two-qubit gate). This is a controlled version of the U gate (generic single qubit rotation), including a possible global phase $e^{i\gamma}$ of the U gate. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`cu()`](qiskit.circuit.QuantumCircuit#cu ""qiskit.circuit.QuantumCircuit.cu"") method. **Circuit symbol:** ```python q_0: ──────■────── ┌─────┴──────┐ q_1: ┤ U(ϴ,φ,λ,γ) ├ └────────────┘ ``` **Matrix representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} CU(\theta, \phi, \lambda, \gamma)\ q_0, q_1 = I \otimes |0\rangle\langle 0| + e^{i\gamma} U(\theta,\phi,\lambda) \otimes |1\rangle\langle 1| = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & e^{i\gamma}\cos(\rotationangle) & 0 & -e^{i(\gamma + \lambda)}\sin(\rotationangle) \\ 0 & 0 & 1 & 0 \\ 0 & e^{i(\gamma+\phi)}\sin(\rotationangle) & 0 & e^{i(\gamma+\phi+\lambda)}\cos(\rotationangle) \end{pmatrix} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be: ```python ┌────────────┐ q_0: ┤ U(ϴ,φ,λ,γ) ├ └─────┬──────┘ q_1: ──────■─────── ``` $$ \newcommand{\rotationangle}{\frac{\theta}{2}} CU(\theta, \phi, \lambda, \gamma)\ q_1, q_0 = |0\rangle\langle 0| \otimes I + e^{i\gamma}|1\rangle\langle 1| \otimes U(\theta,\phi,\lambda) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & e^{i\gamma} \cos(\rotationangle) & -e^{i(\gamma + \lambda)}\sin(\rotationangle) \\ 0 & 0 & e^{i(\gamma + \phi)}\sin(\rotationangle) & e^{i(\gamma + \phi+\lambda)}\cos(\rotationangle) \end{pmatrix} $$ Create new CU gate. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CUGate.base_class ""qiskit.circuit.library.CUGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### params ### unit Get the time unit of duration. ## Methods ### inverse Return inverted CU gate. $CU(\theta,\phi,\lambda,\gamma)^{\dagger} = CU(-\theta,-\phi,-\lambda,-\gamma))$ **Parameters** **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). However, for this class this argument is ignored as the inverse of this gate is always a [`CUGate`](#qiskit.circuit.library.CUGate ""qiskit.circuit.library.CUGate"") with inverse parameter values. **Returns** inverse gate. **Return type** [CUGate](#qiskit.circuit.library.CUGate ""qiskit.circuit.library.CUGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CUGate.mdx "--- title: CXGate description: API reference for qiskit.circuit.library.CXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CXGate --- # CXGate Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate ""qiskit.circuit.singleton.SingletonControlledGate"") Controlled-X gate. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`cx()`](qiskit.circuit.QuantumCircuit#cx ""qiskit.circuit.QuantumCircuit.cx"") and `cnot()` methods. **Circuit symbol:** ```python q_0: ──■── ┌─┴─┐ q_1: ┤ X ├ └───┘ ``` **Matrix representation:** $$ CX\ q_0, q_1 = I \otimes |0\rangle\langle0| + X \otimes |1\rangle\langle1| = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \end{pmatrix} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be: ```python ┌───┐ q_0: ┤ X ├ └─┬─┘ q_1: ──■── ``` $$ CX\ q_1, q_0 = |0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes X = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{pmatrix} $$ In the computational basis, this gate flips the target qubit if the control qubit is in the $|1\rangle$ state. In this sense it is similar to a classical XOR gate. $$ `|a, b\rangle \rightarrow |a, a \oplus b\rangle` $$ Create new CX gate. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CXGate.base_class ""qiskit.circuit.library.CXGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### control Return a controlled-X gate with more control lines. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### inverse Return inverted CX gate (itself). **Parameters** **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). However, for this class this argument is ignored as this gate is self-inverse. **Returns** inverse gate (self-inverse). **Return type** [CXGate](#qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CXGate.mdx "--- title: CYGate description: API reference for qiskit.circuit.library.CYGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CYGate --- # CYGate Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate ""qiskit.circuit.singleton.SingletonControlledGate"") Controlled-Y gate. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`cy()`](qiskit.circuit.QuantumCircuit#cy ""qiskit.circuit.QuantumCircuit.cy"") method. **Circuit symbol:** ```python q_0: ──■── ┌─┴─┐ q_1: ┤ Y ├ └───┘ ``` **Matrix representation:** $$ CY\ q_0, q_1 = I \otimes |0 \rangle\langle 0| + Y \otimes |1 \rangle\langle 1| = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & -i \\ 0 & 0 & 1 & 0 \\ 0 & i & 0 & 0 \end{pmatrix} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In many textbooks, controlled gates are presented with the assumption of more significant qubits as control, which in our case would be q\_1. Thus a textbook matrix for this gate will be: ```python ┌───┐ q_0: ┤ Y ├ └─┬─┘ q_1: ──■── ``` $$ CY\ q_1, q_0 = |0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes Y = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & -i \\ 0 & 0 & i & 0 \end{pmatrix} $$ Create new CY gate. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CYGate.base_class ""qiskit.circuit.library.CYGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse Return inverted CY gate (itself). **Parameters** **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). However, for this class this argument is ignored as this gate is self-inverse. **Returns** inverse gate (self-inverse). **Return type** [CYGate](#qiskit.circuit.library.CYGate ""qiskit.circuit.library.CYGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CYGate.mdx "--- title: CZGate description: API reference for qiskit.circuit.library.CZGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.CZGate --- # CZGate Bases: [`SingletonControlledGate`](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate ""qiskit.circuit.singleton.SingletonControlledGate"") Controlled-Z gate. This is a Clifford and symmetric gate. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`cz()`](qiskit.circuit.QuantumCircuit#cz ""qiskit.circuit.QuantumCircuit.cz"") method. **Circuit symbol:** ```python q_0: ─■─ │ q_1: ─■─ ``` **Matrix representation:** $$ CZ\ q_0, q_1 = I \otimes |0\rangle\langle 0| + Z \otimes |1\rangle\langle 1| = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & -1 \end{pmatrix} $$ In the computational basis, this gate flips the phase of the target qubit if the control qubit is in the $|1\rangle$ state. Create new CZ gate. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.CZGate.base_class ""qiskit.circuit.library.CZGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse Return inverted CZ gate (itself). **Parameters** **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). However, for this class this argument is ignored as this gate is self-inverse. **Returns** inverse gate (self-inverse). **Return type** [CZGate](#qiskit.circuit.library.CZGate ""qiskit.circuit.library.CZGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.CZGate.mdx "--- title: DCXGate description: API reference for qiskit.circuit.library.DCXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.DCXGate --- # DCXGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") Double-CNOT gate. A 2-qubit Clifford gate consisting of two back-to-back CNOTs with alternate controls. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`dcx()`](qiskit.circuit.QuantumCircuit#dcx ""qiskit.circuit.QuantumCircuit.dcx"") method. ```python ┌───┐ q_0: ──■──┤ X ├ ┌─┴─┐└─┬─┘ q_1: ┤ X ├──■── └───┘ ``` This is a classical logic gate, equivalent to a CNOT-SWAP (CNS) sequence, and locally equivalent to an iSWAP. $$ DCX\ q_0, q_1 = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \end{pmatrix} $$ Create new DCX gate. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.DCXGate.base_class ""qiskit.circuit.library.DCXGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.DCXGate.mdx "--- title: Diagonal description: API reference for qiskit.circuit.library.Diagonal in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.Diagonal --- # Diagonal Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Diagonal circuit. Circuit symbol: ```python ┌───────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 Diagonal ├ │ │ q_2: ┤2 ├ └───────────┘ ``` Matrix form: $$ \text{DiagonalGate}\ q_0, q_1, .., q_{n-1} = \begin{pmatrix} D[0] & 0 & \dots & 0 \\ 0 & D[1] & \dots & 0 \\ \vdots & \vdots & \ddots & 0 \\ 0 & 0 & \dots & D[n-1] \end{pmatrix} $$ Diagonal gates are useful as representations of Boolean functions, as they can map from $\{0,1\}^{2^n}$ to $\{0,1\}^{2^n}$ space. For example a phase oracle can be seen as a diagonal gate with $\{1, -1\}$ on the diagonals. Such an oracle will induce a $+1$ or :math\`-1\` phase on the amplitude of any corresponding basis state. Diagonal gates appear in many classically hard oracular problems such as Forrelation or Hidden Shift circuits. Diagonal gates are represented and simulated more efficiently than a dense $2^n \times 2^n$ unitary matrix. The reference implementation is via the method described in Theorem 7 of \[1]. The code is based on Emanuel Malvetti’s semester thesis at ETH in 2018, supervised by Raban Iten and Prof. Renato Renner. **Reference:** \[1] Shende et al., Synthesis of Quantum Logic Circuits, 2009 [arXiv:0406176](https://arxiv.org/pdf/quant-ph/0406176.pdf) **Parameters** **diag** (*Sequence\[*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*]*) – List of the $2^k$ diagonal entries (for a diagonal gate on $k$ qubits). **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if the list of the diagonal entries or the qubit list is in bad format; if the number of diagonal entries is not $2^k$, where $k$ denotes the number of qubits. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.Diagonal.mdx "--- title: DiagonalGate description: API reference for qiskit.circuit.library.DiagonalGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.DiagonalGate --- # DiagonalGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Gate implementing a diagonal transformation. **Parameters** **diag** (*Sequence\[*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*]*) – list of the $2^k$ diagonal entries (for a diagonal gate on $k$ qubits). ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.DiagonalGate.base_class ""qiskit.circuit.library.DiagonalGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return the inverse of the diagonal gate. ### validate\_parameter Diagonal Gate parameter should accept complex (in addition to the Gate parameter types) and always return build-in complex. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.DiagonalGate.mdx "--- title: DraperQFTAdder description: API reference for qiskit.circuit.library.DraperQFTAdder in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.DraperQFTAdder --- # DraperQFTAdder Bases: `Adder` A circuit that uses QFT to perform in-place addition on two qubit registers. For registers with $n$ qubits, the QFT adder can perform addition modulo $2^n$ (with `kind=""fixed""`) or ordinary addition by adding a carry qubits (with `kind=""half""`). As an example, a non-fixed\_point QFT adder circuit that performs addition on two 2-qubit sized registers is as follows: ```python a_0: ─────────■──────■────────────────────────■──────────────── │ │ │ a_1: ─────────┼──────┼────────■──────■────────┼──────────────── ┌──────┐ │P(π) │ │ │ │ ┌───────┐ b_0: ┤0 ├─■──────┼────────┼──────┼────────┼───────┤0 ├ │ │ │P(π/2) │P(π) │ │ │ │ b_1: ┤1 qft ├────────■────────■──────┼────────┼───────┤1 iqft ├ │ │ │P(π/2) │P(π/4) │ │ cout_0: ┤2 ├────────────────────────■────────■───────┤2 ├ └──────┘ └───────┘ ``` **References:** \[1] T. G. Draper, Addition on a Quantum Computer, 2000. [arXiv:quant-ph/0008033](https://arxiv.org/pdf/quant-ph/0008033.pdf) \[2] Ruiz-Perez et al., Quantum arithmetic with the Quantum Fourier Transform, 2017. [arXiv:1411.5949](https://arxiv.org/pdf/1411.5949.pdf) \[3] Vedral et al., Quantum Networks for Elementary Arithmetic Operations, 1995. [arXiv:quant-ph/9511018](https://arxiv.org/pdf/quant-ph/9511018.pdf) **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits in either input register for state $|a\rangle$ or $|b\rangle$. The two input registers must have the same number of qubits. * **kind** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The kind of adder, can be `'half'` for a half adder or `'fixed'` for a fixed-sized adder. A half adder contains a carry-out to represent the most-significant bit, but the fixed-sized adder doesn’t and hence performs addition modulo `2 ** num_state_qubits`. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit object. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If `num_state_qubits` is lower than 1. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### num\_state\_qubits The number of state qubits, i.e. the number of bits in each input register. **Returns** The number of state qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.DraperQFTAdder.mdx "--- title: ECRGate description: API reference for qiskit.circuit.library.ECRGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.ECRGate --- # ECRGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") An echoed cross-resonance gate. This gate is maximally entangling and is equivalent to a CNOT up to single-qubit pre-rotations. The echoing procedure mitigates some unwanted terms (terms other than ZX) to cancel in an experiment. More specifically, this gate implements $\frac{1}{\sqrt{2}}(IX-XY)$. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`ecr()`](qiskit.circuit.QuantumCircuit#ecr ""qiskit.circuit.QuantumCircuit.ecr"") method. **Circuit Symbol:** ```python ┌─────────┐ ┌────────────┐┌────────┐┌─────────────┐ q_0: ┤0 ├ q_0: ┤0 ├┤ RX(pi) ├┤0 ├ │ ECR │ = │ RZX(pi/4) │└────────┘│ RZX(-pi/4) │ q_1: ┤1 ├ q_1: ┤1 ├──────────┤1 ├ └─────────┘ └────────────┘ └─────────────┘ ``` **Matrix Representation:** $$ ECR\ q_0, q_1 = \frac{1}{\sqrt{2}} \begin{pmatrix} 0 & 1 & 0 & i \\ 1 & 0 & -i & 0 \\ 0 & i & 0 & 1 \\ -i & 0 & 1 & 0 \end{pmatrix} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In the above example we apply the gate on (q\_0, q\_1) which results in the $X \otimes Z$ tensor order. Instead, if we apply it on (q\_1, q\_0), the matrix will be $Z \otimes X$: ```python ┌─────────┐ q_0: ┤1 ├ │ ECR │ q_1: ┤0 ├ └─────────┘ ``` $$ ECR\ q_0, q_1 = \frac{1}{\sqrt{2}} \begin{pmatrix} 0 & 0 & 1 & i \\ 0 & 0 & i & 1 \\ 1 & -i & 0 & 0 \\ -i & 1 & 0 & 0 \end{pmatrix} $$ Create new ECR gate. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.ECRGate.base_class ""qiskit.circuit.library.ECRGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse ECR gate (itself). **Parameters** **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). However, for this class this argument is ignored as this gate is self-inverse. **Returns** inverse gate (self-inverse). **Return type** [ECRGate](#qiskit.circuit.library.ECRGate ""qiskit.circuit.library.ECRGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.ECRGate.mdx "--- title: EfficientSU2 description: API reference for qiskit.circuit.library.EfficientSU2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.EfficientSU2 --- # EfficientSU2 Bases: [`TwoLocal`](qiskit.circuit.library.TwoLocal ""qiskit.circuit.library.n_local.two_local.TwoLocal"") The hardware efficient SU(2) 2-local circuit. The `EfficientSU2` circuit consists of layers of single qubit operations spanned by SU(2) and $CX$ entanglements. This is a heuristic pattern that can be used to prepare trial wave functions for variational quantum algorithms or classification circuit for machine learning. SU(2) stands for special unitary group of degree 2, its elements are $2 \times 2$ unitary matrices with determinant 1, such as the Pauli rotation gates. On 3 qubits and using the Pauli $Y$ and $Z$ su2\_gates as single qubit gates, the hardware efficient SU(2) circuit is represented by: ```python ┌──────────┐┌──────────┐ ░ ░ ░ ┌───────────┐┌───────────┐ ┤ RY(θ[0]) ├┤ RZ(θ[3]) ├─░────────■───░─ ... ─░─┤ RY(θ[12]) ├┤ RZ(θ[15]) ├ ├──────────┤├──────────┤ ░ ┌─┴─┐ ░ ░ ├───────────┤├───────────┤ ┤ RY(θ[1]) ├┤ RZ(θ[4]) ├─░───■──┤ X ├─░─ ... ─░─┤ RY(θ[13]) ├┤ RZ(θ[16]) ├ ├──────────┤├──────────┤ ░ ┌─┴─┐└───┘ ░ ░ ├───────────┤├───────────┤ ┤ RY(θ[2]) ├┤ RZ(θ[5]) ├─░─┤ X ├──────░─ ... ─░─┤ RY(θ[14]) ├┤ RZ(θ[17]) ├ └──────────┘└──────────┘ ░ └───┘ ░ ░ └───────────┘└───────────┘ ``` See [`RealAmplitudes`](qiskit.circuit.library.RealAmplitudes ""qiskit.circuit.library.RealAmplitudes"") for more detail on the possible arguments and options such as skipping unentanglement qubits, which apply here too. **Examples** ```python >>> circuit = EfficientSU2(3, reps=1) >>> print(circuit) ┌──────────┐┌──────────┐ ┌──────────┐┌──────────┐ q_0: ┤ RY(θ[0]) ├┤ RZ(θ[3]) ├──■────■──┤ RY(θ[6]) ├┤ RZ(θ[9]) ├───────────── ├──────────┤├──────────┤┌─┴─┐ │ └──────────┘├──────────┤┌───────────┐ q_1: ┤ RY(θ[1]) ├┤ RZ(θ[4]) ├┤ X ├──┼───────■──────┤ RY(θ[7]) ├┤ RZ(θ[10]) ├ ├──────────┤├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤├───────────┤ q_2: ┤ RY(θ[2]) ├┤ RZ(θ[5]) ├─────┤ X ├───┤ X ├────┤ RY(θ[8]) ├┤ RZ(θ[11]) ├ └──────────┘└──────────┘ └───┘ └───┘ └──────────┘└───────────┘ ``` ```python >>> ansatz = EfficientSU2(4, su2_gates=['rx', 'y'], entanglement='circular', reps=1) >>> qc = QuantumCircuit(4) # create a circuit and append the RY variational form >>> qc.compose(ansatz, inplace=True) >>> qc.draw() ┌──────────┐┌───┐┌───┐ ┌──────────┐ ┌───┐ q_0: ┤ RX(θ[0]) ├┤ Y ├┤ X ├──■──┤ RX(θ[4]) ├───┤ Y ├───────────────────── ├──────────┤├───┤└─┬─┘┌─┴─┐└──────────┘┌──┴───┴───┐ ┌───┐ q_1: ┤ RX(θ[1]) ├┤ Y ├──┼──┤ X ├─────■──────┤ RX(θ[5]) ├───┤ Y ├───────── ├──────────┤├───┤ │ └───┘ ┌─┴─┐ └──────────┘┌──┴───┴───┐┌───┐ q_2: ┤ RX(θ[2]) ├┤ Y ├──┼──────────┤ X ├─────────■──────┤ RX(θ[6]) ├┤ Y ├ ├──────────┤├───┤ │ └───┘ ┌─┴─┐ ├──────────┤├───┤ q_3: ┤ RX(θ[3]) ├┤ Y ├──■──────────────────────┤ X ├────┤ RX(θ[7]) ├┤ Y ├ └──────────┘└───┘ └───┘ └──────────┘└───┘ ``` **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits of the EfficientSU2 circuit. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Specifies how often the structure of a rotation layer followed by an entanglement layer is repeated. * **su2\_gates** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*type*](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"") *|*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") *|*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*type*](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"") *|*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") *|*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] | None*) – The SU(2) single qubit gates to apply in single qubit gate layers. If only one gate is provided, the same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order. * **entanglement** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]] | Callable\[\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*],* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – Specifies the entanglement structure. Can be a string (‘full’, ‘linear’ , ‘reverse\_linear’, ‘circular’ or ‘sca’), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to ‘reverse\_linear’ entanglement. Note that ‘reverse\_linear’ entanglement provides the same unitary as ‘full’ with fewer entangling gates. See the Examples section of [`TwoLocal`](qiskit.circuit.library.TwoLocal ""qiskit.circuit.library.TwoLocal"") for more detail. * **initial\_state** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *| None*) – A QuantumCircuit object to prepend to the circuit. * **skip\_unentangled\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, the single qubit gates are only applied to qubits that are entangled with another qubit. If False, the single qubit gates are applied to each qubit in the Ansatz. Defaults to False. * **skip\_final\_rotation\_layer** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If False, a rotation layer is added at the end of the ansatz. If True, no rotation layer is added. * **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The parameterized gates require a parameter to be defined, for which we use [`ParameterVector`](qiskit.circuit.ParameterVector ""qiskit.circuit.ParameterVector""). * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, barriers are inserted in between each layer. If False, no barriers are inserted. * **flatten** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – Set this to `True` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you’re using this circuit for anything besides visualization its **strongly** recommended to set this flag to `True` to avoid a large performance overhead for parameter binding. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### entanglement Get the entanglement strategy. **Returns** The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted. ### entanglement\_blocks The blocks in the entanglement layers. **Returns** The blocks in the entanglement layers. ### flatten Returns whether the circuit is wrapped in nested gates/instructions or flattened. ### global\_phase Return the global phase of the current circuit scope in radians. ### initial\_state Return the initial state that is added in front of the n-local circuit. **Returns** The initial state. ### insert\_barriers If barriers are inserted in between the layers or not. **Returns** `True`, if barriers are inserted in between the layers, `False` if not. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_layers Return the number of layers in the n-local circuit. **Returns** The number of layers in the circuit. ### num\_parameters ### num\_parameters\_settable The number of total parameters that can be set to distinct values. This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from `num_parameters` which counts the number of unique [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") objects currently in the circuit. **Returns** The number of parameters originally available in the circuit. This quantity does not require the circuit to be built yet. ### num\_qubits Returns the number of qubits in this circuit. **Returns** The number of qubits. ### 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. ### ordered\_parameters The parameters used in the underlying circuit. This includes float values and duplicates. **Examples** ```python >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] ``` **Returns** The parameters objects used in the circuit. ### parameter\_bounds Return the parameter bounds. **Returns** The parameter bounds. ### parameters ### preferred\_init\_points The initial points for the parameters. Can be stored as initial guess in optimization. **Returns** The initial values for the parameters, or None, if none have been set. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### reps The number of times rotation and entanglement block are repeated. **Returns** The number of repetitions. ### rotation\_blocks The blocks in the rotation layers. **Returns** The blocks in the rotation layers. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.EfficientSU2.mdx "--- title: EvolvedOperatorAnsatz description: API reference for qiskit.circuit.library.EvolvedOperatorAnsatz in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.EvolvedOperatorAnsatz --- # EvolvedOperatorAnsatz Bases: [`NLocal`](qiskit.circuit.library.NLocal ""qiskit.circuit.library.n_local.n_local.NLocal"") The evolved operator ansatz. **Parameters** * **operators** (*BaseOperator |* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *| None*) – The operators to evolve. If a circuit is passed, we assume it implements an already evolved operator and thus the circuit is not evolved again. Can be a single operator (circuit) or a list of operators (and circuits). * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of times to repeat the evolved operators. * **evolution** (*EvolutionBase |* [*EvolutionSynthesis*](qiskit.synthesis.EvolutionSynthesis ""qiskit.synthesis.EvolutionSynthesis"") *| None*) – A specification of which evolution synthesis to use for the [`PauliEvolutionGate`](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate""). Defaults to first order Trotterization. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to insert barriers in between each evolution. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit. * **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| Sequence\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – Set the names of the circuit parameters. If a string, the same prefix will be used for each parameters. Can also be a list to specify a prefix per operator. * **initial\_state** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *| None*) – A [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") object to prepend to the circuit. * **flatten** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – Set this to `True` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you’re using this circuit for anything besides visualization its **strongly** recommended to set this flag to `True` to avoid a large performance overhead for parameter binding. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### entanglement Get the entanglement strategy. **Returns** The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted. ### entanglement\_blocks The blocks in the entanglement layers. **Returns** The blocks in the entanglement layers. ### evolution The evolution converter used to compute the evolution. **Returns** The evolution converter used to compute the evolution. **Return type** [EvolutionSynthesis](qiskit.synthesis.EvolutionSynthesis ""qiskit.synthesis.EvolutionSynthesis"") ### flatten Returns whether the circuit is wrapped in nested gates/instructions or flattened. ### global\_phase Return the global phase of the current circuit scope in radians. ### initial\_state Return the initial state that is added in front of the n-local circuit. **Returns** The initial state. ### insert\_barriers If barriers are inserted in between the layers or not. **Returns** `True`, if barriers are inserted in between the layers, `False` if not. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_layers Return the number of layers in the n-local circuit. **Returns** The number of layers in the circuit. ### num\_parameters ### num\_parameters\_settable The number of total parameters that can be set to distinct values. This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from `num_parameters` which counts the number of unique [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") objects currently in the circuit. **Returns** The number of parameters originally available in the circuit. This quantity does not require the circuit to be built yet. ### num\_qubits Returns the number of qubits in this circuit. **Returns** The number of qubits. ### 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. ### operators The operators that are evolved in this circuit. **Returns** The operators to be evolved (and circuits) contained in this ansatz. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") ### ordered\_parameters The parameters used in the underlying circuit. This includes float values and duplicates. **Examples** ```python >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] ``` **Returns** The parameters objects used in the circuit. ### parameter\_bounds The parameter bounds for the unbound parameters in the circuit. **Returns** A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If `None` is returned, problem is fully unbounded. ### parameters ### preferred\_init\_points Getter of preferred initial points based on the given initial state. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### reps The number of times rotation and entanglement block are repeated. **Returns** The number of repetitions. ### rotation\_blocks The blocks in the rotation layers. **Returns** The blocks in the rotation layers. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.EvolvedOperatorAnsatz.mdx "--- title: ExactReciprocal description: API reference for qiskit.circuit.library.ExactReciprocal in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.ExactReciprocal --- # ExactReciprocal Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Exact reciprocal $$ |x\rangle |0\rangle \mapsto \cos(1/x)|x\rangle|0\rangle + \sin(1/x)|x\rangle |1\rangle $$ **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits representing the value to invert. * **scaling** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Scaling factor $s$ of the reciprocal function, i.e. to compute $s / x$. * **neg\_vals** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether $x$ might represent negative values. In this case the first qubit is the sign, with $|1\rangle$ for negative and $|0\rangle$ for positive. For the negative case it is assumed that the remaining string represents $1 - x$. This is because $e^{-2 \pi i x} = e^{2 \pi i (1 - x)}$ for $x \in [0,1)$. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the object. It is assumed that the binary string $x$ represents a number \< 1. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.ExactReciprocal.mdx "--- title: ExcitationPreserving description: API reference for qiskit.circuit.library.ExcitationPreserving in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.ExcitationPreserving --- # ExcitationPreserving Bases: [`TwoLocal`](qiskit.circuit.library.TwoLocal ""qiskit.circuit.library.n_local.two_local.TwoLocal"") The heuristic excitation-preserving wave function ansatz. The `ExcitationPreserving` circuit preserves the ratio of $|00\rangle$, $|01\rangle + |10\rangle$ and $|11\rangle$ states. To this end, this circuit uses two-qubit interactions of the form $$ \newcommand{\rotationangle}{\theta/2} \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos\left(\rotationangle\right) & -i\sin\left(\rotationangle\right) & 0 \\ 0 & -i\sin\left(\rotationangle\right) & \cos\left(\rotationangle\right) & 0 \\ 0 & 0 & 0 & e^{-i\phi} \end{pmatrix} $$ for the mode `'fsim'` or with $e^{-i\phi} = 1$ for the mode `'iswap'`. Note that other wave functions, such as UCC-ansatzes, are also excitation preserving. However these can become complex quickly, while this heuristically motivated circuit follows a simpler pattern. This trial wave function consists of layers of $Z$ rotations with 2-qubit entanglements. The entangling is creating using $XX+YY$ rotations and optionally a controlled-phase gate for the mode `'fsim'`. See [`RealAmplitudes`](qiskit.circuit.library.RealAmplitudes ""qiskit.circuit.library.RealAmplitudes"") for more detail on the possible arguments and options such as skipping unentanglement qubits, which apply here too. The rotations of the ExcitationPreserving ansatz can be written as **Examples** ```python >>> ansatz = ExcitationPreserving(3, reps=1, insert_barriers=True, entanglement='linear') >>> print(ansatz) # show the circuit ┌──────────┐ ░ ┌────────────┐┌────────────┐ ░ ┌──────────┐ q_0: ┤ RZ(θ[0]) ├─░─┤0 ├┤0 ├─────────────────────────────░─┤ RZ(θ[5]) ├ ├──────────┤ ░ │ RXX(θ[3]) ││ RYY(θ[3]) │┌────────────┐┌────────────┐ ░ ├──────────┤ q_1: ┤ RZ(θ[1]) ├─░─┤1 ├┤1 ├┤0 ├┤0 ├─░─┤ RZ(θ[6]) ├ ├──────────┤ ░ └────────────┘└────────────┘│ RXX(θ[4]) ││ RYY(θ[4]) │ ░ ├──────────┤ q_2: ┤ RZ(θ[2]) ├─░─────────────────────────────┤1 ├┤1 ├─░─┤ RZ(θ[7]) ├ └──────────┘ ░ └────────────┘└────────────┘ ░ └──────────┘ ``` ```python >>> ansatz = ExcitationPreserving(2, reps=1) >>> qc = QuantumCircuit(2) # create a circuit and append the RY variational form >>> qc.cry(0.2, 0, 1) # do some previous operation >>> qc.compose(ansatz, inplace=True) # add the swaprz >>> qc.draw() ┌──────────┐┌────────────┐┌────────────┐┌──────────┐ q_0: ─────■─────┤ RZ(θ[0]) ├┤0 ├┤0 ├┤ RZ(θ[3]) ├ ┌────┴────┐├──────────┤│ RXX(θ[2]) ││ RYY(θ[2]) │├──────────┤ q_1: ┤ RY(0.2) ├┤ RZ(θ[1]) ├┤1 ├┤1 ├┤ RZ(θ[4]) ├ └─────────┘└──────────┘└────────────┘└────────────┘└──────────┘ ``` ```python >>> ansatz = ExcitationPreserving(3, reps=1, mode='fsim', entanglement=[[0,2]], ... insert_barriers=True) >>> print(ansatz) ┌──────────┐ ░ ┌────────────┐┌────────────┐ ░ ┌──────────┐ q_0: ┤ RZ(θ[0]) ├─░─┤0 ├┤0 ├─■──────░─┤ RZ(θ[5]) ├ ├──────────┤ ░ │ ││ │ │ ░ ├──────────┤ q_1: ┤ RZ(θ[1]) ├─░─┤ RXX(θ[3]) ├┤ RYY(θ[3]) ├─┼──────░─┤ RZ(θ[6]) ├ ├──────────┤ ░ │ ││ │ │θ[4] ░ ├──────────┤ q_2: ┤ RZ(θ[2]) ├─░─┤1 ├┤1 ├─■──────░─┤ RZ(θ[7]) ├ └──────────┘ ░ └────────────┘└────────────┘ ░ └──────────┘ ``` **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits of the ExcitationPreserving circuit. * **mode** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Choose the entangler mode, can be ‘iswap’ or ‘fsim’. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Specifies how often the structure of a rotation layer followed by an entanglement layer is repeated. * **entanglement** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]] | Callable\[\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*],* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – Specifies the entanglement structure. Can be a string (‘full’, ‘linear’ or ‘sca’), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. See the Examples section of [`TwoLocal`](qiskit.circuit.library.TwoLocal ""qiskit.circuit.library.TwoLocal"") for more detail. * **initial\_state** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *| None*) – A QuantumCircuit object to prepend to the circuit. * **skip\_unentangled\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, the single qubit gates are only applied to qubits that are entangled with another qubit. If False, the single qubit gates are applied to each qubit in the Ansatz. Defaults to False. * **skip\_final\_rotation\_layer** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, a rotation layer is added at the end of the ansatz. If False, no rotation layer is added. Defaults to True. * **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The parameterized gates require a parameter to be defined, for which we use [`ParameterVector`](qiskit.circuit.ParameterVector ""qiskit.circuit.ParameterVector""). * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, barriers are inserted in between each layer. If False, no barriers are inserted. * **flatten** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – Set this to `True` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you’re using this circuit for anything besides visualization its **strongly** recommended to set this flag to `True` to avoid a large performance overhead for parameter binding. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the selected mode is not supported. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### entanglement Get the entanglement strategy. **Returns** The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted. ### entanglement\_blocks The blocks in the entanglement layers. **Returns** The blocks in the entanglement layers. ### flatten Returns whether the circuit is wrapped in nested gates/instructions or flattened. ### global\_phase Return the global phase of the current circuit scope in radians. ### initial\_state Return the initial state that is added in front of the n-local circuit. **Returns** The initial state. ### insert\_barriers If barriers are inserted in between the layers or not. **Returns** `True`, if barriers are inserted in between the layers, `False` if not. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_layers Return the number of layers in the n-local circuit. **Returns** The number of layers in the circuit. ### num\_parameters ### num\_parameters\_settable The number of total parameters that can be set to distinct values. This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from `num_parameters` which counts the number of unique [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") objects currently in the circuit. **Returns** The number of parameters originally available in the circuit. This quantity does not require the circuit to be built yet. ### num\_qubits Returns the number of qubits in this circuit. **Returns** The number of qubits. ### 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. ### ordered\_parameters The parameters used in the underlying circuit. This includes float values and duplicates. **Examples** ```python >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] ``` **Returns** The parameters objects used in the circuit. ### parameter\_bounds Return the parameter bounds. **Returns** The parameter bounds. ### parameters ### preferred\_init\_points The initial points for the parameters. Can be stored as initial guess in optimization. **Returns** The initial values for the parameters, or None, if none have been set. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### reps The number of times rotation and entanglement block are repeated. **Returns** The number of repetitions. ### rotation\_blocks The blocks in the rotation layers. **Returns** The blocks in the rotation layers. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.ExcitationPreserving.mdx "--- title: FourierChecking description: API reference for qiskit.circuit.library.FourierChecking in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.FourierChecking --- # FourierChecking Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Fourier checking circuit. The circuit for the Fourier checking algorithm, introduced in \[1], involves a layer of Hadamards, the function $f$, another layer of Hadamards, the function $g$, followed by a final layer of Hadamards. The functions $f$ and $g$ are classical functions realized as phase oracles (diagonal operators with \{-1, 1} on the diagonal). The probability of observing the all-zeros string is $p(f,g)$. The algorithm solves the promise Fourier checking problem, which decides if f is correlated with the Fourier transform of g, by testing if $p(f,g) <= 0.01$ or $p(f,g) >= 0.05$, promised that one or the other of these is true. The functions $f$ and $g$ are currently implemented from their truth tables but could be represented concisely and implemented efficiently for special classes of functions. Fourier checking is a special case of $k$-fold forrelation \[2]. **Reference:** \[1] S. Aaronson, BQP and the Polynomial Hierarchy, 2009 (Section 3.2). [arXiv:0910.4698](https://arxiv.org/abs/0910.4698) \[2] S. Aaronson, A. Ambainis, Forrelation: a problem that optimally separates quantum from classical computing, 2014. [arXiv:1411.5729](https://arxiv.org/abs/1411.5729) Create Fourier checking circuit. **Parameters** * **f** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – truth table for f, length 2\*\*n list of \{1,-1}. * **g** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – truth table for g, length 2\*\*n list of \{1,-1}. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if the inputs f and g are not valid. **Reference Circuit:** ![../\_images/qiskit-circuit-library-FourierChecking-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-FourierChecking-1.png) ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.FourierChecking.mdx "--- title: FunctionalPauliRotations description: API reference for qiskit.circuit.library.FunctionalPauliRotations in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.FunctionalPauliRotations --- # FunctionalPauliRotations Bases: `BlueprintCircuit`, [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Base class for functional Pauli rotations. Create a new functional Pauli rotation circuit. **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits representing the state $|x\rangle$. * **basis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The kind of Pauli rotation to use. Must be ‘X’, ‘Y’ or ‘Z’. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit object. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### basis The kind of Pauli rotation to be used. Set the basis to ‘X’, ‘Y’ or ‘Z’ for controlled-X, -Y, or -Z rotations respectively. **Returns** The kind of Pauli rotation used in controlled rotation. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancilla\_qubits The minimum number of ancilla qubits in the circuit. **Returns** The minimal number of ancillas required. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters ### num\_qubits Return number of qubits. ### num\_state\_qubits The number of state qubits representing the state $|x\rangle$. **Returns** The number of state qubits. ### 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. ### parameters ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.FunctionalPauliRotations.mdx "--- title: GlobalPhaseGate description: API reference for qiskit.circuit.library.GlobalPhaseGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.GlobalPhaseGate --- # GlobalPhaseGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") The global phase gate ($e^{i\theta}$). Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **Mathematical Representation:** $$ \text{GlobalPhaseGate}\ = \begin{pmatrix} e^{i\theta} \end{pmatrix} $$ **Parameters** * **phase** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The value of phase it takes. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.GlobalPhaseGate.base_class ""qiskit.circuit.library.GlobalPhaseGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse GlobalPhaseGate gate. $\text{GlobalPhaseGate}(\lambda)^{\dagger} = \text{GlobalPhaseGate}(-\lambda)$ **Parameters** **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). However, for this class this argument is ignored as the inverse is always another [`GlobalPhaseGate`](#qiskit.circuit.library.GlobalPhaseGate ""qiskit.circuit.library.GlobalPhaseGate"") with an inverted parameter value. **Returns** inverse gate. **Return type** [GlobalPhaseGate](#qiskit.circuit.library.GlobalPhaseGate ""qiskit.circuit.library.GlobalPhaseGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.GlobalPhaseGate.mdx "--- title: GMS description: API reference for qiskit.circuit.library.GMS in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.GMS --- # GMS Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Global Mølmer–Sørensen gate. **Circuit symbol:** ```python ┌───────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 GMS ├ │ │ q_2: ┤2 ├ └───────────┘ ``` **Expanded Circuit:** ![../\_images/qiskit-circuit-library-GMS-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-GMS-1.png) The Mølmer–Sørensen gate is native to ion-trap systems. The global MS can be applied to multiple ions to entangle multiple qubits simultaneously \[1]. In the two-qubit case, this is equivalent to an XX(theta) interaction, and is thus reduced to the RXXGate. The global MS gate is a sum of XX interactions on all pairs \[2]. $$ GMS(\chi_{12}, \chi_{13}, ..., \chi_{n-1 n}) = exp(-i \sum_{i=1}^{n} \sum_{j=i+1}^{n} X{\otimes}X \frac{\chi_{ij}}{2}) $$ **References:** \[1] Sørensen, A. and Mølmer, K., Multi-particle entanglement of hot trapped ions. Physical Review Letters. 82 (9): 1835–1838. [arXiv:9810040](https://arxiv.org/abs/quant-ph/9810040) \[2] Maslov, D. and Nam, Y., Use of global interactions in efficient quantum circuit constructions. New Journal of Physics, 20(3), p.033018. [arXiv:1707.06356](https://arxiv.org/abs/1707.06356) Create a new Global Mølmer–Sørensen (GMS) gate. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – width of gate. * **theta** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]] |* [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – a num\_qubits x num\_qubits symmetric matrix of interaction angles for each qubit pair. The upper triangle is considered. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.GMS.mdx "--- title: GR description: API reference for qiskit.circuit.library.GR in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.GR --- # GR Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Global R gate. **Circuit symbol:** ```python ┌──────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 GR(ϴ,φ) ├ │ │ q_2: ┤2 ├ └──────────┘ ``` The global R gate is native to atomic systems (ion traps, cold neutrals). The global R can be applied to multiple qubits simultaneously. In the one-qubit case, this is equivalent to an R(theta, phi) operation, and is thus reduced to the RGate. The global R gate is a direct sum of R operations on all individual qubits. $$ GR(\theta, \phi) = \exp(-i \sum_{i=1}^{n} (\cos(\phi)X_i + \sin(\phi)Y_i) \theta/2) $$ **Expanded Circuit:** ![../\_images/qiskit-circuit-library-GR-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-GR-1.png) Create a new Global R (GR) gate. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubits. * **theta** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – rotation angle about axis determined by phi * **phi** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – angle of rotation axis in xy-plane ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.GR.mdx "--- title: GraphState description: API reference for qiskit.circuit.library.GraphState in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.GraphState --- # GraphState Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Circuit to prepare a graph state. Given a graph G = (V, E), with the set of vertices V and the set of edges E, the corresponding graph state is defined as $$ |G\rangle = \prod_{(a,b) \in E} CZ_{(a,b)} {|+\rangle}^{\otimes V} $$ Such a state can be prepared by first preparing all qubits in the $+$ state, then applying a $CZ$ gate for each corresponding graph edge. Graph state preparation circuits are Clifford circuits, and thus easy to simulate classically. However, by adding a layer of measurements in a product basis at the end, there is evidence that the circuit becomes hard to simulate \[2]. **Reference Circuit:** ![../\_images/qiskit-circuit-library-GraphState-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-GraphState-1.png) **References:** **\[1] M. Hein, J. Eisert, H.J. Briegel, Multi-party Entanglement in Graph States,** [arXiv:0307130](https://arxiv.org/pdf/quant-ph/0307130.pdf) **\[2] D. Koh, Further Extensions of Clifford Circuits & their Classical Simulation Complexities.** [arXiv:1512.07892](https://arxiv.org/pdf/1512.07892.pdf) Create graph state preparation circuit. **Parameters** **adjacency\_matrix** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *| np.ndarray*) – input graph as n-by-n list of 0-1 lists **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – If adjacency\_matrix is not symmetric. The circuit prepares a graph state with the given adjacency matrix. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.GraphState.mdx "--- title: GroverOperator description: API reference for qiskit.circuit.library.GroverOperator in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.GroverOperator --- # GroverOperator Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") The Grover operator. Grover’s search algorithm \[1, 2] consists of repeated applications of the so-called Grover operator used to amplify the amplitudes of the desired output states. This operator, $\mathcal{Q}$, consists of the phase oracle, $\mathcal{S}_f$, zero phase-shift or zero reflection, $\mathcal{S}_0$, and an input state preparation $\mathcal{A}$: $$ \mathcal{Q} = \mathcal{A} \mathcal{S}_0 \mathcal{A}^\dagger \mathcal{S}_f $$ In the standard Grover search we have $\mathcal{A} = H^{\otimes n}$: $$ \mathcal{Q} = H^{\otimes n} \mathcal{S}_0 H^{\otimes n} \mathcal{S}_f = D \mathcal{S_f} $$ The operation $D = H^{\otimes n} \mathcal{S}_0 H^{\otimes n}$ is also referred to as diffusion operator. In this formulation we can see that Grover’s operator consists of two steps: first, the phase oracle multiplies the good states by -1 (with $\mathcal{S}_f$) and then the whole state is reflected around the mean (with $D$). This class allows setting a different state preparation, as in quantum amplitude amplification (a generalization of Grover’s algorithm), $\mathcal{A}$ might not be a layer of Hardamard gates \[3]. The action of the phase oracle $\mathcal{S}_f$ is defined as $$ \mathcal{S}_f: |x\rangle \mapsto (-1)^{f(x)}|x\rangle $$ where $f(x) = 1$ if $x$ is a good state and 0 otherwise. To highlight the fact that this oracle flips the phase of the good states and does not flip the state of a result qubit, we call $\mathcal{S}_f$ a phase oracle. Note that you can easily construct a phase oracle from a bitflip oracle by sandwiching the controlled X gate on the result qubit by a X and H gate. For instance ```python Bitflip oracle Phaseflip oracle q_0: ──■── q_0: ────────────■──────────── ┌─┴─┐ ┌───┐┌───┐┌─┴─┐┌───┐┌───┐ out: ┤ X ├ out: ┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├ └───┘ └───┘└───┘└───┘└───┘└───┘ ``` There is some flexibility in defining the oracle and $\mathcal{A}$ operator. Before the Grover operator is applied in Grover’s algorithm, the qubits are first prepared with one application of the $\mathcal{A}$ operator (or Hadamard gates in the standard formulation). Thus, we always have operation of the form $\mathcal{A} \mathcal{S}_f \mathcal{A}^\dagger$. Therefore it is possible to move bitflip logic into $\mathcal{A}$ and leaving the oracle only to do phaseflips via Z gates based on the bitflips. One possible use-case for this are oracles that do not uncompute the state qubits. The zero reflection $\mathcal{S}_0$ is usually defined as $$ \mathcal{S}_0 = 2 |0\rangle^{\otimes n} \langle 0|^{\otimes n} - \mathbb{I}_n $$ where $\mathbb{I}_n$ is the identity on $n$ qubits. By default, this class implements the negative version $2 |0\rangle^{\otimes n} \langle 0|^{\otimes n} - \mathbb{I}_n$, since this can simply be implemented with a multi-controlled Z sandwiched by X gates on the target qubit and the introduced global phase does not matter for Grover’s algorithm. **Examples** ```python >>> from qiskit.circuit import QuantumCircuit >>> from qiskit.circuit.library import GroverOperator >>> oracle = QuantumCircuit(2) >>> oracle.z(0) # good state = first qubit is |1> >>> grover_op = GroverOperator(oracle, insert_barriers=True) >>> grover_op.decompose().draw() ┌───┐ ░ ┌───┐ ░ ┌───┐ ┌───┐ ░ ┌───┐ state_0: ┤ Z ├─░─┤ H ├─░─┤ X ├───────■──┤ X ├──────░─┤ H ├ └───┘ ░ ├───┤ ░ ├───┤┌───┐┌─┴─┐├───┤┌───┐ ░ ├───┤ state_1: ──────░─┤ H ├─░─┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├─░─┤ H ├ ░ └───┘ ░ └───┘└───┘└───┘└───┘└───┘ ░ └───┘ ``` ```python >>> oracle = QuantumCircuit(1) >>> oracle.z(0) # the qubit state |1> is the good state >>> state_preparation = QuantumCircuit(1) >>> state_preparation.ry(0.2, 0) # non-uniform state preparation >>> grover_op = GroverOperator(oracle, state_preparation) >>> grover_op.decompose().draw() ┌───┐┌──────────┐┌───┐┌───┐┌───┐┌─────────┐ state_0: ┤ Z ├┤ RY(-0.2) ├┤ X ├┤ Z ├┤ X ├┤ RY(0.2) ├ └───┘└──────────┘└───┘└───┘└───┘└─────────┘ ``` ```python >>> oracle = QuantumCircuit(4) >>> oracle.z(3) >>> reflection_qubits = [0, 3] >>> state_preparation = QuantumCircuit(4) >>> state_preparation.cry(0.1, 0, 3) >>> state_preparation.ry(0.5, 3) >>> grover_op = GroverOperator(oracle, state_preparation, ... reflection_qubits=reflection_qubits) >>> grover_op.decompose().draw() ┌───┐ ┌───┐ state_0: ──────────────────────■──────┤ X ├───────■──┤ X ├──────────■──────────────── │ └───┘ │ └───┘ │ state_1: ──────────────────────┼──────────────────┼─────────────────┼──────────────── │ │ │ state_2: ──────────────────────┼──────────────────┼─────────────────┼──────────────── ┌───┐┌──────────┐┌────┴─────┐┌───┐┌───┐┌─┴─┐┌───┐┌───┐┌────┴────┐┌─────────┐ state_3: ┤ Z ├┤ RY(-0.5) ├┤ RY(-0.1) ├┤ X ├┤ H ├┤ X ├┤ H ├┤ X ├┤ RY(0.1) ├┤ RY(0.5) ├ └───┘└──────────┘└──────────┘└───┘└───┘└───┘└───┘└───┘└─────────┘└─────────┘ ``` ```python >>> mark_state = Statevector.from_label('011') >>> diffuse_operator = 2 * DensityMatrix.from_label('000') - Operator.from_label('III') >>> grover_op = GroverOperator(oracle=mark_state, zero_reflection=diffuse_operator) >>> grover_op.decompose().draw(fold=70) ┌─────────────────┐ ┌───┐ » state_0: ┤0 ├──────┤ H ├──────────────────────────» │ │┌─────┴───┴─────┐ ┌───┐ » state_1: ┤1 UCRZ(0,pi,0,0) ├┤0 ├─────┤ H ├──────────» │ ││ UCRZ(pi/2,0) │┌────┴───┴────┐┌───┐» state_2: ┤2 ├┤1 ├┤ UCRZ(-pi/4) ├┤ H ├» └─────────────────┘└───────────────┘└─────────────┘└───┘» « ┌─────────────────┐ ┌───┐ «state_0: ┤0 ├──────┤ H ├───────────────────────── « │ │┌─────┴───┴─────┐ ┌───┐ «state_1: ┤1 UCRZ(pi,0,0,0) ├┤0 ├────┤ H ├────────── « │ ││ UCRZ(pi/2,0) │┌───┴───┴────┐┌───┐ «state_2: ┤2 ├┤1 ├┤ UCRZ(pi/4) ├┤ H ├ « └─────────────────┘└───────────────┘└────────────┘└───┘ ``` **References** **\[1]: L. K. Grover (1996), A fast quantum mechanical algorithm for database search,** [arXiv:quant-ph/9605043](https://arxiv.org/abs/quant-ph/9605043). **\[2]: I. Chuang & M. Nielsen, Quantum Computation and Quantum Information,** Cambridge: Cambridge University Press, 2000. Chapter 6.1.2. **\[3]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000).** Quantum Amplitude Amplification and Estimation. [arXiv:quant-ph/0005055](http://arxiv.org/abs/quant-ph/0005055). **Parameters** * **oracle** (*Union\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*,* [*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"")*]*) – The phase oracle implementing a reflection about the bad state. Note that this is not a bitflip oracle, see the docstring for more information. * **state\_preparation** (*Optional\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]*) – The operator preparing the good and bad state. For Grover’s algorithm, this is a n-qubit Hadamard gate and for amplitude amplification or estimation the operator $\mathcal{A}$. * **zero\_reflection** (*Optional\[Union\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*,* [*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")*,* [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")*]]*) – The reflection about the zero state, $\mathcal{S}_0$. * **reflection\_qubits** (*Optional\[List\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – Qubits on which the zero reflection acts on. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether barriers should be inserted between the reflections and A. * **mcx\_mode** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The mode to use for building the default zero reflection. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### oracle The oracle implementing a reflection about the bad state. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ### reflection\_qubits Reflection qubits, on which S0 is applied (if S0 is not user-specified). ### state\_preparation The subcircuit implementing the A operator or Hadamards. ### zero\_reflection The subcircuit implementing the reflection about 0. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.GroverOperator.mdx "--- title: GRX description: API reference for qiskit.circuit.library.GRX in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.GRX --- # GRX Bases: [`GR`](qiskit.circuit.library.GR ""qiskit.circuit.library.generalized_gates.gr.GR"") Global RX gate. **Circuit symbol:** ```python ┌──────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 GRX(ϴ) ├ │ │ q_2: ┤2 ├ └──────────┘ ``` The global RX gate is native to atomic systems (ion traps, cold neutrals). The global RX can be applied to multiple qubits simultaneously. In the one-qubit case, this is equivalent to an RX(theta) operations, and is thus reduced to the RXGate. The global RX gate is a direct sum of RX operations on all individual qubits. $$ GRX(\theta) = \exp(-i \sum_{i=1}^{n} X_i \theta/2) $$ **Expanded Circuit:** ![../\_images/qiskit-circuit-library-GRX-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-GRX-1.png) Create a new Global RX (GRX) gate. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubits. * **theta** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – rotation angle about x-axis ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.GRX.mdx "--- title: GRY description: API reference for qiskit.circuit.library.GRY in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.GRY --- # GRY Bases: [`GR`](qiskit.circuit.library.GR ""qiskit.circuit.library.generalized_gates.gr.GR"") Global RY gate. **Circuit symbol:** ```python ┌──────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 GRY(ϴ) ├ │ │ q_2: ┤2 ├ └──────────┘ ``` The global RY gate is native to atomic systems (ion traps, cold neutrals). The global RY can be applied to multiple qubits simultaneously. In the one-qubit case, this is equivalent to an RY(theta) operation, and is thus reduced to the RYGate. The global RY gate is a direct sum of RY operations on all individual qubits. $$ GRY(\theta) = \exp(-i \sum_{i=1}^{n} Y_i \theta/2) $$ **Expanded Circuit:** ![../\_images/qiskit-circuit-library-GRY-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-GRY-1.png) Create a new Global RY (GRY) gate. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubits. * **theta** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – rotation angle about y-axis ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.GRY.mdx "--- title: GRZ description: API reference for qiskit.circuit.library.GRZ in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.GRZ --- # GRZ Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Global RZ gate. **Circuit symbol:** ```python ┌──────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 GRZ(φ) ├ │ │ q_2: ┤2 ├ └──────────┘ ``` The global RZ gate is native to atomic systems (ion traps, cold neutrals). The global RZ can be applied to multiple qubits simultaneously. In the one-qubit case, this is equivalent to an RZ(phi) operation, and is thus reduced to the RZGate. The global RZ gate is a direct sum of RZ operations on all individual qubits. $$ GRZ(\phi) = \exp(-i \sum_{i=1}^{n} Z_i \phi) $$ **Expanded Circuit:** ![../\_images/qiskit-circuit-library-GRZ-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-GRZ-1.png) Create a new Global RZ (GRZ) gate. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubits. * **phi** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – rotation angle about z-axis ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.GRZ.mdx "--- title: HamiltonianGate description: API reference for qiskit.circuit.library.HamiltonianGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.HamiltonianGate --- # HamiltonianGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Class for representing evolution by a Hamiltonian operator as a gate. This gate resolves to a [`UnitaryGate`](qiskit.circuit.library.UnitaryGate ""qiskit.circuit.library.UnitaryGate"") as $U(t) = \exp(-i t H)$, which can be decomposed into basis gates if it is 2 qubits or less, or simulated directly in Aer for more qubits. **Parameters** * **data** (*np.ndarray |* [*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"") *| BaseOperator*) – A hermitian operator. * **time** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Time evolution parameter. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Unitary name for backend \[Default: `None`]. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – if input data is not an N-qubit unitary operator. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.HamiltonianGate.base_class ""qiskit.circuit.library.HamiltonianGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### adjoint Return the adjoint of the unitary. ### conjugate Return the conjugate of the Hamiltonian. ### inverse Return the adjoint of the unitary. ### transpose Return the transpose of the Hamiltonian. ### validate\_parameter Hamiltonian parameter has to be an ndarray, operator or float. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.HamiltonianGate.mdx "--- title: HGate description: API reference for qiskit.circuit.library.HGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.HGate --- # HGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") Single-qubit Hadamard gate. This gate is a pi rotation about the X+Z axis, and has the effect of changing computation basis from $|0\rangle,|1\rangle$ to $|+\rangle,|-\rangle$ and vice-versa. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`h()`](qiskit.circuit.QuantumCircuit#h ""qiskit.circuit.QuantumCircuit.h"") method. **Circuit symbol:** ```python ┌───┐ q_0: ┤ H ├ └───┘ ``` **Matrix Representation:** $$ H = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix} $$ Create new H gate. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.HGate.base_class ""qiskit.circuit.library.HGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-H gate. One control qubit returns a CH gate. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### inverse Return inverted H gate (itself). **Parameters** **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). However, for this class this argument is ignored as this gate is self-inverse. **Returns** inverse gate (self-inverse). **Return type** [HGate](#qiskit.circuit.library.HGate ""qiskit.circuit.library.HGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.HGate.mdx "--- title: HiddenLinearFunction description: API reference for qiskit.circuit.library.HiddenLinearFunction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.HiddenLinearFunction --- # HiddenLinearFunction Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Circuit to solve the hidden linear function problem. The 2D Hidden Linear Function problem is determined by a 2D adjacency matrix A, where only elements that are nearest-neighbor on a grid have non-zero entries. Each row/column corresponds to one binary variable $x_i$. The hidden linear function problem is as follows: Consider the quadratic form $$ q(x) = \sum_{i,j=1}^{n}{x_i x_j} ~(\mathrm{mod}~ 4) $$ and restrict $q(x)$ onto the nullspace of A. This results in a linear function. $$ 2 \sum_{i=1}^{n}{z_i x_i} ~(\mathrm{mod}~ 4) \forall x \in \mathrm{Ker}(A) $$ and the goal is to recover this linear function (equivalently a vector $[z_0, ..., z_{n-1}]$). There can be multiple solutions. In \[1] it is shown that the present circuit solves this problem on a quantum computer in constant depth, whereas any corresponding solution on a classical computer would require circuits that grow logarithmically with $n$. Thus this circuit is an example of quantum advantage with shallow circuits. **Reference Circuit:** > ![../\_images/qiskit-circuit-library-HiddenLinearFunction-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-HiddenLinearFunction-1.png) **Reference:** \[1] S. Bravyi, D. Gosset, R. Koenig, Quantum Advantage with Shallow Circuits, 2017. [arXiv:1704.00690](https://arxiv.org/abs/1704.00690) Create new HLF circuit. **Parameters** **adjacency\_matrix** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]] |* [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – a symmetric n-by-n list of 0-1 lists. n will be the number of qubits. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – If A is not symmetric. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.HiddenLinearFunction.mdx "--- title: HRSCumulativeMultiplier description: API reference for qiskit.circuit.library.HRSCumulativeMultiplier in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.HRSCumulativeMultiplier --- # HRSCumulativeMultiplier Bases: `Multiplier` A multiplication circuit to store product of two input registers out-of-place. Circuit uses the approach from \[1]. As an example, a multiplier circuit that performs a non-modular multiplication on two 3-qubit sized registers with the default adder is as follows (where `Adder` denotes the `CDKMRippleCarryAdder`): ```python a_0: ────■───────────────────────── │ a_1: ────┼─────────■─────────────── │ │ a_2: ────┼─────────┼─────────■───── ┌───┴────┐┌───┴────┐┌───┴────┐ b_0: ┤0 ├┤0 ├┤0 ├ │ ││ ││ │ b_1: ┤1 ├┤1 ├┤1 ├ │ ││ ││ │ b_2: ┤2 ├┤2 ├┤2 ├ │ ││ ││ │ out_0: ┤3 ├┤ ├┤ ├ │ ││ ││ │ out_1: ┤4 ├┤3 ├┤ ├ │ Adder ││ Adder ││ Adder │ out_2: ┤5 ├┤4 ├┤3 ├ │ ││ ││ │ out_3: ┤6 ├┤5 ├┤4 ├ │ ││ ││ │ out_4: ┤ ├┤6 ├┤5 ├ │ ││ ││ │ out_5: ┤ ├┤ ├┤6 ├ │ ││ ││ │ aux_0: ┤7 ├┤7 ├┤7 ├ └────────┘└────────┘└────────┘ ``` Multiplication in this circuit is implemented in a classical approach by performing a series of shifted additions using one of the input registers while the qubits from the other input register act as control qubits for the adders. **References:** \[1] Häner et al., Optimizing Quantum Circuits for Arithmetic, 2018. [arXiv:1805.12445](https://arxiv.org/pdf/1805.12445.pdf) **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits in either input register for state $|a\rangle$ or $|b\rangle$. The two input registers must have the same number of qubits. * **num\_result\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of result qubits to limit the output to. If number of result qubits is $n$, multiplication modulo $2^n$ is performed to limit the output to the specified number of qubits. Default value is `2 * num_state_qubits` to represent any possible result from the multiplication of the two inputs. * **adder** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") *| None*) – Half adder circuit to be used for performing multiplication. The CDKMRippleCarryAdder is used as default if no adder is provided. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit object. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – If `num_result_qubits` is not default and a custom adder is provided. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### num\_result\_qubits The number of result qubits to limit the output to. **Returns** The number of result qubits. ### num\_state\_qubits The number of state qubits, i.e. the number of bits in each input register. **Returns** The number of state qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.HRSCumulativeMultiplier.mdx "--- title: IGate description: API reference for qiskit.circuit.library.IGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.IGate --- # IGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") Identity gate. Identity gate corresponds to a single-qubit gate wait cycle, and should not be optimized or unrolled (it is an opaque gate). Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the `i()` and [`id()`](qiskit.circuit.QuantumCircuit#id ""qiskit.circuit.QuantumCircuit.id"") methods. **Matrix Representation:** $$ I = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} $$ **Circuit symbol:** ```python ┌───┐ q_0: ┤ I ├ └───┘ ``` Create new Identity gate. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.IGate.base_class ""qiskit.circuit.library.IGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Returne the inverse gate (itself). **Parameters** **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – when set to `True`, this is typically used to return an [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"") with an inverse modifier set instead of a concrete [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate""). However, for this class this argument is ignored as this gate is self-inverse. **Returns** inverse gate (self-inverse). **Return type** [IGate](#qiskit.circuit.library.IGate ""qiskit.circuit.library.IGate"") . ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.IGate.mdx "--- title: Initialize description: API reference for qiskit.circuit.library.Initialize in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.Initialize --- # Initialize Bases: [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"") Complex amplitude initialization. Class that initializes some flexible collection of qubit registers, implemented by calling the [`StatePreparation`](qiskit.circuit.library.StatePreparation ""qiskit.circuit.library.StatePreparation"") class. Note that `Initialize` is an [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") and not a [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") since it contains a reset instruction, which is not unitary. **Parameters** * **params** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *| Sequence\[*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*] |* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The state to initialize to, can be either of the following. * Statevector or vector of complex amplitudes to initialize to. * Labels of basis states of the Pauli eigenstates Z, X, Y. See [`Statevector.from_label()`](qiskit.quantum_info.Statevector#from_label ""qiskit.quantum_info.Statevector.from_label""). Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label ‘01’ initializes the qubit zero to $|1\rangle$ and the qubit one to $|0\rangle$. * An integer that is used as a bitmap indicating which qubits to initialize to $|1\rangle$. Example: setting params to 5 would initialize qubit 0 and qubit 2 to $|1\rangle$ and qubit 1 to $|0\rangle$. * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – This parameter is only used if params is an int. Indicates the total number of qubits in the initialize call. Example: initialize covers 5 qubits and params is 3. This allows qubits 0 and 1 to be initialized to $|1\rangle$ and the remaining 3 qubits to be initialized to $|0\rangle$. * **normalize** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to normalize an input array to a unit vector. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.Initialize.base_class ""qiskit.circuit.library.Initialize.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params Return initialize params. ### unit Get the time unit of duration. ## Methods ### broadcast\_arguments 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. ### gates\_to\_uncompute Call to create a circuit with gates that take the desired vector to zero. **Returns** Circuit to take `self.params` vector to $|{00\ldots0}\rangle$ **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.Initialize.mdx "--- title: InnerProduct description: API reference for qiskit.circuit.library.InnerProduct in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.InnerProduct --- # InnerProduct Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") A 2n-qubit Boolean function that computes the inner product of two n-qubit vectors over $F_2$. This implementation is a phase oracle which computes the following transform. $$ \mathcal{IP}_{2n} : F_2^{2n} \rightarrow {-1, 1} \mathcal{IP}_{2n}(x_1, \cdots, x_n, y_1, \cdots, y_n) = (-1)^{x.y} $$ The corresponding unitary is a diagonal, which induces a -1 phase on any inputs where the inner product of the top and bottom registers is 1. Otherwise it keeps the input intact. ```python q0_0: ─■────────── │ q0_1: ─┼──■─────── │ │ q0_2: ─┼──┼──■──── │ │ │ q0_3: ─┼──┼──┼──■─ │ │ │ │ q1_0: ─■──┼──┼──┼─ │ │ │ q1_1: ────■──┼──┼─ │ │ q1_2: ───────■──┼─ │ q1_3: ──────────■─ ``` **Reference Circuit:** ![../\_images/qiskit-circuit-library-InnerProduct-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-InnerProduct-1.png) Return a circuit to compute the inner product of 2 n-qubit registers. **Parameters** **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – width of top and bottom registers (half total circuit width) ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.InnerProduct.mdx "--- title: IntegerComparator description: API reference for qiskit.circuit.library.IntegerComparator in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.IntegerComparator --- # IntegerComparator Bases: `BlueprintCircuit` Integer Comparator. Operator compares basis states $|i\rangle_n$ against a classically given integer $L$ of fixed value and flips a target qubit if $i \geq L$ (or $<$ depending on the parameter `geq`): $$ |i\rangle_n |0\rangle \mapsto |i\rangle_n |i \geq L\rangle $$ This operation is based on two’s complement implementation of binary subtraction but only uses carry bits and no actual result bits. If the most significant carry bit (the results bit) is 1, the $\geq$ condition is `True` otherwise it is `False`. Create a new fixed value comparator circuit. **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Number of state qubits. If this is set it will determine the number of qubits required for the circuit. * **value** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The fixed value to compare with. * **geq** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, evaluate a `>=` condition, else `<`. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of the circuit. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### geq Return whether the comparator compares greater or less equal. **Returns** True, if the comparator compares `>=`, False if `<`. ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters ### num\_qubits Return number of qubits. ### num\_state\_qubits The number of qubits encoding the state for the comparison. **Returns** The number of state qubits. ### 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. ### parameters ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### value The value to compare the qubit register to. **Returns** The value against which the value of the qubit register is compared. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.IntegerComparator.mdx "--- title: IQP description: API reference for qiskit.circuit.library.IQP in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.IQP --- # IQP Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Instantaneous quantum polynomial (IQP) circuit. The circuit consists of a column of Hadamard gates, a column of powers of T gates, a sequence of powers of CS gates (up to $\frac{n^2-n}{2}$ of them), and a final column of Hadamard gates, as introduced in \[1]. The circuit is parameterized by an n x n interactions matrix. The powers of each T gate are given by the diagonal elements of the interactions matrix. The powers of the CS gates are given by the upper triangle of the interactions matrix. **Reference Circuit:** ![../\_images/qiskit-circuit-library-IQP-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-IQP-1.png) **Expanded Circuit:** > ![../\_images/qiskit-circuit-library-IQP-2.png](/images/api/qiskit/1.0/qiskit-circuit-library-IQP-2.png) **References:** \[1] M. J. Bremner et al. Average-case complexity versus approximate simulation of commuting quantum computations, Phys. Rev. Lett. 117, 080501 (2016). [arXiv:1504.07999](https://arxiv.org/abs/1504.07999) Create IQP circuit. **Parameters** **interactions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *| np.ndarray*) – input n-by-n symmetric matrix. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if the inputs is not as symmetric matrix. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.IQP.mdx "--- title: Isometry description: API reference for qiskit.circuit.library.Isometry in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.Isometry --- # Isometry Bases: [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"") Decomposition of arbitrary isometries from $m$ to $n$ qubits. In particular, this allows to decompose unitaries (m=n) and to do state preparation ($m=0$). The decomposition is based on \[1]. **References:** **\[1] Iten et al., Quantum circuits for isometries (2016).** [Phys. Rev. A 93, 032318](https://journals.aps.org/pra/abstract/10.1103/PhysRevA.93.032318). **Parameters** * **isometry** (*np.ndarray*) – An isometry from $m$ to :math\`n\` qubits, i.e., a complex `np.ndarray` of dimension $2^n \times 2^m$ with orthonormal columns (given in the computational basis specified by the order of the ancillas and the input qubits, where the ancillas are considered to be more significant than the input qubits). * **num\_ancillas\_zero** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of additional ancillas that start in the state $|0\rangle$ (the $n-m$ ancillas required for providing the output of the isometry are not accounted for here). * **num\_ancillas\_dirty** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of additional ancillas that start in an arbitrary state. * **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Error tolerance of calculations. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.Isometry.base_class ""qiskit.circuit.library.Isometry.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inv\_gate Return the adjoint of the unitary. ### inverse 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. ### validate\_parameter Isometry parameter has to be an ndarray. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.Isometry.mdx "--- title: iSwapGate description: API reference for qiskit.circuit.library.iSwapGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.iSwapGate --- # iSwapGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") iSWAP gate. A 2-qubit XX+YY interaction. This is a Clifford and symmetric gate. Its action is to swap two qubit states and phase the $|01\rangle$ and $|10\rangle$ amplitudes by i. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`iswap()`](qiskit.circuit.QuantumCircuit#iswap ""qiskit.circuit.QuantumCircuit.iswap"") method. **Circuit Symbol:** ```python q_0: ─⨂─ │ q_1: ─⨂─ ``` **Reference Implementation:** ```python ┌───┐┌───┐ ┌───┐ q_0: ┤ S ├┤ H ├──■──┤ X ├───── ├───┤└───┘┌─┴─┐└─┬─┘┌───┐ q_1: ┤ S ├─────┤ X ├──■──┤ H ├ └───┘ └───┘ └───┘ ``` **Matrix Representation:** $$ iSWAP = R_{XX+YY}\left(-\frac{\pi}{2}\right) = \exp\left(i \frac{\pi}{4} \left(X{\otimes}X+Y{\otimes}Y\right)\right) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & i & 0 \\ 0 & i & 0 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} $$ This gate is equivalent to a SWAP up to a diagonal. $$ iSWAP = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} . \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & i & 0 & 0 \\ 0 & 0 & i & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} $$ Create new iSwap gate. ## Attributes ### base\_class Get the base class of this instruction. This is guaranteed to be in the inheritance tree of `self`. The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for \_all\_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioural perspective. In particular, you should *not* override [`base_class`](#qiskit.circuit.library.iSwapGate.base_class ""qiskit.circuit.library.iSwapGate.base_class"") if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrised gate with a particular set of parameters for the purposes of distinguishing it in a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") from the full parametrised gate. This is often exactly equivalent to `type(obj)`, except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example: ```python >>> isinstance(XGate(), XGate) True >>> type(XGate()) is XGate False >>> XGate().base_class is XGate True ``` In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that `Instruction.name` should be a more suitable discriminator in most situations. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.iSwapGate.mdx "--- title: LinearAmplitudeFunction description: API reference for qiskit.circuit.library.LinearAmplitudeFunction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.LinearAmplitudeFunction --- # LinearAmplitudeFunction Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") A circuit implementing a (piecewise) linear function on qubit amplitudes. An amplitude function $F$ of a function $f$ is a mapping $$ F|x\rangle|0\rangle = \sqrt{1 - \hat{f}(x)} |x\rangle|0\rangle + \sqrt{\hat{f}(x)} |x\rangle|1\rangle. $$ for a function $\hat{f}: \{ 0, ..., 2^n - 1 \} \rightarrow [0, 1]$, where $|x\rangle$ is a $n$ qubit state. This circuit implements $F$ for piecewise linear functions $\hat{f}$. In this case, the mapping $F$ can be approximately implemented using a Taylor expansion and linearly controlled Pauli-Y rotations, see \[1, 2] for more detail. This approximation uses a `rescaling_factor` to determine the accuracy of the Taylor expansion. In general, the function of interest $f$ is defined from some interval $[a,b]$, the `domain` to $[c,d]$, the `image`, instead of $\{ 1, ..., N \}$ to $[0, 1]$. Using an affine transformation we can rescale $f$ to $\hat{f}$: $$ \hat{f}(x) = \frac{f(\phi(x)) - c}{d - c} $$ with $$ \phi(x) = a + \frac{b - a}{2^n - 1} x. $$ If $f$ is a piecewise linear function on $m$ intervals $[p_{i-1}, p_i], i \in \{1, ..., m\}$ with slopes $\alpha_i$ and offsets $\beta_i$ it can be written as $$ f(x) = \sum_{i=1}^m 1_{[p_{i-1}, p_i]}(x) (\alpha_i x + \beta_i) $$ where $1_{[a, b]}$ is an indication function that is 1 if the argument is in the interval $[a, b]$ and otherwise 0. The breakpoints $p_i$ can be specified by the `breakpoints` argument. **References** **\[1]: Woerner, S., & Egger, D. J. (2018).** Quantum Risk Analysis. [arXiv:1806.06893](http://arxiv.org/abs/1806.06893) **\[2]: Gacon, J., Zoufal, C., & Woerner, S. (2020).** Quantum-Enhanced Simulation-Based Optimization. [arXiv:2005.10780](http://arxiv.org/abs/2005.10780) **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits used to encode the variable $x$. * **slope** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – The slope of the linear function. Can be a list of slopes if it is a piecewise linear function. * **offset** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – The offset of the linear function. Can be a list of offsets if it is a piecewise linear function. * **domain** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – The domain of the function as tuple $(x_\min{}, x_\max{})$. * **image** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – The image of the function as tuple $(f_\min{}, f_\max{})$. * **rescaling\_factor** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The rescaling factor to adjust the accuracy in the Taylor approximation. * **breakpoints** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None*) – The breakpoints if the function is piecewise linear. If None, the function is not piecewise. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of the circuit. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ## Methods ### post\_processing Map the function value of the approximated $\hat{f}$ to $f$. **Parameters** **scaled\_value** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – A function value from the Taylor expansion of $\hat{f}(x)$. **Returns** The `scaled_value` mapped back to the domain of $f$, by first inverting the transformation used for the Taylor approximation and then mapping back from $[0, 1]$ to the original domain. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.LinearAmplitudeFunction.mdx "--- title: LinearFunction description: API reference for qiskit.circuit.library.LinearFunction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.LinearFunction --- # LinearFunction Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") A linear reversible circuit on n qubits. Internally, a linear function acting on n qubits is represented as a n x n matrix of 0s and 1s in numpy array format. A linear function can be synthesized into CX and SWAP gates using the Patel–Markov–Hayes algorithm, as implemented in [`synth_cnot_count_full_pmh()`](synthesis#qiskit.synthesis.synth_cnot_count_full_pmh ""qiskit.synthesis.synth_cnot_count_full_pmh"") based on reference \[1]. For efficiency, the internal n x n matrix is stored in the format expected by cnot\_synth, which is the big-endian (and not the little-endian) bit-ordering convention. **Example:** the circuit ```python q_0: ──■── ┌─┴─┐ q_1: ┤ X ├ └───┘ q_2: ───── ``` is represented by a 3x3 linear matrix $$ \begin{pmatrix} 1 & 0 & 0 \\ 1 & 1 & 0 \\ 0 & 0 & 1 \end{pmatrix} $$ **References:** \[1] Ketan N. Patel, Igor L. Markov, and John P. Hayes, Optimal synthesis of linear reversible circuits, Quantum Inf. Comput. 8(3) (2008). [Online at umich.edu.](https://web.eecs.umich.edu/~imarkov/pubs/jour/qic08-cnot.pdf) Create a new linear function. **Parameters** * **linear** ([*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)"")*] | np.ndarray\[*[*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*] |* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *|*[*LinearFunction*](#qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.LinearFunction"") *|*[*PermutationGate*](qiskit.circuit.library.PermutationGate ""qiskit.circuit.library.PermutationGate"") *|*[*Clifford*](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"")) – data from which a linear function can be constructed. It can be either a nxn matrix (describing the linear transformation), a permutation (which is a special case of a linear function), another linear function, a clifford (when it corresponds to a linear function), or a quantum circuit composed of linear gates (CX and SWAP) and other objects described above, including nested subcircuits. * **validate\_input** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, performs more expensive input validation checks, such as checking that a given n x n matrix is invertible. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if the input is invalid: either the input matrix is not square or not invertible, or the input quantum circuit contains non-linear objects (for example, a Hadamard gate, or a Clifford that does not correspond to a linear function). ## Attributes ### 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.LinearFunction.base_class ""qiskit.circuit.library.LinearFunction.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### linear Returns the n x n matrix representing this linear function. ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### original\_circuit Returns the original circuit used to construct this linear function (including None, when the linear function is not constructed from a circuit). ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### extend\_with\_identity Extend linear function to a linear function over nq qubits, with identities on other subsystems. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubits of the extended function. * **positions** ([*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)"")*]*) – describes the positions of original qubits in the extended function’s qubits. **Returns** extended linear function. **Return type** [LinearFunction](#qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.LinearFunction"") ### function\_str Return string representation of the linear function viewed as a linear transformation. ### is\_permutation Returns whether this linear function is a permutation, that is whether every row and every column of the n x n matrix has exactly one 1. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### mat\_str Return string representation of the linear function viewed as a matrix with 0/1 entries. ### permutation\_pattern This method first checks if a linear function is a permutation and raises a qiskit.circuit.exceptions.CircuitError if not. In the case that this linear function is a permutation, returns the permutation pattern. ### synthesize Synthesizes the linear function into a quantum circuit. **Returns** A circuit implementing the evolution. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### validate\_parameter Parameter validation ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.LinearFunction.mdx "--- title: LinearPauliRotations description: API reference for qiskit.circuit.library.LinearPauliRotations in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.LinearPauliRotations --- # LinearPauliRotations Bases: [`FunctionalPauliRotations`](qiskit.circuit.library.FunctionalPauliRotations ""qiskit.circuit.library.arithmetic.functional_pauli_rotations.FunctionalPauliRotations"") Linearly-controlled X, Y or Z rotation. For a register of state qubits $|x\rangle$, a target qubit $|0\rangle$ and the basis `'Y'` this circuit acts as: ```python q_0: ─────────────────────────■───────── ... ────────────────────── │ . │ q_(n-1): ─────────────────────────┼───────── ... ───────────■────────── ┌────────────┐ ┌───────┴───────┐ ┌─────────┴─────────┐ q_n: ─┤ RY(offset) ├──┤ RY(2^0 slope) ├ ... ┤ RY(2^(n-1) slope) ├ └────────────┘ └───────────────┘ └───────────────────┘ ``` This can for example be used to approximate linear functions, with $a =$ `slope`$/2$ and $b =$ `offset`$/2$ and the basis `'Y'`: $$ |x\rangle |0\rangle \mapsto \cos(ax + b)|x\rangle|0\rangle + \sin(ax + b)|x\rangle |1\rangle $$ Since for small arguments $\sin(x) \approx x$ this operator can be used to approximate linear functions. Create a new linear rotation circuit. **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits representing the state $|x\rangle$. * **slope** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The slope of the controlled rotation. * **offset** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The offset of the controlled rotation. * **basis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The type of Pauli rotation (‘X’, ‘Y’, ‘Z’). * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit object. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### basis The kind of Pauli rotation to be used. Set the basis to ‘X’, ‘Y’ or ‘Z’ for controlled-X, -Y, or -Z rotations respectively. **Returns** The kind of Pauli rotation used in controlled rotation. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancilla\_qubits The minimum number of ancilla qubits in the circuit. **Returns** The minimal number of ancillas required. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters ### num\_qubits Return number of qubits. ### num\_state\_qubits The number of state qubits representing the state $|x\rangle$. **Returns** The number of state qubits. ### offset The angle of the single qubit offset rotation on the target qubit. Before applying the controlled rotations, a single rotation of angle `offset` is applied to the target qubit. **Returns** The offset angle. ### 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. ### parameters ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### slope The multiplicative factor in the rotation angle of the controlled rotations. The rotation angles are `slope * 2^0`, `slope * 2^1`, … , `slope * 2^(n-1)` where `n` is the number of state qubits. **Returns** The rotation angle common in all controlled rotations. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.LinearPauliRotations.mdx "--- title: MCMT description: API reference for qiskit.circuit.library.MCMT in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.MCMT --- # MCMT Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") The multi-controlled multi-target gate, for an arbitrary singly controlled target gate. For example, the H gate controlled on 3 qubits and acting on 2 target qubit is represented as: ```python ───■──── │ ───■──── │ ───■──── ┌──┴───┐ ┤0 ├ │ 2-H │ ┤1 ├ └──────┘ ``` This default implementations requires no ancilla qubits, by broadcasting the target gate to the number of target qubits and using Qiskit’s generic control routine to control the broadcasted target on the control qubits. If ancilla qubits are available, a more efficient variant using the so-called V-chain decomposition can be used. This is implemented in [`MCMTVChain`](qiskit.circuit.library.MCMTVChain ""qiskit.circuit.library.MCMTVChain""). Create a new multi-control multi-target gate. **Parameters** * **gate** ([*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"") *| Callable\[\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*,* [*circuit.Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*,* [*circuit.Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*],* [*circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")*]*) – The gate to be applied controlled on the control qubits and applied to the target qubits. Can be either a Gate or a circuit method. If it is a callable, it will be casted to a Gate. * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of control qubits. * **num\_target\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of target qubits. **Raises** * [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the gate cannot be casted to a controlled gate. * [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the number of controls or targets is 0. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancilla\_qubits Return the number of ancillas. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ## Methods ### control Return the controlled version of the MCMT circuit. ### inverse Return the inverse MCMT circuit, which is itself. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.MCMT.mdx "--- title: MCMTVChain description: API reference for qiskit.circuit.library.MCMTVChain in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.MCMTVChain --- # MCMTVChain Bases: [`MCMT`](qiskit.circuit.library.MCMT ""qiskit.circuit.library.generalized_gates.mcmt.MCMT"") The MCMT implementation using the CCX V-chain. This implementation requires ancillas but is decomposed into a much shallower circuit than the default implementation in [`MCMT`](qiskit.circuit.library.MCMT ""qiskit.circuit.library.MCMT""). **Expanded Circuit:** ![../\_images/qiskit-circuit-library-MCMTVChain-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-MCMTVChain-1.png) **Examples:** > ```python > >>> from qiskit.circuit.library import HGate > >>> MCMTVChain(HGate(), 3, 2).draw() > ``` > > **q\_0: ──■────────────────────────■──** > > │ │ > > **q\_1: ──■────────────────────────■──** > > │ │ > > **q\_2: ──┼────■──────────────■────┼──** > > │ │ ┌───┐ │ │ > > **q\_3: ──┼────┼──┤ H ├───────┼────┼──** > > │ │ └─┬─┘┌───┐ │ │ > > **q\_4: ──┼────┼────┼──┤ H ├──┼────┼──** > > ┌─┴─┐ │ │ └─┬─┘ │ ┌─┴─┐ > > **q\_5: ┤ X ├──■────┼────┼────■──┤ X ├** > > └───┘┌─┴─┐ │ │ ┌─┴─┐└───┘ > > **q\_6: ─────┤ X ├──■────■──┤ X ├─────** > > └───┘ └───┘ Create a new multi-control multi-target gate. **Parameters** * **gate** ([*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"") *| Callable\[\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*,* [*circuit.Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*,* [*circuit.Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*],* [*circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")*]*) – The gate to be applied controlled on the control qubits and applied to the target qubits. Can be either a Gate or a circuit method. If it is a callable, it will be casted to a Gate. * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of control qubits. * **num\_target\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of target qubits. **Raises** * [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the gate cannot be casted to a controlled gate. * [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the number of controls or targets is 0. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancilla\_qubits Return the number of ancilla qubits required. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ## Methods ### inverse Return the inverse MCMT circuit, which is itself. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.MCMTVChain.mdx "--- title: MCPhaseGate description: API reference for qiskit.circuit.library.MCPhaseGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.MCPhaseGate --- # MCPhaseGate Bases: [`ControlledGate`](qiskit.circuit.ControlledGate ""qiskit.circuit.controlledgate.ControlledGate"") Multi-controlled-Phase gate. This is a diagonal and symmetric gate that induces a phase on the state of the target qubit, depending on the state of the control qubits. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`mcp()`](qiskit.circuit.QuantumCircuit#mcp ""qiskit.circuit.QuantumCircuit.mcp"") method. **Circuit symbol:** ```python q_0: ───■──── │ . │ q_(n-1): ───■──── ┌──┴───┐ q_n: ┤ P(λ) ├ └──────┘ ``` `CPhaseGate`: The singly-controlled-version of this gate. Create new MCPhase gate. ## Attributes ### 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.MCPhaseGate.base_class ""qiskit.circuit.library.MCPhaseGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### control 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"") ### inverse Return inverted MCU1 gate ($MCU1(\lambda)^{\dagger} = MCU1(-\lambda)$) ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.MCPhaseGate.mdx "--- title: MCXGate description: API reference for qiskit.circuit.library.MCXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.MCXGate --- # MCXGate Bases: [`ControlledGate`](qiskit.circuit.ControlledGate ""qiskit.circuit.controlledgate.ControlledGate"") The general, multi-controlled X gate. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`mcx()`](qiskit.circuit.QuantumCircuit#mcx ""qiskit.circuit.QuantumCircuit.mcx"") method. Create new MCX gate. ## Attributes ### 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.MCXGate.base_class ""qiskit.circuit.library.MCXGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_ancilla\_qubits The number of ancilla qubits. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### control Return a multi-controlled-X gate with more control lines. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### get\_num\_ancilla\_qubits Get the number of required ancilla qubits without instantiating the class. This staticmethod might be necessary to check the number of ancillas before creating the gate, or to use the number of ancillas in the initialization. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### inverse Invert this gate. The MCX 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** [MCXGate](#qiskit.circuit.library.MCXGate ""qiskit.circuit.library.MCXGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.MCXGate.mdx "--- title: MCXGrayCode description: API reference for qiskit.circuit.library.MCXGrayCode in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.MCXGrayCode --- # MCXGrayCode Bases: [`MCXGate`](qiskit.circuit.library.MCXGate ""qiskit.circuit.library.standard_gates.x.MCXGate"") Implement the multi-controlled X gate using the Gray code. This delegates the implementation to the MCU1 gate, since $X = H \cdot U1(\pi) \cdot H$. Create new MCX gate. ## Attributes ### 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.MCXGrayCode.base_class ""qiskit.circuit.library.MCXGrayCode.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_ancilla\_qubits The number of ancilla qubits. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### inverse Invert this gate. The MCX 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** [MCXGrayCode](#qiskit.circuit.library.MCXGrayCode ""qiskit.circuit.library.MCXGrayCode"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.MCXGrayCode.mdx "--- title: MCXRecursive description: API reference for qiskit.circuit.library.MCXRecursive in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.MCXRecursive --- # MCXRecursive Bases: [`MCXGate`](qiskit.circuit.library.MCXGate ""qiskit.circuit.library.standard_gates.x.MCXGate"") Implement the multi-controlled X gate using recursion. Using a single ancilla qubit, the multi-controlled X gate is recursively split onto four sub-registers. This is done until we reach the 3- or 4-controlled X gate since for these we have a concrete implementation that do not require ancillas. Create new MCX gate. ## Attributes ### 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.MCXRecursive.base_class ""qiskit.circuit.library.MCXRecursive.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_ancilla\_qubits The number of ancilla qubits. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### get\_num\_ancilla\_qubits Get the number of required ancilla qubits. ### inverse Invert this gate. The MCX 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** [MCXRecursive](#qiskit.circuit.library.MCXRecursive ""qiskit.circuit.library.MCXRecursive"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.MCXRecursive.mdx "--- title: MCXVChain description: API reference for qiskit.circuit.library.MCXVChain in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.MCXVChain --- # MCXVChain Bases: [`MCXGate`](qiskit.circuit.library.MCXGate ""qiskit.circuit.library.standard_gates.x.MCXGate"") Implement the multi-controlled X gate using a V-chain of CX gates. Create new MCX gate. ## Attributes ### 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.MCXVChain.base_class ""qiskit.circuit.library.MCXVChain.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### ctrl\_state Return the control state of the gate as a decimal integer. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### 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. ### duration Get the duration. ### label Return instruction label ### 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. ### name Get name of gate. If the gate has open controls the gate name will become: > \ where \ is the gate name for the default case of closed control qubits and \ is the integer value of the control state for the gate. ### num\_ancilla\_qubits The number of ancilla qubits. ### num\_clbits Return the number of clbits. ### 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)"") ### num\_qubits Return the number of qubits. ### 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 ### unit Get the time unit of duration. ## Methods ### get\_num\_ancilla\_qubits Get the number of required ancilla qubits. ### inverse Invert this gate. The MCX 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** [MCXVChain](#qiskit.circuit.library.MCXVChain ""qiskit.circuit.library.MCXVChain"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.MCXVChain.mdx "--- title: Measure description: API reference for qiskit.circuit.library.Measure in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.Measure --- # Measure Bases: [`SingletonInstruction`](circuit_singleton#qiskit.circuit.singleton.SingletonInstruction ""qiskit.circuit.singleton.SingletonInstruction"") Quantum measurement in the computational basis. Create new measurement instruction. ## Attributes ### 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.Measure.base_class ""qiskit.circuit.library.Measure.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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. ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### 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"") ### soft\_compare 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)"") ### 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. ### validate\_parameter Instruction parameters has no validation or normalization. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.Measure.mdx "--- title: MSGate description: API reference for qiskit.circuit.library.MSGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.MSGate --- # MSGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") MSGate has been deprecated. Please use `GMS` in `qiskit.circuit.generalized_gates` instead. Global Mølmer–Sørensen gate. The Mølmer–Sørensen gate is native to ion-trap systems. The global MS can be applied to multiple ions to entangle multiple qubits simultaneously. In the two-qubit case, this is equivalent to an XX(theta) interaction, and is thus reduced to the RXXGate. Create new MS gate. ## Attributes ### 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.MSGate.base_class ""qiskit.circuit.library.MSGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.MSGate.mdx "--- title: NLocal description: API reference for qiskit.circuit.library.NLocal in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.NLocal --- # NLocal Bases: `BlueprintCircuit` The n-local circuit class. The structure of the n-local circuit are alternating rotation and entanglement layers. In both layers, parameterized circuit-blocks act on the circuit in a defined way. In the rotation layer, the blocks are applied stacked on top of each other, while in the entanglement layer according to the `entanglement` strategy. The circuit blocks can have arbitrary sizes (smaller equal to the number of qubits in the circuit). Each layer is repeated `reps` times, and by default a final rotation layer is appended. For instance, a rotation block on 2 qubits and an entanglement block on 4 qubits using `'linear'` entanglement yields the following circuit. ```python ┌──────┐ ░ ┌──────┐ ░ ┌──────┐ ┤0 ├─░─┤0 ├──────────────── ... ─░─┤0 ├ │ Rot │ ░ │ │┌──────┐ ░ │ Rot │ ┤1 ├─░─┤1 ├┤0 ├──────── ... ─░─┤1 ├ ├──────┤ ░ │ Ent ││ │┌──────┐ ░ ├──────┤ ┤0 ├─░─┤2 ├┤1 ├┤0 ├ ... ─░─┤0 ├ │ Rot │ ░ │ ││ Ent ││ │ ░ │ Rot │ ┤1 ├─░─┤3 ├┤2 ├┤1 ├ ... ─░─┤1 ├ ├──────┤ ░ └──────┘│ ││ Ent │ ░ ├──────┤ ┤0 ├─░─────────┤3 ├┤2 ├ ... ─░─┤0 ├ │ Rot │ ░ └──────┘│ │ ░ │ Rot │ ┤1 ├─░─────────────────┤3 ├ ... ─░─┤1 ├ └──────┘ ░ └──────┘ ░ └──────┘ | | +---------------------------------+ repeated reps times ``` If specified, barriers can be inserted in between every block. If an initial state object is provided, it is added in front of the NLocal. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits of the circuit. * **rotation\_blocks** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] |* [*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")*] | None*) – The blocks used in the rotation layers. If multiple are passed, these will be applied one after another (like new sub-layers). * **entanglement\_blocks** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] |* [*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")*] | None*) – The blocks used in the entanglement layers. If multiple are passed, these will be applied one after another. To use different entanglements for the sub-layers, see [`get_entangler_map()`](#qiskit.circuit.library.NLocal.get_entangler_map ""qiskit.circuit.library.NLocal.get_entangler_map""). * **entanglement** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]] | None*) – The indices specifying on which qubits the input blocks act. If `None`, the entanglement blocks are applied at the top of the circuit. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Specifies how often the rotation blocks and entanglement blocks are repeated. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True`, barriers are inserted in between each layer. If `False`, no barriers are inserted. * **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The prefix used if default parameters are generated. * **overwrite\_block\_parameters** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(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)"")*\[*[*Parameter*](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")*]]*) – If the parameters in the added blocks should be overwritten. If `False`, the parameters in the blocks are not changed. * **skip\_final\_rotation\_layer** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether a final rotation layer is added to the circuit. * **skip\_unentangled\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True`, the rotation gates act only on qubits that are entangled. If `False`, the rotation gates act on all qubits. * **initial\_state** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *| None*) – A [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") object which can be used to describe an initial state prepended to the NLocal circuit. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The name of the circuit. * **flatten** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – Set this to `True` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you’re using this circuit for anything besides visualization its **strongly** recommended to set this flag to `True` to avoid a large performance overhead for parameter binding. **Raises** * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If `reps` parameter is less than or equal to 0. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – If `reps` parameter is not an int value. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### entanglement Get the entanglement strategy. **Returns** The entanglement strategy, see [`get_entangler_map()`](#qiskit.circuit.library.NLocal.get_entangler_map ""qiskit.circuit.library.NLocal.get_entangler_map"") for more detail on how the format is interpreted. ### entanglement\_blocks The blocks in the entanglement layers. **Returns** The blocks in the entanglement layers. ### flatten Returns whether the circuit is wrapped in nested gates/instructions or flattened. ### global\_phase Return the global phase of the current circuit scope in radians. ### initial\_state Return the initial state that is added in front of the n-local circuit. **Returns** The initial state. ### insert\_barriers If barriers are inserted in between the layers or not. **Returns** `True`, if barriers are inserted in between the layers, `False` if not. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_layers Return the number of layers in the n-local circuit. **Returns** The number of layers in the circuit. ### num\_parameters ### num\_parameters\_settable The number of total parameters that can be set to distinct values. This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from `num_parameters` which counts the number of unique [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") objects currently in the circuit. **Returns** The number of parameters originally available in the circuit. This quantity does not require the circuit to be built yet. ### num\_qubits Returns the number of qubits in this circuit. **Returns** The number of qubits. ### 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. ### ordered\_parameters The parameters used in the underlying circuit. This includes float values and duplicates. **Examples** ```python >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] ``` **Returns** The parameters objects used in the circuit. ### parameter\_bounds The parameter bounds for the unbound parameters in the circuit. **Returns** A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If `None` is returned, problem is fully unbounded. ### parameters ### preferred\_init\_points The initial points for the parameters. Can be stored as initial guess in optimization. **Returns** The initial values for the parameters, or None, if none have been set. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### reps The number of times rotation and entanglement block are repeated. **Returns** The number of repetitions. ### rotation\_blocks The blocks in the rotation layers. **Returns** The blocks in the rotation layers. ## Methods ### add\_layer Append another layer to the NLocal. **Parameters** * **other** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *|*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")) – The layer to compose, can be another NLocal, an Instruction or Gate, or a QuantumCircuit. * **entanglement** ([*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)"")*] |* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]] | None*) – The entanglement or qubit indices. * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, `other` is appended to the front, else to the back. **Returns** self, such that chained composes are possible. **Raises** [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – If other is not compatible, i.e. is no Instruction and does not have a to\_instruction method. **Return type** [NLocal](#qiskit.circuit.library.NLocal ""qiskit.circuit.library.NLocal"") ### assign\_parameters Assign parameters to the n-local circuit. This method also supports passing a list instead of a dictionary. If a list is passed, the list must have the same length as the number of unbound parameters in the circuit. The parameters are assigned in the order of the parameters in [`ordered_parameters()`](#qiskit.circuit.library.NLocal.ordered_parameters ""qiskit.circuit.library.NLocal.ordered_parameters""). **Returns** A copy of the NLocal circuit with the specified parameters. **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the parameters are given as list and do not match the number of parameters. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") | None ### get\_entangler\_map Get the entangler map for in the repetition `rep_num` and the block `block_num`. The entangler map for the current block is derived from the value of `self.entanglement`. Below the different cases are listed, where `i` and `j` denote the repetition number and the block number, respectively, and `n` the number of qubits in the block. | entanglement type | entangler map | | -------------------------------- | -------------------------------------------------- | | `None` | `[[0, ..., n - 1]]` | | `str` (e.g `'full'`) | the specified connectivity on `n` qubits | | `List[int]` | \[`entanglement`] | | `List[List[int]]` | `entanglement` | | `List[List[List[int]]]` | `entanglement[i]` | | `List[List[List[List[int]]]]` | `entanglement[i][j]` | | `List[str]` | the connectivity specified in `entanglement[i]` | | `List[List[str]]` | the connectivity specified in `entanglement[i][j]` | | `Callable[int, str]` | same as `List[str]` | | `Callable[int, List[List[int]]]` | same as `List[List[List[int]]]` | Note that all indices are to be taken modulo the length of the array they act on, i.e. no out-of-bounds index error will be raised but we re-iterate from the beginning of the list. **Parameters** * **rep\_num** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The current repetition we are in. * **block\_num** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The block number within the entanglement layers. * **num\_block\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits in the block. **Returns** The entangler map for the current block in the current repetition. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the value of `entanglement` could not be cast to a corresponding entangler map. **Return type** [*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence ""(in Python v3.12)"")\[[*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence ""(in Python v3.12)"")\[[int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")]] ### get\_unentangled\_qubits Get the indices of unentangled qubits in a set. **Returns** The unentangled qubits. **Return type** [set](https://docs.python.org/3/library/stdtypes.html#set ""(in Python v3.12)"")\[[int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")] ### print\_settings Returns information about the setting. **Returns** The class name and the attributes/parameters of the instance as `str`. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.NLocal.mdx "--- title: OR description: API reference for qiskit.circuit.library.OR in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.OR --- # OR Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") A circuit implementing the logical OR operation on a number of qubits. For the OR operation the state $|1\rangle$ is interpreted as `True`. The result qubit is flipped, if the state of any variable qubit is `True`. The OR is implemented using a multi-open-controlled X gate (i.e. flips if the state is $|0\rangle$) and applying an X gate on the result qubit. Using a list of flags, qubits can be skipped or negated. The OR gate without special flags: ![../\_images/qiskit-circuit-library-OR-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-OR-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` or one of the last two are `True` we use the flags `[-1, 0, 0, 1, 1]`. ![../\_images/qiskit-circuit-library-OR-2.png](/images/api/qiskit/1.0/qiskit-circuit-library-OR-2.png) Create a new logical OR 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** (*Optional\[List\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – 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 Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.OR.mdx "--- title: PauliEvolutionGate description: API reference for qiskit.circuit.library.PauliEvolutionGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PauliEvolutionGate --- # PauliEvolutionGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Time-evolution of an operator consisting of Paulis. For an operator $H$ consisting of Pauli terms and (real) evolution time $t$ this gate implements $$ U(t) = e^{-itH}. $$ This gate serves as a high-level definition of the evolution and can be synthesized into a circuit using different algorithms. The evolution gates are related to the Pauli rotation gates by a factor of 2. For example the time evolution of the Pauli $X$ operator is connected to the Pauli $X$ rotation $R_X$ by $$ U(t) = e^{-itX} = R_X(2t). $$ **Examples:** ```python from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import PauliEvolutionGate from qiskit.quantum_info import SparsePauliOp X = SparsePauliOp(""X"") Z = SparsePauliOp(""Z"") # build the evolution gate operator = (Z ^ Z) - 0.1 * (X ^ I) evo = PauliEvolutionGate(operator, time=0.2) # plug it into a circuit circuit = QuantumCircuit(2) circuit.append(evo, range(2)) print(circuit.draw()) ``` The above will print (note that the `-0.1` coefficient is not printed!): ```python ┌──────────────────────────┐ q_0: ┤0 ├ │ exp(-it (ZZ + XI))(0.2) │ q_1: ┤1 ├ └──────────────────────────┘ ``` **References:** \[1] G. Li et al. Paulihedral: A Generalized Block-Wise Compiler Optimization Framework For Quantum Simulation Kernels (2021). \[[arXiv:2109.03371](https://arxiv.org/abs/2109.03371)] **Parameters** * **operator** ([*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") *|*[*SparsePauliOp*](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The operator to evolve. Can also be provided as list of non-commuting operators where the elements are sums of commuting operators. For example: `[XY + YX, ZZ + ZI + IZ, YY]`. * **time** (*Union\[*[*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)"")*,* [*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")*]*) – The evolution time. * **label** (*Optional\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – A label for the gate to display in visualizations. Per default, the label is set to `exp(-it )` where `` is the sum of the Paulis. Note that the label does not include any coefficients of the Paulis. See the class docstring for an example. * **synthesis** (*Optional\[*[*EvolutionSynthesis*](qiskit.synthesis.EvolutionSynthesis ""qiskit.synthesis.EvolutionSynthesis"")*]*) – A synthesis strategy. If None, the default synthesis is the Lie-Trotter product formula with a single repetition. ## Attributes ### 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.PauliEvolutionGate.base_class ""qiskit.circuit.library.PauliEvolutionGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### time Return the evolution time as stored in the gate parameters. **Returns** The evolution time. ### unit Get the time unit of duration. ## Methods ### validate\_parameter Gate parameters should be int, float, or ParameterExpression **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") | [*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PauliEvolutionGate.mdx "--- title: PauliFeatureMap description: API reference for qiskit.circuit.library.PauliFeatureMap in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PauliFeatureMap --- # PauliFeatureMap Bases: [`NLocal`](qiskit.circuit.library.NLocal ""qiskit.circuit.library.n_local.n_local.NLocal"") The Pauli Expansion circuit. The Pauli Expansion circuit is a data encoding circuit that transforms input data $\vec{x} \in \mathbb{R}^n$, where n is the `feature_dimension`, as $$ U_{\Phi(\vec{x})}=\exp\left(i\sum_{S \in \mathcal{I}} \phi_S(\vec{x})\prod_{i\in S} P_i\right). $$ Here, $S$ is a set of qubit indices that describes the connections in the feature map, $\mathcal{I}$ is a set containing all these index sets, and $P_i \in \{I, X, Y, Z\}$. Per default the data-mapping $\phi_S$ is $$ \phi_S(\vec{x}) = \begin{cases} x_i \text{ if } S = \{i\} \\ \prod_{j \in S} (\pi - x_j) \text{ if } |S| > 1 \end{cases}. $$ The possible connections can be set using the `entanglement` and `paulis` arguments. For example, for single-qubit $Z$ rotations and two-qubit $YY$ interactions between all qubit pairs, we can set: ```python feature_map = PauliFeatureMap(..., paulis=[""Z"", ""YY""], entanglement=""full"") ``` which will produce blocks of the form ```python ┌───┐┌──────────────┐┌──────────┐ ┌───────────┐ ┤ H ├┤ U1(2.0*x[0]) ├┤ RX(pi/2) ├──■───────────────────────────────────────■──┤ RX(-pi/2) ├ ├───┤├──────────────┤├──────────┤┌─┴─┐┌─────────────────────────────────┐┌─┴─┐├───────────┤ ┤ H ├┤ U1(2.0*x[1]) ├┤ RX(pi/2) ├┤ X ├┤ U1(2.0*(pi - x[0])*(pi - x[1])) ├┤ X ├┤ RX(-pi/2) ├ └───┘└──────────────┘└──────────┘└───┘└─────────────────────────────────┘└───┘└───────────┘ ``` The circuit contains `reps` repetitions of this transformation. Please refer to [`ZFeatureMap`](qiskit.circuit.library.ZFeatureMap ""qiskit.circuit.library.ZFeatureMap"") for the case of single-qubit Pauli-$Z$ rotations and to [`ZZFeatureMap`](qiskit.circuit.library.ZZFeatureMap ""qiskit.circuit.library.ZZFeatureMap"") for the single- and two-qubit Pauli-$Z$ rotations. **Examples** ```python >>> prep = PauliFeatureMap(2, reps=1, paulis=['ZZ']) >>> print(prep) ┌───┐ q_0: ┤ H ├──■───────────────────────────────────────■── ├───┤┌─┴─┐┌─────────────────────────────────┐┌─┴─┐ q_1: ┤ H ├┤ X ├┤ U1(2.0*(pi - x[0])*(pi - x[1])) ├┤ X ├ └───┘└───┘└─────────────────────────────────┘└───┘ ``` ```python >>> prep = PauliFeatureMap(2, reps=1, paulis=['Z', 'XX']) >>> print(prep) ┌───┐┌──────────────┐┌───┐ ┌───┐ q_0: ┤ H ├┤ U1(2.0*x[0]) ├┤ H ├──■───────────────────────────────────────■──┤ H ├ ├───┤├──────────────┤├───┤┌─┴─┐┌─────────────────────────────────┐┌─┴─┐├───┤ q_1: ┤ H ├┤ U1(2.0*x[1]) ├┤ H ├┤ X ├┤ U1(2.0*(pi - x[0])*(pi - x[1])) ├┤ X ├┤ H ├ └───┘└──────────────┘└───┘└───┘└─────────────────────────────────┘└───┘└───┘ ``` ```python >>> prep = PauliFeatureMap(2, reps=1, paulis=['ZY']) >>> print(prep) ┌───┐┌──────────┐ ┌───────────┐ q_0: ┤ H ├┤ RX(pi/2) ├──■───────────────────────────────────────■──┤ RX(-pi/2) ├ ├───┤└──────────┘┌─┴─┐┌─────────────────────────────────┐┌─┴─┐└───────────┘ q_1: ┤ H ├────────────┤ X ├┤ U1(2.0*(pi - x[0])*(pi - x[1])) ├┤ X ├───────────── └───┘ └───┘└─────────────────────────────────┘└───┘ ``` ```python >>> from qiskit.circuit.library import EfficientSU2 >>> prep = PauliFeatureMap(3, reps=3, paulis=['Z', 'YY', 'ZXZ']) >>> wavefunction = EfficientSU2(3) >>> classifier = prep.compose(wavefunction >>> classifier.num_parameters 27 >>> classifier.count_ops() OrderedDict([('cx', 39), ('rx', 36), ('u1', 21), ('h', 15), ('ry', 12), ('rz', 12)]) ``` References: \[1] Havlicek et al. Supervised learning with quantum enhanced feature spaces, [Nature 567, 209-212 (2019)](https://www.nature.com/articles/s41586-019-0980-2). Create a new Pauli expansion circuit. **Parameters** * **feature\_dimension** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Number of qubits in the circuit. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of repeated circuits. * **entanglement** ([*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)"")*\[*[*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)"")*]] |* [*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(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)"")*]]*) – Specifies the entanglement structure. Refer to [`NLocal`](qiskit.circuit.library.NLocal ""qiskit.circuit.library.NLocal"") for detail. * **alpha** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The Pauli rotation factor, multiplicative to the pauli rotations * **paulis** ([*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 strings for to-be-used paulis. If None are provided, `['Z', 'ZZ']` will be used. * **data\_map\_func** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[*[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")*],* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None*) – A mapping function for data x which can be supplied to override the default mapping from `self_product()`. * **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The prefix used if default parameters are generated. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, barriers are inserted in between the evolution instructions and hadamard layers. ## Attributes ### alpha The Pauli rotation factor (alpha). **Returns** The Pauli rotation factor. ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### entanglement Get the entanglement strategy. **Returns** The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted. ### entanglement\_blocks ### feature\_dimension Returns the feature dimension (which is equal to the number of qubits). **Returns** The feature dimension of this feature map. ### flatten Returns whether the circuit is wrapped in nested gates/instructions or flattened. ### global\_phase Return the global phase of the current circuit scope in radians. ### initial\_state Return the initial state that is added in front of the n-local circuit. **Returns** The initial state. ### insert\_barriers If barriers are inserted in between the layers or not. **Returns** `True`, if barriers are inserted in between the layers, `False` if not. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_layers Return the number of layers in the n-local circuit. **Returns** The number of layers in the circuit. ### num\_parameters ### num\_parameters\_settable The number of distinct parameters. ### num\_qubits Returns the number of qubits in this circuit. **Returns** The number of qubits. ### 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. ### ordered\_parameters The parameters used in the underlying circuit. This includes float values and duplicates. **Examples** ```python >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] ``` **Returns** The parameters objects used in the circuit. ### parameter\_bounds The parameter bounds for the unbound parameters in the circuit. **Returns** A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If `None` is returned, problem is fully unbounded. ### parameters ### paulis The Pauli strings used in the entanglement of the qubits. **Returns** The Pauli strings as list. ### preferred\_init\_points The initial points for the parameters. Can be stored as initial guess in optimization. **Returns** The initial values for the parameters, or None, if none have been set. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### reps The number of times rotation and entanglement block are repeated. **Returns** The number of repetitions. ### rotation\_blocks The blocks in the rotation layers. **Returns** The blocks in the rotation layers. ## Methods ### pauli\_block Get the Pauli block for the feature map circuit. ### pauli\_evolution Get the evolution block for the given pauli string. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PauliFeatureMap.mdx "--- title: PauliGate description: API reference for qiskit.circuit.library.PauliGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PauliGate --- # PauliGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") A multi-qubit Pauli gate. This gate exists for optimization purposes for the quantum statevector simulation, since applying multiple pauli gates to different qubits at once can be done via a single pass on the statevector. The functionality is equivalent to applying the pauli gates sequentially using standard Qiskit gates. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`pauli()`](qiskit.circuit.QuantumCircuit#pauli ""qiskit.circuit.QuantumCircuit.pauli"") method. Create a new gate. **Parameters** * **name** – The Qobj name of the gate. * **num\_qubits** – The number of qubits the gate acts on. * **params** – A list of parameters. * **label** – An optional label for the gate. ## Attributes ### 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.PauliGate.base_class ""qiskit.circuit.library.PauliGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverted pauli gate (itself). ### validate\_parameter Gate parameters should be int, float, or ParameterExpression ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PauliGate.mdx "--- title: PauliTwoDesign description: API reference for qiskit.circuit.library.PauliTwoDesign in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PauliTwoDesign --- # PauliTwoDesign Bases: [`TwoLocal`](qiskit.circuit.library.TwoLocal ""qiskit.circuit.library.n_local.two_local.TwoLocal"") The Pauli Two-Design ansatz. This class implements a particular form of a 2-design circuit \[1], which is frequently studied in quantum machine learning literature, such as e.g. the investigating of Barren plateaus in variational algorithms \[2]. The circuit consists of alternating rotation and entanglement layers with an initial layer of $\sqrt{H} = RY(\pi/4)$ gates. The rotation layers contain single qubit Pauli rotations, where the axis is chosen uniformly at random to be X, Y or Z. The entanglement layers is compromised of pairwise CZ gates with a total depth of 2. For instance, the circuit could look like this (but note that choosing a different seed yields different Pauli rotations). ```python ┌─────────┐┌──────────┐ ░ ┌──────────┐ ░ ┌──────────┐ q_0: ┤ RY(π/4) ├┤ RZ(θ[0]) ├─■─────░─┤ RY(θ[4]) ├─■─────░──┤ RZ(θ[8]) ├ ├─────────┤├──────────┤ │ ░ ├──────────┤ │ ░ ├──────────┤ q_1: ┤ RY(π/4) ├┤ RZ(θ[1]) ├─■──■──░─┤ RY(θ[5]) ├─■──■──░──┤ RX(θ[9]) ├ ├─────────┤├──────────┤ │ ░ ├──────────┤ │ ░ ┌┴──────────┤ q_2: ┤ RY(π/4) ├┤ RX(θ[2]) ├─■──■──░─┤ RY(θ[6]) ├─■──■──░─┤ RX(θ[10]) ├ ├─────────┤├──────────┤ │ ░ ├──────────┤ │ ░ ├───────────┤ q_3: ┤ RY(π/4) ├┤ RZ(θ[3]) ├─■─────░─┤ RX(θ[7]) ├─■─────░─┤ RY(θ[11]) ├ └─────────┘└──────────┘ ░ └──────────┘ ░ └───────────┘ ``` **Examples** ```python from qiskit.circuit.library import PauliTwoDesign circuit = PauliTwoDesign(4, reps=2, seed=5, insert_barriers=True) circuit.draw('mpl') ``` ![../\_images/qiskit-circuit-library-PauliTwoDesign-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-PauliTwoDesign-1.png) **References** **\[1]: Nakata et al., Unitary 2-designs from random X- and Z-diagonal unitaries.** [arXiv:1502.07514](https://arxiv.org/pdf/1502.07514.pdf) **\[2]: McClean et al., Barren plateaus in quantum neural network training landscapes.** [arXiv:1803.11173](https://arxiv.org/pdf/1803.11173.pdf) **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits of the Pauli Two-Design circuit. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Specifies how often a block consisting of a rotation layer and entanglement layer is repeated. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The seed for randomly choosing the axes of the Pauli rotations. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True`, barriers are inserted in between each layer. If `False`, no barriers are inserted. Defaults to `False`. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### entanglement Get the entanglement strategy. **Returns** The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted. ### entanglement\_blocks The blocks in the entanglement layers. **Returns** The blocks in the entanglement layers. ### flatten Returns whether the circuit is wrapped in nested gates/instructions or flattened. ### global\_phase Return the global phase of the current circuit scope in radians. ### initial\_state Return the initial state that is added in front of the n-local circuit. **Returns** The initial state. ### insert\_barriers If barriers are inserted in between the layers or not. **Returns** `True`, if barriers are inserted in between the layers, `False` if not. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_layers Return the number of layers in the n-local circuit. **Returns** The number of layers in the circuit. ### num\_parameters ### num\_parameters\_settable Return the number of settable parameters. **Returns** The number of possibly distinct parameters. ### num\_qubits Returns the number of qubits in this circuit. **Returns** The number of qubits. ### 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. ### ordered\_parameters The parameters used in the underlying circuit. This includes float values and duplicates. **Examples** ```python >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] ``` **Returns** The parameters objects used in the circuit. ### parameter\_bounds The parameter bounds for the unbound parameters in the circuit. **Returns** A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If `None` is returned, problem is fully unbounded. ### parameters ### preferred\_init\_points The initial points for the parameters. Can be stored as initial guess in optimization. **Returns** The initial values for the parameters, or None, if none have been set. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### reps The number of times rotation and entanglement block are repeated. **Returns** The number of repetitions. ### rotation\_blocks The blocks in the rotation layers. **Returns** The blocks in the rotation layers. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PauliTwoDesign.mdx "--- title: Permutation description: API reference for qiskit.circuit.library.Permutation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.Permutation --- # Permutation Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") An n\_qubit circuit that permutes qubits. Return an n\_qubit permutation circuit implemented using SWAPs. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – circuit width. * **pattern** ([*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)"")*] | np.ndarray | None*) – permutation pattern, describing which qubits occupy the positions 0, 1, 2, etc. after applying the permutation, that is `pattern[k] = m` when the permutation maps qubit `m` to position `k`. As an example, the pattern `[2, 4, 3, 0, 1]` means that qubit `2` goes to position `0`, qubit `4` goes to the position `1`, etc. The pattern can also be `None`, in which case a random permutation over `num_qubits` is created. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – random seed in case a random permutation is requested. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if permutation pattern is malformed. **Reference Circuit:** ![../\_images/qiskit-circuit-library-Permutation-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-Permutation-1.png) **Expanded Circuit:** ![../\_images/qiskit-circuit-library-Permutation-2.png](/images/api/qiskit/1.0/qiskit-circuit-library-Permutation-2.png) ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.Permutation.mdx "--- title: PermutationGate description: API reference for qiskit.circuit.library.PermutationGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PermutationGate --- # PermutationGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") A gate that permutes qubits. Return a permutation gate. **Parameters** **pattern** ([*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)"")*]*) – permutation pattern, describing which qubits occupy the positions 0, 1, 2, etc. after applying the permutation, that is `pattern[k] = m` when the permutation maps qubit `m` to position `k`. As an example, the pattern `[2, 4, 3, 0, 1]` means that qubit `2` goes to position `0`, qubit `4` goes to the position `1`, etc. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if permutation pattern is malformed. **Reference Circuit:** ![../\_images/qiskit-circuit-library-PermutationGate-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-PermutationGate-1.png) **Expanded Circuit:** ![../\_images/qiskit-circuit-library-PermutationGate-2.png](/images/api/qiskit/1.0/qiskit-circuit-library-PermutationGate-2.png) ## Attributes ### 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.PermutationGate.base_class ""qiskit.circuit.library.PermutationGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### pattern Returns the permutation pattern defining this permutation. ### unit Get the time unit of duration. ## Methods ### inverse Returns the inverse of the permutation. ### validate\_parameter Parameter validation. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PermutationGate.mdx "--- title: PhaseEstimation description: API reference for qiskit.circuit.library.PhaseEstimation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PhaseEstimation --- # PhaseEstimation Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Phase Estimation circuit. In the Quantum Phase Estimation (QPE) algorithm \[1, 2, 3], the Phase Estimation circuit is used to estimate the phase $\phi$ of an eigenvalue $e^{2\pi i\phi}$ of a unitary operator $U$, provided with the corresponding eigenstate $|\psi\rangle$. That is $$ U|\psi\rangle = e^{2\pi i\phi} |\psi\rangle $$ This estimation (and thereby this circuit) is a central routine to several well-known algorithms, such as Shor’s algorithm or Quantum Amplitude Estimation. **References:** **\[1]: Kitaev, A. Y. (1995). Quantum measurements and the Abelian Stabilizer Problem. 1–22.** [quant-ph/9511026](http://arxiv.org/abs/quant-ph/9511026) **\[2]: Michael A. Nielsen and Isaac L. Chuang. 2011.** Quantum Computation and Quantum Information: 10th Anniversary Edition (10th ed.). Cambridge University Press, New York, NY, USA. **\[3]: Qiskit** [textbook](https://github.com/Qiskit/textbook/blob/main/notebooks/ch-algorithms/quantum-phase-estimation.ipynb) **Parameters** * **num\_evaluation\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of evaluation qubits. * **unitary** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")) – The unitary operation $U$ which will be repeated and controlled. * **iqft** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") *| None*) – A inverse Quantum Fourier Transform, per default the inverse of [`QFT`](qiskit.circuit.library.QFT ""qiskit.circuit.library.QFT"") is used. Note that the QFT should not include the usual swaps! * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit. The inverse QFT should not include a swap of the qubit order. **Reference Circuit:** ![../\_images/qiskit-circuit-library-PhaseEstimation-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-PhaseEstimation-1.png) ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PhaseEstimation.mdx "--- title: PhaseGate description: API reference for qiskit.circuit.library.PhaseGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PhaseGate --- # PhaseGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Single-qubit rotation about the Z axis. This is a diagonal gate. It can be implemented virtually in hardware via framechanges (i.e. at zero error and duration). Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`p()`](qiskit.circuit.QuantumCircuit#p ""qiskit.circuit.QuantumCircuit.p"") method. **Circuit symbol:** ```python ┌──────┐ q_0: ┤ P(λ) ├ └──────┘ ``` **Matrix Representation:** $$ P(\lambda) = \begin{pmatrix} 1 & 0 \\ 0 & e^{i\lambda} \end{pmatrix} $$ **Examples:** > $$ > P(\lambda = \pi) = Z > $$ > > $$ > P(\lambda = \pi/2) = S > $$ > > $$ > P(\lambda = \pi/4) = T > $$ `RZGate`: This gate is equivalent to RZ up to a phase factor. > $$ > P(\lambda) = e^{i{\lambda}/2} RZ(\lambda) > $$ Reference for virtual Z gate implementation: [1612.00858](https://arxiv.org/abs/1612.00858) Create new Phase gate. ## Attributes ### 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.PhaseGate.base_class ""qiskit.circuit.library.PhaseGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-Phase 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"") ### inverse Return inverted Phase gate ($Phase(\lambda)^{\dagger} = Phase(-\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 another `PGate` with an inverse parameter value. **Returns** inverse gate. **Return type** PGate ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PhaseGate.mdx "--- title: PhaseOracle description: API reference for qiskit.circuit.library.PhaseOracle in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PhaseOracle --- # PhaseOracle Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Phase Oracle. The Phase Oracle object constructs circuits for any arbitrary input logical expressions. A logical expression is composed of logical operators & (AND), | (OR), \~ (NOT), and ^ (XOR). as well as symbols for literals (variables). For example, ‘a & b’, and (v0 | \~v1) & (\~v2 & v3) are both valid string representation of boolean logical expressions. For convenience, this oracle, in addition to parsing arbitrary logical expressions, also supports input strings in the [DIMACS CNF format](http://www.satcompetition.org/2009/format-benchmarks2009.html), which is the standard format for specifying SATisfiability (SAT) problem instances in [Conjunctive Normal Form (CNF)](https://en.wikipedia.org/wiki/Conjunctive_normal_form), which is a conjunction of one or more clauses, where a clause is a disjunction of one or more literals. See `qiskit.circuit.library.phase_oracle.PhaseOracle.from_dimacs_file()`. From 16 variables on, possible performance issues should be expected when using the default synthesizer. Creates a PhaseOracle object **Parameters** * **expression** (*Union\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, ClassicalElement]*) – A Python-like boolean expression. * **synthesizer** (*Optional\[Callable\[\[*[*BooleanExpression*](qiskit.circuit.classicalfunction.BooleanExpression ""qiskit.circuit.classicalfunction.BooleanExpression"")*],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]]*) – Optional. A function to convert a BooleanExpression into a QuantumCircuit If None is provided, Tweedledum’s pkrm\_synth with phase\_esop will 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 ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ## Methods ### evaluate\_bitstring Evaluate the oracle on a bitstring. This evaluation is done classically without any quantum circuit. **Parameters** **bitstring** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The bitstring for which to evaluate. The input bitstring is expected to be in little-endian order. **Returns** True if the bitstring is a good state, False otherwise. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### from\_dimacs\_file Create a PhaseOracle from the string in the DIMACS format. It is possible to build a PhaseOracle from a file in [DIMACS CNF format](http://www.satcompetition.org/2009/format-benchmarks2009.html), which is the standard format for specifying SATisfiability (SAT) problem instances in [Conjunctive Normal Form (CNF)](https://en.wikipedia.org/wiki/Conjunctive_normal_form), which is a conjunction of one or more clauses, where a clause is a disjunction of one or more literals. The following is an example of a CNF expressed in the DIMACS format: ```python c DIMACS CNF file with 3 satisfying assignments: 1 -2 3, -1 -2 -3, 1 2 -3. p cnf 3 5 -1 -2 -3 0 1 -2 3 0 1 2 -3 0 1 -2 -3 0 -1 2 3 0 ``` The first line, following the c character, is a comment. The second line specifies that the CNF is over three boolean variables — let us call them $x_1, x_2, x_3$, and contains five clauses. The five clauses, listed afterwards, are implicitly joined by the logical AND operator, $\land$, while the variables in each clause, represented by their indices, are implicitly disjoined by the logical OR operator, $lor$. The $-$ symbol preceding a boolean variable index corresponds to the logical NOT operator, $lnot$. Character 0 (zero) marks the end of each clause. Essentially, the code above corresponds to the following CNF: $(\lnot x_1 \lor \lnot x_2 \lor \lnot x_3) \land (x_1 \lor \lnot x_2 \lor x_3) \land (x_1 \lor x_2 \lor \lnot x_3) \land (x_1 \lor \lnot x_2 \lor \lnot x_3) \land (\lnot x_1 \lor x_2 \lor x_3)$. **Parameters** **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A file in DIMACS format. **Returns** A quantum circuit with a phase oracle. **Return type** [PhaseOracle](#qiskit.circuit.library.PhaseOracle ""qiskit.circuit.library.PhaseOracle"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PhaseOracle.mdx "--- title: PiecewiseChebyshev description: API reference for qiskit.circuit.library.PiecewiseChebyshev in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PiecewiseChebyshev --- # PiecewiseChebyshev Bases: `BlueprintCircuit` Piecewise Chebyshev approximation to an input function. For a given function $f(x)$ and degree $d$, this class implements a piecewise polynomial Chebyshev approximation on $n$ qubits to $f(x)$ on the given intervals. All the polynomials in the approximation are of degree $d$. The values of the parameters are calculated according to \[1] and see \[2] for a more detailed explanation of the circuit construction and how it acts on the qubits. **Examples** ```python import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2 pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits) pw_approximation._build() qc = QuantumCircuit(pw_approximation.num_qubits) qc.h(list(range(num_state_qubits))) qc.append(pw_approximation.to_instruction(), qc.qubits) qc.draw(output='mpl') ``` ![../\_images/qiskit-circuit-library-PiecewiseChebyshev-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-PiecewiseChebyshev-1.png) **References** **\[1]: Haener, T., Roetteler, M., & Svore, K. M. (2018).** Optimizing Quantum Circuits for Arithmetic. [arXiv:1805.12445](http://arxiv.org/abs/1805.12445) **\[2]: Carrera Vazquez, A., Hiptmair, H., & Woerner, S. (2022).** Enhancing the Quantum Linear Systems Algorithm Using Richardson Extrapolation. [ACM Transactions on Quantum Computing 3, 1, Article 2](https://doi.org/10.1145/3490631) **Parameters** * **f\_x** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| Callable\[\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*],* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – the function to be approximated. Constant functions should be specified as f\_x = constant. * **degree** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – the degree of the polynomials. Defaults to `1`. * **breakpoints** ([*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*) – the breakpoints to define the piecewise-linear function. Defaults to the full interval. * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – number of qubits representing the state. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit object. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### breakpoints The breakpoints for the piecewise approximation. **Returns** The breakpoints for the piecewise approximation. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### degree The degree of the polynomials. **Returns** The degree of the polynomials. ### f\_x The function to be approximated. **Returns** The function to be approximated. ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters ### num\_qubits Return number of qubits. ### num\_state\_qubits The number of state qubits representing the state $|x\rangle$. **Returns** The number of state qubits. ### 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. ### parameters ### polynomials The polynomials for the piecewise approximation. **Returns** The polynomials for the piecewise approximation. **Raises** [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – If the input function is not in the correct format. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PiecewiseChebyshev.mdx "--- title: PiecewiseLinearPauliRotations description: API reference for qiskit.circuit.library.PiecewiseLinearPauliRotations in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PiecewiseLinearPauliRotations --- # PiecewiseLinearPauliRotations Bases: [`FunctionalPauliRotations`](qiskit.circuit.library.FunctionalPauliRotations ""qiskit.circuit.library.arithmetic.functional_pauli_rotations.FunctionalPauliRotations"") Piecewise-linearly-controlled Pauli rotations. For a piecewise linear (not necessarily continuous) function $f(x)$, which is defined through breakpoints, slopes and offsets as follows. Suppose the breakpoints $(x_0, ..., x_J)$ are a subset of $[0, 2^n-1]$, where $n$ is the number of state qubits. Further on, denote the corresponding slopes and offsets by $a_j$ and $b_j$ respectively. Then f(x) is defined as: $$ f(x) = \begin{cases} 0, x < x_0 \\ a_j (x - x_j) + b_j, x_j \leq x < x_{j+1} \end{cases} $$ where we implicitly assume $x_{J+1} = 2^n$. Construct piecewise-linearly-controlled Pauli rotations. **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits representing the state. * **breakpoints** ([*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*) – The breakpoints to define the piecewise-linear function. Defaults to `[0]`. * **slopes** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | np.ndarray | None*) – The slopes for different segments of the piecewise-linear function. Defaults to `[1]`. * **offsets** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | np.ndarray | None*) – The offsets for different segments of the piecewise-linear function. Defaults to `[0]`. * **basis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The type of Pauli rotation (`'X'`, `'Y'`, `'Z'`). * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### basis The kind of Pauli rotation to be used. Set the basis to ‘X’, ‘Y’ or ‘Z’ for controlled-X, -Y, or -Z rotations respectively. **Returns** The kind of Pauli rotation used in controlled rotation. ### breakpoints The breakpoints of the piecewise linear function. The function is linear in the intervals `[point_i, point_{i+1}]` where the last point implicitly is `2**(num_state_qubits + 1)`. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### contains\_zero\_breakpoint Whether 0 is the first breakpoint. **Returns** True, if 0 is the first breakpoint, otherwise False. ### data ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### mapped\_offsets The offsets mapped to the internal representation. **Returns** The mapped offsets. ### mapped\_slopes The slopes mapped to the internal representation. **Returns** The mapped slopes. ### 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. ### num\_ancilla\_qubits The minimum number of ancilla qubits in the circuit. **Returns** The minimal number of ancillas required. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters ### num\_qubits Return number of qubits. ### num\_state\_qubits The number of state qubits representing the state $|x\rangle$. **Returns** The number of state qubits. ### offsets The breakpoints of the piecewise linear function. The function is linear in the intervals `[point_i, point_{i+1}]` where the last point implicitly is `2**(num_state_qubits + 1)`. ### 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. ### parameters ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### slopes The breakpoints of the piecewise linear function. The function is linear in the intervals `[point_i, point_{i+1}]` where the last point implicitly is `2**(num_state_qubits + 1)`. ## Methods ### evaluate Classically evaluate the piecewise linear rotation. **Parameters** **x** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Value to be evaluated at. **Returns** Value of piecewise linear function at x. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PiecewiseLinearPauliRotations.mdx "--- title: PiecewisePolynomialPauliRotations description: API reference for qiskit.circuit.library.PiecewisePolynomialPauliRotations in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PiecewisePolynomialPauliRotations --- # PiecewisePolynomialPauliRotations Bases: [`FunctionalPauliRotations`](qiskit.circuit.library.FunctionalPauliRotations ""qiskit.circuit.library.arithmetic.functional_pauli_rotations.FunctionalPauliRotations"") Piecewise-polynomially-controlled Pauli rotations. This class implements a piecewise polynomial (not necessarily continuous) function, $f(x)$, on qubit amplitudes, which is defined through breakpoints and coefficients as follows. Suppose the breakpoints $(x_0, ..., x_J)$ are a subset of $[0, 2^n-1]$, where $n$ is the number of state qubits. Further on, denote the corresponding coefficients by $[a_{j,1},...,a_{j,d}]$, where $d$ is the highest degree among all polynomials. Then $f(x)$ is defined as: $$ f(x) = \begin{cases} 0, x < x_0 \\ \sum_{i=0}^{i=d}a_{j,i}/2 x^i, x_j \leq x < x_{j+1} \end{cases} $$ where if given the same number of breakpoints as polynomials, we implicitly assume $x_{J+1} = 2^n$. Note the $1/2$ factor in the coefficients of $f(x)$, this is consistent with Qiskit’s Pauli rotations. **Examples** ```python >>> from qiskit import QuantumCircuit >>> from qiskit.circuit.library.arithmetic.piecewise_polynomial_pauli_rotations import\ ... PiecewisePolynomialPauliRotations >>> qubits, breakpoints, coeffs = (2, [0, 2], [[0, -1.2],[-1, 1, 3]]) >>> poly_r = PiecewisePolynomialPauliRotations(num_state_qubits=qubits, ...breakpoints=breakpoints, coeffs=coeffs) >>> >>> qc = QuantumCircuit(poly_r.num_qubits) >>> qc.h(list(range(qubits))); >>> qc.append(poly_r.to_instruction(), list(range(qc.num_qubits))); >>> qc.draw() ┌───┐┌──────────┐ q_0: ┤ H ├┤0 ├ ├───┤│ │ q_1: ┤ H ├┤1 ├ └───┘│ │ q_2: ─────┤2 ├ │ pw_poly │ q_3: ─────┤3 ├ │ │ q_4: ─────┤4 ├ │ │ q_5: ─────┤5 ├ └──────────┘ ``` **References** **\[1]: Haener, T., Roetteler, M., & Svore, K. M. (2018).** Optimizing Quantum Circuits for Arithmetic. [arXiv:1805.12445](http://arxiv.org/abs/1805.12445) **\[2]: Carrera Vazquez, A., Hiptmair, R., & Woerner, S. (2022).** Enhancing the Quantum Linear Systems Algorithm using Richardson Extrapolation. [ACM Transactions on Quantum Computing 3, 1, Article 2](https://doi.org/10.1145/3490631) **Parameters** * **num\_state\_qubits** (*Optional\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The number of qubits representing the state. * **breakpoints** (*Optional\[List\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – The breakpoints to define the piecewise-linear function. Defaults to `[0]`. * **coeffs** (*Optional\[List\[List\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]]]*) – The coefficients of the polynomials for different segments of the * **x** (*piecewise-linear function. coeffs\[j]\[i] is the coefficient of the i-th power of*) – * **polynomial.** (*for the j-th*) – Defaults to linear: `[[1]]`. * **basis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The type of Pauli rotation (`'X'`, `'Y'`, `'Z'`). * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### basis The kind of Pauli rotation to be used. Set the basis to ‘X’, ‘Y’ or ‘Z’ for controlled-X, -Y, or -Z rotations respectively. **Returns** The kind of Pauli rotation used in controlled rotation. ### breakpoints The breakpoints of the piecewise polynomial function. The function is polynomial in the intervals `[point_i, point_{i+1}]` where the last point implicitly is `2**(num_state_qubits + 1)`. **Returns** The list of breakpoints. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### coeffs The coefficients of the polynomials. **Returns** The polynomial coefficients per interval as nested lists. ### contains\_zero\_breakpoint Whether 0 is the first breakpoint. **Returns** True, if 0 is the first breakpoint, otherwise False. ### data ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### mapped\_coeffs The coefficients mapped to the internal representation, since we only compare x>=breakpoint. **Returns** The mapped coefficients. ### 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. ### num\_ancilla\_qubits The minimum number of ancilla qubits in the circuit. **Returns** The minimal number of ancillas required. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters ### num\_qubits Return number of qubits. ### num\_state\_qubits The number of state qubits representing the state $|x\rangle$. **Returns** The number of state qubits. ### 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. ### parameters ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ## Methods ### evaluate Classically evaluate the piecewise polynomial rotation. **Parameters** **x** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Value to be evaluated at. **Returns** Value of piecewise polynomial function at x. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PiecewisePolynomialPauliRotations.mdx "--- title: PolynomialPauliRotations description: API reference for qiskit.circuit.library.PolynomialPauliRotations in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.PolynomialPauliRotations --- # PolynomialPauliRotations Bases: [`FunctionalPauliRotations`](qiskit.circuit.library.FunctionalPauliRotations ""qiskit.circuit.library.arithmetic.functional_pauli_rotations.FunctionalPauliRotations"") A circuit implementing polynomial Pauli rotations. For a polynomial $p(x)$, a basis state $|i\rangle$ and a target qubit $|0\rangle$ this operator acts as: $$ |i\rangle |0\rangle \mapsto \cos\left(\frac{p(i)}{2}\right) |i\rangle |0\rangle + \sin\left(\frac{p(i)}{2}\right) |i\rangle |1\rangle $$ Let n be the number of qubits representing the state, d the degree of p(x) and q\_i the qubits, where q\_0 is the least significant qubit. Then for $$ x = \sum_{i=0}^{n-1} 2^i q_i, $$ we can write $$ p(x) = \sum_{j=0}^{j=d} c_j x^j $$ where $c$ are the input coefficients, `coeffs`. Prepare an approximation to a state with amplitudes specified by a polynomial. **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits representing the state. * **coeffs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None*) – The coefficients of the polynomial. `coeffs[i]` is the coefficient of the i-th power of x. Defaults to linear: \[0, 1]. * **basis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The type of Pauli rotation (‘X’, ‘Y’, ‘Z’). * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### basis The kind of Pauli rotation to be used. Set the basis to ‘X’, ‘Y’ or ‘Z’ for controlled-X, -Y, or -Z rotations respectively. **Returns** The kind of Pauli rotation used in controlled rotation. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### coeffs The coefficients of the polynomial. `coeffs[i]` is the coefficient of the i-th power of the function input $x$, that means that the rotation angles are based on the coefficients value, following the formula $$ c_j x^j , j=0, ..., d $$ where $d$ is the degree of the polynomial $p(x)$ and $c$ are the coefficients `coeffs`. **Returns** The coefficients of the polynomial. ### data ### degree Return the degree of the polynomial, equals to the number of coefficients minus 1. **Returns** The degree of the polynomial. If the coefficients have not been set, return 0. ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancilla\_qubits The minimum number of ancilla qubits in the circuit. **Returns** The minimal number of ancillas required. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters ### num\_qubits Return number of qubits. ### num\_state\_qubits The number of state qubits representing the state $|x\rangle$. **Returns** The number of state qubits. ### 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. ### parameters ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.PolynomialPauliRotations.mdx "--- title: QAOAAnsatz description: API reference for qiskit.circuit.library.QAOAAnsatz in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.QAOAAnsatz --- # QAOAAnsatz Bases: [`EvolvedOperatorAnsatz`](qiskit.circuit.library.EvolvedOperatorAnsatz ""qiskit.circuit.library.n_local.evolved_operator_ansatz.EvolvedOperatorAnsatz"") A generalized QAOA quantum circuit with a support of custom initial states and mixers. **References** **\[1]: Farhi et al., A Quantum Approximate Optimization Algorithm.** [arXiv:1411.4028](https://arxiv.org/pdf/1411.4028) **Parameters** * **cost\_operator** (*BaseOperator or OperatorBase, optional*) – The operator representing the cost of the optimization problem, denoted as $U(C, \gamma)$ in the original paper. Must be set either in the constructor or via property setter. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The integer parameter p, which determines the depth of the circuit, as specified in the original paper, default is 1. * **initial\_state** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*, optional*) – An optional initial state to use. If None is passed then a set of Hadamard gates is applied as an initial state to all qubits. * **mixer\_operator** (*BaseOperator or OperatorBase or* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*, optional*) – An optional custom mixer to use instead of the global X-rotations, denoted as $U(B, \beta)$ in the original paper. Can be an operator or an optionally parameterized quantum circuit. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A name of the circuit, default ‘qaoa’ * **flatten** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – Set this to `True` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you’re using this circuit for anything besides visualization its **strongly** recommended to set this flag to `True` to avoid a large performance overhead for parameter binding. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### cost\_operator Returns an operator representing the cost of the optimization problem. **Returns** cost operator. **Return type** BaseOperator or OperatorBase ### data ### entanglement Get the entanglement strategy. **Returns** The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted. ### entanglement\_blocks The blocks in the entanglement layers. **Returns** The blocks in the entanglement layers. ### evolution The evolution converter used to compute the evolution. **Returns** The evolution converter used to compute the evolution. **Return type** [EvolutionSynthesis](qiskit.synthesis.EvolutionSynthesis ""qiskit.synthesis.EvolutionSynthesis"") ### flatten Returns whether the circuit is wrapped in nested gates/instructions or flattened. ### global\_phase Return the global phase of the current circuit scope in radians. ### initial\_state Returns an optional initial state as a circuit ### insert\_barriers If barriers are inserted in between the layers or not. **Returns** `True`, if barriers are inserted in between the layers, `False` if not. ### instances ### 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. ### 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. ### mixer\_operator Returns an optional mixer operator expressed as an operator or a quantum circuit. **Returns** mixer operator or circuit. **Return type** BaseOperator or OperatorBase or [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""), optional ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_layers Return the number of layers in the n-local circuit. **Returns** The number of layers in the circuit. ### num\_parameters ### num\_parameters\_settable The number of total parameters that can be set to distinct values. This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from `num_parameters` which counts the number of unique [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") objects currently in the circuit. **Returns** The number of parameters originally available in the circuit. This quantity does not require the circuit to be built yet. ### num\_qubits ### 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. ### operators The operators that are evolved in this circuit. **Returns** **The operators to be evolved** (and circuits) in this ansatz. **Return type** List\[Union\[BaseOperator, OperatorBase, [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")]] ### ordered\_parameters The parameters used in the underlying circuit. This includes float values and duplicates. **Examples** ```python >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] ``` **Returns** The parameters objects used in the circuit. ### parameter\_bounds The parameter bounds for the unbound parameters in the circuit. **Returns** A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If None is returned, problem is fully unbounded. ### parameters ### preferred\_init\_points Getter of preferred initial points based on the given initial state. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### reps Returns the reps parameter, which determines the depth of the circuit. ### rotation\_blocks The blocks in the rotation layers. **Returns** The blocks in the rotation layers. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.QAOAAnsatz.mdx "--- title: QFT description: API reference for qiskit.circuit.library.QFT in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.QFT --- # QFT Bases: `BlueprintCircuit` Quantum Fourier Transform Circuit. The Quantum Fourier Transform (QFT) on $n$ qubits is the operation $$ |j\rangle \mapsto \frac{1}{2^{n/2}} \sum_{k=0}^{2^n - 1} e^{2\pi ijk / 2^n} |k\rangle $$ The circuit that implements this transformation can be implemented using Hadamard gates on each qubit, a series of controlled-U1 (or Z, depending on the phase) gates and a layer of Swap gates. The layer of Swap gates can in principle be dropped if the QFT appears at the end of the circuit, since then the re-ordering can be done classically. They can be turned off using the `do_swaps` attribute. For 4 qubits, the circuit that implements this transformation is: ![../\_images/qiskit-circuit-library-QFT-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-QFT-1.png) The inverse QFT can be obtained by calling the `inverse` method on this class. The respective circuit diagram is: ![../\_images/qiskit-circuit-library-QFT-2.png](/images/api/qiskit/1.0/qiskit-circuit-library-QFT-2.png) One method to reduce circuit depth is to implement the QFT approximately by ignoring controlled-phase rotations where the angle is beneath a threshold. This is discussed in more detail in [https://arxiv.org/abs/quant-ph/9601018](https://arxiv.org/abs/quant-ph/9601018) or [https://arxiv.org/abs/quant-ph/0403071](https://arxiv.org/abs/quant-ph/0403071). Here, this can be adjusted using the `approximation_degree` attribute: the smallest `approximation_degree` rotation angles are dropped from the QFT. For instance, a QFT on 5 qubits with approximation degree 2 yields (the barriers are dropped in this example): ![../\_images/qiskit-circuit-library-QFT-3.png](/images/api/qiskit/1.0/qiskit-circuit-library-QFT-3.png) Construct a new QFT circuit. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits on which the QFT acts. * **approximation\_degree** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The degree of approximation (0 for no approximation). * **do\_swaps** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to include the final swaps in the QFT. * **inverse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, the inverse Fourier transform is constructed. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, barriers are inserted as visualization improvement. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The name of the circuit. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### approximation\_degree The approximation degree of the QFT. **Returns** The currently set approximation degree. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### do\_swaps Whether the final swaps of the QFT are applied or not. **Returns** True, if the final swaps are applied, False if not. ### global\_phase Return the global phase of the current circuit scope in radians. ### insert\_barriers Whether barriers are inserted for better visualization or not. **Returns** True, if barriers are inserted, False if not. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters ### num\_qubits The number of qubits in the QFT circuit. **Returns** The number of qubits in the circuit. ### 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. ### parameters ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ## Methods ### inverse Invert this circuit. **Parameters** **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the inverse gate can be implemented as an annotated gate. The value of this argument is ignored as the inverse of a QFT is an IQFT which is just another instance of [`QFT`](#qiskit.circuit.library.QFT ""qiskit.circuit.library.QFT""). **Returns** The inverted circuit. **Return type** [*QFT*](#qiskit.circuit.library.QFT ""qiskit.circuit.library.basis_change.qft.QFT"") ### is\_inverse Whether the inverse Fourier transform is implemented. **Returns** True, if the inverse Fourier transform is implemented, False otherwise. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.QFT.mdx "--- title: QuadraticForm description: API reference for qiskit.circuit.library.QuadraticForm in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.QuadraticForm --- # QuadraticForm Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Implements a quadratic form on binary variables encoded in qubit registers. A quadratic form on binary variables is a quadratic function $Q$ acting on a binary variable of $n$ bits, $x = x_0 ... x_{n-1}$. For an integer matrix $A$, an integer vector $b$ and an integer $c$ the function can be written as $$ Q(x) = x^T A x + x^T b + c $$ If $A$, $b$ or $c$ contain scalar values, this circuit computes only an approximation of the quadratic form. Provided with $m$ qubits to encode the value, this circuit computes $Q(x) \mod 2^m$ in \[two’s complement]\([https://stackoverflow.com/questions/1049722/what-is-2s-complement](https://stackoverflow.com/questions/1049722/what-is-2s-complement)) representation. $$ |x\rangle_n |0\rangle_m \mapsto |x\rangle_n |(Q(x) + 2^m) \mod 2^m \rangle_m $$ Since we use two’s complement e.g. the value of $Q(x) = 3$ requires 2 bits to represent the value and 1 bit for the sign: 3 = ‘011’ where the first 0 indicates a positive value. On the other hand, $Q(x) = -3$ would be -3 = ‘101’, where the first 1 indicates a negative value and 01 is the two’s complement of 3. If the value of $Q(x)$ is too large to be represented with m qubits, the resulting bitstring is $(Q(x) + 2^m) \mod 2^m)$. The implementation of this circuit is discussed in \[1], Fig. 6. **References** **\[1]: Gilliam et al., Grover Adaptive Search for Constrained Polynomial Binary Optimization.** [arXiv:1912.04088](https://arxiv.org/pdf/1912.04088.pdf) **Parameters** * **num\_result\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits to encode the result. Called $m$ in the class documentation. * **quadratic** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"")*]] | None*) – A matrix containing the quadratic coefficients, $A$. * **linear** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"") *|*[*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)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"")*] | None*) – An array containing the linear coefficients, $b$. * **offset** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *| None*) – A constant offset, $c$. * **little\_endian** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Encode the result in little endianness. **Raises** * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If `linear` and `quadratic` have mismatching sizes. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If `num_result_qubits` is unspecified but cannot be determined because some values of the quadratic form are parameterized. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ## Methods ### required\_result\_qubits Get the number of required result qubits. **Parameters** * **quadratic** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"") *|*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]]*) – A matrix containing the quadratic coefficients. * **linear** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"") *|*[*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)"")*]*) – An array containing the linear coefficients. * **offset** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – A constant offset. **Returns** The number of qubits needed to represent the value of the quadratic form in twos complement. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.QuadraticForm.mdx "--- title: QuantumVolume description: API reference for qiskit.circuit.library.QuantumVolume in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.QuantumVolume --- # QuantumVolume Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") A quantum volume model circuit. The model circuits are random instances of circuits used to measure the Quantum Volume metric, as introduced in \[1]. The model circuits consist of layers of Haar random elements of SU(4) applied between corresponding pairs of qubits in a random bipartition. **Reference Circuit:** ![../\_images/qiskit-circuit-library-QuantumVolume-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-QuantumVolume-1.png) **Expanded Circuit:** ![../\_images/qiskit-circuit-library-QuantumVolume-2.png](/images/api/qiskit/1.0/qiskit-circuit-library-QuantumVolume-2.png) **References:** \[1] A. Cross et al. Validating quantum computers using randomized model circuits, Phys. Rev. A 100, 032328 (2019). \[[arXiv:1811.12926](https://arxiv.org/abs/1811.12926)] Create quantum volume model circuit of size num\_qubits x depth. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of active qubits in model circuit. * **depth** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – layers of SU(4) operations in model circuit. * **seed** ([*Generator*](https://numpy.org/doc/stable/reference/random/generator.html#numpy.random.Generator ""(in NumPy v1.26)"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Random number generator or generator seed. * **classical\_permutation** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – use classical permutations at every layer, rather than quantum. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.QuantumVolume.mdx "--- title: RC3XGate description: API reference for qiskit.circuit.library.RC3XGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RC3XGate --- # RC3XGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") The simplified 3-controlled Toffoli gate. The simplified Toffoli gate implements the Toffoli gate up to relative phases. Note, that the simplified Toffoli is not equivalent to the Toffoli. But can be used in places where the Toffoli gate is uncomputed again. This concrete implementation is from [https://arxiv.org/abs/1508.03273](https://arxiv.org/abs/1508.03273), the complete circuit of Fig. 4. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`rcccx()`](qiskit.circuit.QuantumCircuit#rcccx ""qiskit.circuit.QuantumCircuit.rcccx"") method. Create a new RC3X gate. ## Attributes ### 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.RC3XGate.base_class ""qiskit.circuit.library.RC3XGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RC3XGate.mdx "--- title: RCCXGate description: API reference for qiskit.circuit.library.RCCXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RCCXGate --- # RCCXGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") The simplified Toffoli gate, also referred to as Margolus gate. The simplified Toffoli gate implements the Toffoli gate up to relative phases. This implementation requires three CX gates which is the minimal amount possible, as shown in [https://arxiv.org/abs/quant-ph/0312225](https://arxiv.org/abs/quant-ph/0312225). Note, that the simplified Toffoli is not equivalent to the Toffoli. But can be used in places where the Toffoli gate is uncomputed again. This concrete implementation is from [https://arxiv.org/abs/1508.03273](https://arxiv.org/abs/1508.03273), the dashed box of Fig. 3. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`rccx()`](qiskit.circuit.QuantumCircuit#rccx ""qiskit.circuit.QuantumCircuit.rccx"") method. Create a new simplified CCX gate. ## Attributes ### 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.RCCXGate.base_class ""qiskit.circuit.library.RCCXGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RCCXGate.mdx "--- title: RealAmplitudes description: API reference for qiskit.circuit.library.RealAmplitudes in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RealAmplitudes --- # RealAmplitudes Bases: [`TwoLocal`](qiskit.circuit.library.TwoLocal ""qiskit.circuit.library.n_local.two_local.TwoLocal"") The real-amplitudes 2-local circuit. The `RealAmplitudes` circuit is a heuristic trial wave function used as Ansatz in chemistry applications or classification circuits in machine learning. The circuit consists of alternating layers of $Y$ rotations and $CX$ entanglements. The entanglement pattern can be user-defined or selected from a predefined set. It is called `RealAmplitudes` since the prepared quantum states will only have real amplitudes, the complex part is always 0. For example a `RealAmplitudes` circuit with 2 repetitions on 3 qubits with `'reverse_linear'` entanglement is ```python ┌──────────┐ ░ ░ ┌──────────┐ ░ ░ ┌──────────┐ ┤ Ry(θ[0]) ├─░────────■───░─┤ Ry(θ[3]) ├─░────────■───░─┤ Ry(θ[6]) ├ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ ┤ Ry(θ[1]) ├─░───■──┤ X ├─░─┤ Ry(θ[4]) ├─░───■──┤ X ├─░─┤ Ry(θ[7]) ├ ├──────────┤ ░ ┌─┴─┐└───┘ ░ ├──────────┤ ░ ┌─┴─┐└───┘ ░ ├──────────┤ ┤ Ry(θ[2]) ├─░─┤ X ├──────░─┤ Ry(θ[5]) ├─░─┤ X ├──────░─┤ Ry(θ[8]) ├ └──────────┘ ░ └───┘ ░ └──────────┘ ░ └───┘ ░ └──────────┘ ``` The entanglement can be set using the `entanglement` keyword as string or a list of index-pairs. See the documentation of [`TwoLocal`](qiskit.circuit.library.TwoLocal ""qiskit.circuit.library.TwoLocal"") and `NLocal` for more detail. Additional options that can be set include the number of repetitions, skipping rotation gates on qubits that are not entangled, leaving out the final rotation layer and inserting barriers in between the rotation and entanglement layers. If some qubits are not entangled with other qubits it makes sense to not apply rotation gates on these qubits, since a sequence of $Y$ rotations can be reduced to a single $Y$ rotation with summed rotation angles. **Examples** ```python >>> ansatz = RealAmplitudes(3, reps=2) # create the circuit on 3 qubits >>> print(ansatz) ┌──────────┐ ┌──────────┐ ┌──────────┐ q_0: ┤ Ry(θ[0]) ├──────────■──────┤ Ry(θ[3]) ├──────────■──────┤ Ry(θ[6]) ├ ├──────────┤ ┌─┴─┐ ├──────────┤ ┌─┴─┐ ├──────────┤ q_1: ┤ Ry(θ[1]) ├──■─────┤ X ├────┤ Ry(θ[4]) ├──■─────┤ X ├────┤ Ry(θ[7]) ├ ├──────────┤┌─┴─┐┌──┴───┴───┐└──────────┘┌─┴─┐┌──┴───┴───┐└──────────┘ q_2: ┤ Ry(θ[2]) ├┤ X ├┤ Ry(θ[5]) ├────────────┤ X ├┤ Ry(θ[8]) ├──────────── └──────────┘└───┘└──────────┘ └───┘└──────────┘ ``` ```python >>> ansatz = RealAmplitudes(3, entanglement='full', reps=2) # it is the same unitary as above >>> print(ansatz) ┌──────────┐ ┌──────────┐ ┌──────────┐ q_0: ┤ RY(θ[0]) ├──■────■──┤ RY(θ[3]) ├──────────────■────■──┤ RY(θ[6]) ├──────────── ├──────────┤┌─┴─┐ │ └──────────┘┌──────────┐┌─┴─┐ │ └──────────┘┌──────────┐ q_1: ┤ RY(θ[1]) ├┤ X ├──┼───────■──────┤ RY(θ[4]) ├┤ X ├──┼───────■──────┤ RY(θ[7]) ├ ├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤ q_2: ┤ RY(θ[2]) ├─────┤ X ├───┤ X ├────┤ RY(θ[5]) ├─────┤ X ├───┤ X ├────┤ RY(θ[8]) ├ └──────────┘ └───┘ └───┘ └──────────┘ └───┘ └───┘ └──────────┘ ``` ```python >>> ansatz = RealAmplitudes(3, entanglement='linear', reps=2, insert_barriers=True) >>> qc = QuantumCircuit(3) # create a circuit and append the RY variational form >>> qc.compose(ansatz, inplace=True) >>> qc.draw() ┌──────────┐ ░ ░ ┌──────────┐ ░ ░ ┌──────────┐ q_0: ┤ RY(θ[0]) ├─░───■────────░─┤ RY(θ[3]) ├─░───■────────░─┤ RY(θ[6]) ├ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ q_1: ┤ RY(θ[1]) ├─░─┤ X ├──■───░─┤ RY(θ[4]) ├─░─┤ X ├──■───░─┤ RY(θ[7]) ├ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ q_2: ┤ RY(θ[2]) ├─░──────┤ X ├─░─┤ RY(θ[5]) ├─░──────┤ X ├─░─┤ RY(θ[8]) ├ └──────────┘ ░ └───┘ ░ └──────────┘ ░ └───┘ ░ └──────────┘ ``` ```python >>> ansatz = RealAmplitudes(4, reps=1, entanglement='circular', insert_barriers=True) >>> print(ansatz) ┌──────────┐ ░ ┌───┐ ░ ┌──────────┐ q_0: ┤ RY(θ[0]) ├─░─┤ X ├──■─────────────░─┤ RY(θ[4]) ├ ├──────────┤ ░ └─┬─┘┌─┴─┐ ░ ├──────────┤ q_1: ┤ RY(θ[1]) ├─░───┼──┤ X ├──■────────░─┤ RY(θ[5]) ├ ├──────────┤ ░ │ └───┘┌─┴─┐ ░ ├──────────┤ q_2: ┤ RY(θ[2]) ├─░───┼───────┤ X ├──■───░─┤ RY(θ[6]) ├ ├──────────┤ ░ │ └───┘┌─┴─┐ ░ ├──────────┤ q_3: ┤ RY(θ[3]) ├─░───■────────────┤ X ├─░─┤ RY(θ[7]) ├ └──────────┘ ░ └───┘ ░ └──────────┘ ``` ```python >>> ansatz = RealAmplitudes(4, reps=2, entanglement=[[0,3], [0,2]], ... skip_unentangled_qubits=True) >>> print(ansatz) ┌──────────┐ ┌──────────┐ ┌──────────┐ q_0: ┤ RY(θ[0]) ├──■───────■──────┤ RY(θ[3]) ├──■───────■──────┤ RY(θ[6]) ├ └──────────┘ │ │ └──────────┘ │ │ └──────────┘ q_1: ──────────────┼───────┼────────────────────┼───────┼────────────────── ┌──────────┐ │ ┌─┴─┐ ┌──────────┐ │ ┌─┴─┐ ┌──────────┐ q_2: ┤ RY(θ[1]) ├──┼─────┤ X ├────┤ RY(θ[4]) ├──┼─────┤ X ├────┤ RY(θ[7]) ├ ├──────────┤┌─┴─┐┌──┴───┴───┐└──────────┘┌─┴─┐┌──┴───┴───┐└──────────┘ q_3: ┤ RY(θ[2]) ├┤ X ├┤ RY(θ[5]) ├────────────┤ X ├┤ RY(θ[8]) ├──────────── └──────────┘└───┘└──────────┘ └───┘└──────────┘ ``` **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits of the RealAmplitudes circuit. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Specifies how often the structure of a rotation layer followed by an entanglement layer is repeated. * **entanglement** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]] | Callable\[\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*],* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – Specifies the entanglement structure. Can be a string (‘full’, ‘linear’ ‘reverse\_linear, ‘circular’ or ‘sca’), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to ‘reverse\_linear’ entanglement. Note that ‘reverse\_linear’ entanglement provides the same unitary as ‘full’ with fewer entangling gates. See the Examples section of [`TwoLocal`](qiskit.circuit.library.TwoLocal ""qiskit.circuit.library.TwoLocal"") for more detail. * **initial\_state** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *| None*) – A QuantumCircuit object to prepend to the circuit. * **skip\_unentangled\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, the single qubit gates are only applied to qubits that are entangled with another qubit. If False, the single qubit gates are applied to each qubit in the Ansatz. Defaults to False. * **skip\_final\_rotation\_layer** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If False, a rotation layer is added at the end of the ansatz. If True, no rotation layer is added. * **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The parameterized gates require a parameter to be defined, for which we use [`ParameterVector`](qiskit.circuit.ParameterVector ""qiskit.circuit.ParameterVector""). * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, barriers are inserted in between each layer. If False, no barriers are inserted. * **flatten** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – Set this to `True` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you’re using this circuit for anything besides visualization its **strongly** recommended to set this flag to `True` to avoid a large performance overhead for parameter binding. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### entanglement Get the entanglement strategy. **Returns** The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted. ### entanglement\_blocks The blocks in the entanglement layers. **Returns** The blocks in the entanglement layers. ### flatten Returns whether the circuit is wrapped in nested gates/instructions or flattened. ### global\_phase Return the global phase of the current circuit scope in radians. ### initial\_state Return the initial state that is added in front of the n-local circuit. **Returns** The initial state. ### insert\_barriers If barriers are inserted in between the layers or not. **Returns** `True`, if barriers are inserted in between the layers, `False` if not. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_layers Return the number of layers in the n-local circuit. **Returns** The number of layers in the circuit. ### num\_parameters ### num\_parameters\_settable The number of total parameters that can be set to distinct values. This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from `num_parameters` which counts the number of unique [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") objects currently in the circuit. **Returns** The number of parameters originally available in the circuit. This quantity does not require the circuit to be built yet. ### num\_qubits Returns the number of qubits in this circuit. **Returns** The number of qubits. ### 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. ### ordered\_parameters The parameters used in the underlying circuit. This includes float values and duplicates. **Examples** ```python >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] ``` **Returns** The parameters objects used in the circuit. ### parameter\_bounds Return the parameter bounds. **Returns** The parameter bounds. ### parameters ### preferred\_init\_points The initial points for the parameters. Can be stored as initial guess in optimization. **Returns** The initial values for the parameters, or None, if none have been set. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### reps The number of times rotation and entanglement block are repeated. **Returns** The number of repetitions. ### rotation\_blocks The blocks in the rotation layers. **Returns** The blocks in the rotation layers. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RealAmplitudes.mdx "--- title: Reset description: API reference for qiskit.circuit.library.Reset in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.Reset --- # Reset Bases: [`SingletonInstruction`](circuit_singleton#qiskit.circuit.singleton.SingletonInstruction ""qiskit.circuit.singleton.SingletonInstruction"") Qubit reset. Create new reset instruction. ## Attributes ### 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.Reset.base_class ""qiskit.circuit.library.Reset.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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. ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### 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"") ### soft\_compare 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)"") ### 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. ### validate\_parameter Instruction parameters has no validation or normalization. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.Reset.mdx "--- title: RGate description: API reference for qiskit.circuit.library.RGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RGate --- # RGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Rotation θ around the cos(φ)x + sin(φ)y axis. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`r()`](qiskit.circuit.QuantumCircuit#r ""qiskit.circuit.QuantumCircuit.r"") method. **Circuit symbol:** ```python ┌──────┐ q_0: ┤ R(ϴ) ├ └──────┘ ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} R(\theta, \phi) = e^{-i \rotationangle \left(\cos{\phi} x + \sin{\phi} y\right)} = \begin{pmatrix} \cos\left(\rotationangle\right) & -i e^{-i \phi} \sin\left(\rotationangle\right) \\ -i e^{i \phi} \sin\left(\rotationangle\right) & \cos\left(\rotationangle\right) \end{pmatrix} $$ Create new r single-qubit gate. ## Attributes ### 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.RGate.base_class ""qiskit.circuit.library.RGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Invert this gate as: $r(θ, φ)^dagger = r(-θ, φ)$ **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 [`RGate`](#qiskit.circuit.library.RGate ""qiskit.circuit.library.RGate"") with an inverted parameter value. **Returns** inverse gate. **Return type** [RGate](#qiskit.circuit.library.RGate ""qiskit.circuit.library.RGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RGate.mdx "--- title: RGQFTMultiplier description: API reference for qiskit.circuit.library.RGQFTMultiplier in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RGQFTMultiplier --- # RGQFTMultiplier Bases: `Multiplier` A QFT multiplication circuit to store product of two input registers out-of-place. Multiplication in this circuit is implemented using the procedure of Fig. 3 in \[1], where weighted sum rotations are implemented as given in Fig. 5 in \[1]. QFT is used on the output register and is followed by rotations controlled by input registers. The rotations transform the state into the product of two input registers in QFT base, which is reverted from QFT base using inverse QFT. As an example, a circuit that performs a modular QFT multiplication on two 2-qubit sized input registers with an output register of 2 qubits, is as follows: ```python a_0: ────────────────────────────────────────■───────■──────■──────■──────────────── │ │ │ │ a_1: ─────────■───────■───────■───────■──────┼───────┼──────┼──────┼──────────────── │ │ │ │ │ │ │ │ b_0: ─────────┼───────┼───────■───────■──────┼───────┼──────■──────■──────────────── │ │ │ │ │ │ │ │ b_1: ─────────■───────■───────┼───────┼──────■───────■──────┼──────┼──────────────── ┌──────┐ │P(4π) │ │P(2π) │ │P(2π) │ │P(π) │ ┌───────┐ out_0: ┤0 ├─■───────┼───────■───────┼──────■───────┼──────■──────┼───────┤0 ├ │ qft │ │P(2π) │P(π) │P(π) │P(π/2) │ iqft │ out_1: ┤1 ├─────────■───────────────■──────────────■─────────────■───────┤1 ├ └──────┘ └───────┘ ``` **References:** \[1] Ruiz-Perez et al., Quantum arithmetic with the Quantum Fourier Transform, 2017. [arXiv:1411.5949](https://arxiv.org/pdf/1411.5949.pdf) **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits in either input register for state $|a\rangle$ or $|b\rangle$. The two input registers must have the same number of qubits. * **num\_result\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of result qubits to limit the output to. If number of result qubits is $n$, multiplication modulo $2^n$ is performed to limit the output to the specified number of qubits. Default value is `2 * num_state_qubits` to represent any possible result from the multiplication of the two inputs. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit object. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### num\_result\_qubits The number of result qubits to limit the output to. **Returns** The number of result qubits. ### num\_state\_qubits The number of state qubits, i.e. the number of bits in each input register. **Returns** The number of state qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RGQFTMultiplier.mdx "--- title: RVGate description: API reference for qiskit.circuit.library.RVGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RVGate --- # RVGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Rotation around arbitrary rotation axis $\vec{v}$ where $\|\vec{v}\|_2$ is angle of rotation in radians. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`rv()`](qiskit.circuit.QuantumCircuit#rv ""qiskit.circuit.QuantumCircuit.rv"") method. **Circuit symbol:** ```python ┌─────────────────┐ q_0: ┤ RV(v_x,v_y,v_z) ├ └─────────────────┘ ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\|\vec{v}\|_2}{2}} R(\vec{v}) = e^{-i \vec{v}\cdot\vec{\sigma} / 2} = \begin{pmatrix} \cos\left(\rotationangle\right) -i \frac{v_z}{\|\vec{v}\|_2} \sin\left(\rotationangle\right) & -(i \frac{v_x}{\|\vec{v}\|_2} + \frac{v_y}{\|\vec{v}\|_2}) \sin\left(\rotationangle\right) \\ -(i \frac{v_x}{\|\vec{v}\|_2} - \frac{v_y}{\|\vec{v}\|_2}) \sin\left(\rotationangle\right) & \cos\left(\rotationangle\right) + i \frac{v_z}{\|\vec{v}\|_2} \sin\left(\rotationangle\right) \end{pmatrix} $$ Create new rv single-qubit gate. **Parameters** * **v\_x** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – x-component * **v\_y** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – y-component * **v\_z** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – z-component * **basis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, optional*) – basis (see [`OneQubitEulerDecomposer`](qiskit.synthesis.OneQubitEulerDecomposer ""qiskit.synthesis.one_qubit.one_qubit_decompose.OneQubitEulerDecomposer"")) ## Attributes ### 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.RVGate.base_class ""qiskit.circuit.library.RVGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Invert this gate. ### to\_matrix Return a numpy.array for the R(v) gate. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RVGate.mdx "--- title: RXGate description: API reference for qiskit.circuit.library.RXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RXGate --- # RXGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Single-qubit rotation about the X axis. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`rx()`](qiskit.circuit.QuantumCircuit#rx ""qiskit.circuit.QuantumCircuit.rx"") method. **Circuit symbol:** ```python ┌───────┐ q_0: ┤ Rx(ϴ) ├ └───────┘ ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} RX(\theta) = \exp\left(-i \rotationangle X\right) = \begin{pmatrix} \cos\left(\rotationangle\right) & -i\sin\left(\rotationangle\right) \\ -i\sin\left(\rotationangle\right) & \cos\left(\rotationangle\right) \end{pmatrix} $$ Create new RX gate. ## Attributes ### 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.RXGate.base_class ""qiskit.circuit.library.RXGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-RX gate. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### inverse Return inverted RX gate. $RX(\lambda)^{\dagger} = RX(-\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 [`RXGate`](#qiskit.circuit.library.RXGate ""qiskit.circuit.library.RXGate"") with an inverted parameter value. **Returns** inverse gate. **Return type** [RXGate](#qiskit.circuit.library.RXGate ""qiskit.circuit.library.RXGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RXGate.mdx "--- title: RXXGate description: API reference for qiskit.circuit.library.RXXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RXXGate --- # RXXGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") A parametric 2-qubit $X \otimes X$ interaction (rotation about XX). This gate is symmetric, and is maximally entangling at $\theta = \pi/2$. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`rxx()`](qiskit.circuit.QuantumCircuit#rxx ""qiskit.circuit.QuantumCircuit.rxx"") method. **Circuit Symbol:** ```python ┌─────────┐ q_0: ┤1 ├ │ Rxx(ϴ) │ q_1: ┤0 ├ └─────────┘ ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} R_{XX}(\theta) = \exp\left(-i \rotationangle X{\otimes}X\right) = \begin{pmatrix} \cos\left(\rotationangle\right) & 0 & 0 & -i\sin\left(\rotationangle\right) \\ 0 & \cos\left(\rotationangle\right) & -i\sin\left(\rotationangle\right) & 0 \\ 0 & -i\sin\left(\rotationangle\right) & \cos\left(\rotationangle\right) & 0 \\ -i\sin\left(\rotationangle\right) & 0 & 0 & \cos\left(\rotationangle\right) \end{pmatrix} $$ **Examples:** > $$ > R_{XX}(\theta = 0) = I > $$ > > $$ > R_{XX}(\theta = \pi) = i X \otimes X > $$ > > $$ > R_{XX}\left(\theta = \frac{\pi}{2}\right) = \frac{1}{\sqrt{2}} > \begin{pmatrix} > 1 & 0 & 0 & -i \\ > 0 & 1 & -i & 0 \\ > 0 & -i & 1 & 0 \\ > -i & 0 & 0 & 1 > \end{pmatrix} > $$ Create new RXX gate. ## Attributes ### 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.RXXGate.base_class ""qiskit.circuit.library.RXXGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse RXX 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 [`RXXGate`](#qiskit.circuit.library.RXXGate ""qiskit.circuit.library.RXXGate"") with an inverted parameter value. **Returns** inverse gate. **Return type** [RXXGate](#qiskit.circuit.library.RXXGate ""qiskit.circuit.library.RXXGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RXXGate.mdx "--- title: RYGate description: API reference for qiskit.circuit.library.RYGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RYGate --- # RYGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Single-qubit rotation about the Y axis. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`ry()`](qiskit.circuit.QuantumCircuit#ry ""qiskit.circuit.QuantumCircuit.ry"") method. **Circuit symbol:** ```python ┌───────┐ q_0: ┤ Ry(ϴ) ├ └───────┘ ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} RY(\theta) = \exp\left(-i \rotationangle Y\right) = \begin{pmatrix} \cos\left(\rotationangle\right) & -\sin\left(\rotationangle\right) \\ \sin\left(\rotationangle\right) & \cos\left(\rotationangle\right) \end{pmatrix} $$ Create new RY gate. ## Attributes ### 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.RYGate.base_class ""qiskit.circuit.library.RYGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-RY gate. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### inverse Return inverse RY gate. $RY(\lambda)^{\dagger} = RY(-\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 [`RYGate`](#qiskit.circuit.library.RYGate ""qiskit.circuit.library.RYGate"") with an inverted parameter value. **Returns** inverse gate. **Return type** [RYGate](#qiskit.circuit.library.RYGate ""qiskit.circuit.library.RYGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RYGate.mdx "--- title: RYYGate description: API reference for qiskit.circuit.library.RYYGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RYYGate --- # RYYGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") A parametric 2-qubit $Y \otimes Y$ interaction (rotation about YY). This gate is symmetric, and is maximally entangling at $\theta = \pi/2$. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`ryy()`](qiskit.circuit.QuantumCircuit#ryy ""qiskit.circuit.QuantumCircuit.ryy"") method. **Circuit Symbol:** ```python ┌─────────┐ q_0: ┤1 ├ │ Ryy(ϴ) │ q_1: ┤0 ├ └─────────┘ ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} R_{YY}(\theta) = \exp\left(-i \rotationangle Y{\otimes}Y\right) = \begin{pmatrix} \cos\left(\rotationangle\right) & 0 & 0 & i\sin\left(\rotationangle\right) \\ 0 & \cos\left(\rotationangle\right) & -i\sin\left(\rotationangle\right) & 0 \\ 0 & -i\sin\left(\rotationangle\right) & \cos\left(\rotationangle\right) & 0 \\ i\sin\left(\rotationangle\right) & 0 & 0 & \cos\left(\rotationangle\right) \end{pmatrix} $$ **Examples:** > $$ > R_{YY}(\theta = 0) = I > $$ > > $$ > R_{YY}(\theta = \pi) = i Y \otimes Y > $$ > > $$ > R_{YY}\left(\theta = \frac{\pi}{2}\right) = \frac{1}{\sqrt{2}} > \begin{pmatrix} > 1 & 0 & 0 & i \\ > 0 & 1 & -i & 0 \\ > 0 & -i & 1 & 0 \\ > i & 0 & 0 & 1 > \end{pmatrix} > $$ Create new RYY gate. ## Attributes ### 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.RYYGate.base_class ""qiskit.circuit.library.RYYGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse RYY 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 [`RYYGate`](#qiskit.circuit.library.RYYGate ""qiskit.circuit.library.RYYGate"") with an inverted parameter value. **Returns** inverse gate. **Return type** [RYYGate](#qiskit.circuit.library.RYYGate ""qiskit.circuit.library.RYYGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RYYGate.mdx "--- title: RZGate description: API reference for qiskit.circuit.library.RZGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RZGate --- # RZGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Single-qubit rotation about the Z axis. This is a diagonal gate. It can be implemented virtually in hardware via framechanges (i.e. at zero error and duration). Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`rz()`](qiskit.circuit.QuantumCircuit#rz ""qiskit.circuit.QuantumCircuit.rz"") method. **Circuit symbol:** ```python ┌───────┐ q_0: ┤ Rz(λ) ├ └───────┘ ``` **Matrix Representation:** $$ RZ(\lambda) = \exp\left(-i\frac{\lambda}{2}Z\right) = \begin{pmatrix} e^{-i\frac{\lambda}{2}} & 0 \\ 0 & e^{i\frac{\lambda}{2}} \end{pmatrix} $$ `U1Gate` This gate is equivalent to U1 up to a phase factor. > $$ > U1(\lambda) = e^{i{\lambda}/2}RZ(\lambda) > $$ Reference for virtual Z gate implementation: [1612.00858](https://arxiv.org/abs/1612.00858) Create new RZ gate. ## Attributes ### 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.RZGate.base_class ""qiskit.circuit.library.RZGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-RZ gate. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### inverse Return inverted RZ gate $RZ(\lambda)^{\dagger} = RZ(-\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 [`RZGate`](#qiskit.circuit.library.RZGate ""qiskit.circuit.library.RZGate"") with an inverted parameter value. **Returns** inverse gate. **Return type** [RZGate](#qiskit.circuit.library.RZGate ""qiskit.circuit.library.RZGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RZGate.mdx "--- title: RZXGate description: API reference for qiskit.circuit.library.RZXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RZXGate --- # RZXGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") A parametric 2-qubit $Z \otimes X$ interaction (rotation about ZX). This gate is maximally entangling at $\theta = \pi/2$. The cross-resonance gate (CR) for superconducting qubits implements a ZX interaction (however other terms are also present in an experiment). Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`rzx()`](qiskit.circuit.QuantumCircuit#rzx ""qiskit.circuit.QuantumCircuit.rzx"") method. **Circuit Symbol:** ```python ┌─────────┐ q_0: ┤0 ├ │ Rzx(θ) │ q_1: ┤1 ├ └─────────┘ ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} R_{ZX}(\theta)\ q_0, q_1 = \exp\left(-i \frac{\theta}{2} X{\otimes}Z\right) = \begin{pmatrix} \cos\left(\rotationangle\right) & 0 & -i\sin\left(\rotationangle\right) & 0 \\ 0 & \cos\left(\rotationangle\right) & 0 & i\sin\left(\rotationangle\right) \\ -i\sin\left(\rotationangle\right) & 0 & \cos\left(\rotationangle\right) & 0 \\ 0 & i\sin\left(\rotationangle\right) & 0 & \cos\left(\rotationangle\right) \end{pmatrix} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In the above example we apply the gate on (q\_0, q\_1) which results in the $X \otimes Z$ tensor order. Instead, if we apply it on (q\_1, q\_0), the matrix will be $Z \otimes X$: ```python ┌─────────┐ q_0: ┤1 ├ │ Rzx(θ) │ q_1: ┤0 ├ └─────────┘ ``` $$ \newcommand{\rotationangle}{\frac{\theta}{2}} R_{ZX}(\theta)\ q_1, q_0 = exp(-i \frac{\theta}{2} Z{\otimes}X) = \begin{pmatrix} \cos(\rotationangle) & -i\sin(\rotationangle) & 0 & 0 \\ -i\sin(\rotationangle) & \cos(\rotationangle) & 0 & 0 \\ 0 & 0 & \cos(\rotationangle) & i\sin(\rotationangle) \\ 0 & 0 & i\sin(\rotationangle) & \cos(\rotationangle) \end{pmatrix} $$ This is a direct sum of RX rotations, so this gate is equivalent to a uniformly controlled (multiplexed) RX gate: $$ R_{ZX}(\theta)\ q_1, q_0 = \begin{pmatrix} RX(\theta) & 0 \\ 0 & RX(-\theta) \end{pmatrix} $$ **Examples:** > $$ > R_{ZX}(\theta = 0) = I > $$ > > $$ > R_{ZX}(\theta = 2\pi) = -I > $$ > > $$ > R_{ZX}(\theta = \pi) = -i Z \otimes X > $$ > > $$ > RZX(\theta = \frac{\pi}{2}) = \frac{1}{\sqrt{2}} > \begin{pmatrix} > 1 & 0 & -i & 0 \\ > 0 & 1 & 0 & i \\ > -i & 0 & 1 & 0 \\ > 0 & i & 0 & 1 > \end{pmatrix} > $$ Create new RZX gate. ## Attributes ### 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.RZXGate.base_class ""qiskit.circuit.library.RZXGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse RZX 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 [`RZXGate`](#qiskit.circuit.library.RZXGate ""qiskit.circuit.library.RZXGate"") with an inverted parameter value. **Returns:** RZXGate: inverse gate. ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RZXGate.mdx "--- title: RZZGate description: API reference for qiskit.circuit.library.RZZGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.RZZGate --- # RZZGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") A parametric 2-qubit $Z \otimes Z$ interaction (rotation about ZZ). This gate is symmetric, and is maximally entangling at $\theta = \pi/2$. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`rzz()`](qiskit.circuit.QuantumCircuit#rzz ""qiskit.circuit.QuantumCircuit.rzz"") method. **Circuit Symbol:** ```python q_0: ───■──── │zz(θ) q_1: ───■──── ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} R_{ZZ}(\theta) = \exp\left(-i \rotationangle Z{\otimes}Z\right) = \begin{pmatrix} e^{-i \rotationangle} & 0 & 0 & 0 \\ 0 & e^{i \rotationangle} & 0 & 0 \\ 0 & 0 & e^{i \rotationangle} & 0 \\ 0 & 0 & 0 & e^{-i \rotationangle} \end{pmatrix} $$ This is a direct sum of RZ rotations, so this gate is equivalent to a uniformly controlled (multiplexed) RZ gate: $$ R_{ZZ}(\theta) = \begin{pmatrix} RZ(\theta) & 0 \\ 0 & RZ(-\theta) \end{pmatrix} $$ **Examples:** > $$ > R_{ZZ}(\theta = 0) = I > $$ > > $$ > R_{ZZ}(\theta = 2\pi) = -I > $$ > > $$ > R_{ZZ}(\theta = \pi) = - Z \otimes Z > $$ > > $$ > R_{ZZ}\left(\theta = \frac{\pi}{2}\right) = \frac{1}{\sqrt{2}} > \begin{pmatrix} > 1-i & 0 & 0 & 0 \\ > 0 & 1+i & 0 & 0 \\ > 0 & 0 & 1+i & 0 \\ > 0 & 0 & 0 & 1-i > \end{pmatrix} > $$ Create new RZZ gate. ## Attributes ### 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.RZZGate.base_class ""qiskit.circuit.library.RZZGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse RZZ 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 [`RZZGate`](#qiskit.circuit.library.RZZGate ""qiskit.circuit.library.RZZGate"") with an inverted parameter value. **Returns** inverse gate. **Return type** [RZZGate](#qiskit.circuit.library.RZZGate ""qiskit.circuit.library.RZZGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.RZZGate.mdx "--- title: SdgGate description: API reference for qiskit.circuit.library.SdgGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.SdgGate --- # SdgGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") Single qubit S-adjoint gate (\~Z\*\*0.5). It induces a $-\pi/2$ phase. This is a Clifford gate and a square-root of Pauli-Z. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`sdg()`](qiskit.circuit.QuantumCircuit#sdg ""qiskit.circuit.QuantumCircuit.sdg"") method. **Matrix Representation:** $$ Sdg = \begin{pmatrix} 1 & 0 \\ 0 & -i \end{pmatrix} $$ **Circuit symbol:** ```python ┌─────┐ q_0: ┤ Sdg ├ └─────┘ ``` Equivalent to a $-\pi/2$ radian rotation about the Z axis. Create new Sdg gate. ## Attributes ### 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.SdgGate.base_class ""qiskit.circuit.library.SdgGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse of Sdg (SGate). **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 [`SGate`](qiskit.circuit.library.SGate ""qiskit.circuit.library.SGate""). **Returns** inverse of [`SdgGate`](#qiskit.circuit.library.SdgGate ""qiskit.circuit.library.SdgGate"") **Return type** [SGate](qiskit.circuit.library.SGate ""qiskit.circuit.library.SGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.SdgGate.mdx "--- title: SGate description: API reference for qiskit.circuit.library.SGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.SGate --- # SGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") Single qubit S gate (Z\*\*0.5). It induces a $\pi/2$ phase, and is sometimes called the P gate (phase). This is a Clifford gate and a square-root of Pauli-Z. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`s()`](qiskit.circuit.QuantumCircuit#s ""qiskit.circuit.QuantumCircuit.s"") method. **Matrix Representation:** $$ S = \begin{pmatrix} 1 & 0 \\ 0 & i \end{pmatrix} $$ **Circuit symbol:** ```python ┌───┐ q_0: ┤ S ├ └───┘ ``` Equivalent to a $\pi/2$ radian rotation about the Z axis. Create new S gate. ## Attributes ### 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.SGate.base_class ""qiskit.circuit.library.SGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse of S (SdgGate). **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 [`SdgGate`](qiskit.circuit.library.SdgGate ""qiskit.circuit.library.SdgGate""). **Returns** inverse of [`SGate`](#qiskit.circuit.library.SGate ""qiskit.circuit.library.SGate"") **Return type** [SdgGate](qiskit.circuit.library.SdgGate ""qiskit.circuit.library.SdgGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.SGate.mdx "--- title: StatePreparation description: API reference for qiskit.circuit.library.StatePreparation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.StatePreparation --- # StatePreparation Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Complex amplitude state preparation. Class that implements the (complex amplitude) state preparation of some flexible collection of qubit registers. **Parameters** * **params** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.states.statevector.Statevector"")) – * Statevector: Statevector to initialize to. * list: vector of complex amplitudes to initialize to. * string: labels of basis states of the Pauli eigenstates Z, X, Y. See [`Statevector.from_label()`](qiskit.quantum_info.Statevector#from_label ""qiskit.quantum_info.Statevector.from_label""). Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label ‘01’ initializes the qubit zero to $|1\rangle$ and the qubit one to $|0\rangle$. * int: an integer that is used as a bitmap indicating which qubits to initialize to $|1\rangle$. Example: setting params to 5 would initialize qubit 0 and qubit 2 to $|1\rangle$ and qubit 1 to $|0\rangle$. * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – This parameter is only used if params is an int. Indicates the total number of qubits in the initialize call. Example: initialize covers 5 qubits and params is 3. This allows qubits 0 and 1 to be initialized to $|1\rangle$ and the remaining 3 qubits to be initialized to $|0\rangle$. * **inverse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, the inverse state is constructed. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate * **normalize** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to normalize an input array to a unit vector. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – `num_qubits` parameter used when `params` is not an integer When a Statevector argument is passed the state is prepared using a recursive initialization algorithm, including optimizations, from \[1], as well as some additional optimizations including removing zero rotations and double cnots. **References:** \[1] Shende, Bullock, Markov. Synthesis of Quantum Logic Circuits (2004) \[[https://arxiv.org/abs/quant-ph/0406176v5](https://arxiv.org/abs/quant-ph/0406176v5)] ## Attributes ### 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.StatePreparation.base_class ""qiskit.circuit.library.StatePreparation.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### broadcast\_arguments 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 of quantum bit arguments. * **cargs** – 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. ### inverse Return inverted StatePreparation ### validate\_parameter StatePreparation instruction parameter can be str, int, float, and complex. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.StatePreparation.mdx "--- title: SwapGate description: API reference for qiskit.circuit.library.SwapGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.SwapGate --- # SwapGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") The SWAP gate. This is a symmetric and Clifford gate. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`swap()`](qiskit.circuit.QuantumCircuit#swap ""qiskit.circuit.QuantumCircuit.swap"") method. **Circuit symbol:** ```python q_0: ─X─ │ q_1: ─X─ ``` **Matrix Representation:** $$ SWAP = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} $$ The gate is equivalent to a state swap and is a classical logic gate. $$ |a, b\rangle \rightarrow |b, a\rangle $$ Create new SWAP gate. ## Attributes ### 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.SwapGate.base_class ""qiskit.circuit.library.SwapGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-SWAP gate. One control returns a CSWAP (Fredkin) gate. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### inverse Return inverse Swap 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** [SwapGate](#qiskit.circuit.library.SwapGate ""qiskit.circuit.library.SwapGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.SwapGate.mdx "--- title: SXdgGate description: API reference for qiskit.circuit.library.SXdgGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.SXdgGate --- # SXdgGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") The inverse single-qubit Sqrt(X) gate. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`sxdg()`](qiskit.circuit.QuantumCircuit#sxdg ""qiskit.circuit.QuantumCircuit.sxdg"") method. $$ \sqrt{X}^{\dagger} = \frac{1}{2} \begin{pmatrix} 1 - i & 1 + i \\ 1 + i & 1 - i \end{pmatrix} $$ A global phase difference exists between the definitions of $RX(-\pi/2)$ and $\sqrt{X}^{\dagger}$. $$ RX(-\pi/2) = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & i \\ i & 1 \end{pmatrix} = e^{-i \pi/4} \sqrt{X}^{\dagger} $$ Create new SXdg gate. ## Attributes ### 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.SXdgGate.base_class ""qiskit.circuit.library.SXdgGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse SXdg gate (i.e. SX). **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 [`SXGate`](qiskit.circuit.library.SXGate ""qiskit.circuit.library.SXGate""). **Returns** inverse of [`SXdgGate`](#qiskit.circuit.library.SXdgGate ""qiskit.circuit.library.SXdgGate"") **Return type** [SXGate](qiskit.circuit.library.SXGate ""qiskit.circuit.library.SXGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.SXdgGate.mdx "--- title: SXGate description: API reference for qiskit.circuit.library.SXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.SXGate --- # SXGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") The single-qubit Sqrt(X) gate ($\sqrt{X}$). Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`sx()`](qiskit.circuit.QuantumCircuit#sx ""qiskit.circuit.QuantumCircuit.sx"") method. **Matrix Representation:** $$ \sqrt{X} = \frac{1}{2} \begin{pmatrix} 1 + i & 1 - i \\ 1 - i & 1 + i \end{pmatrix} $$ **Circuit symbol:** ```python ┌────┐ q_0: ┤ √X ├ └────┘ ``` A global phase difference exists between the definitions of $RX(\pi/2)$ and $\sqrt{X}$. $$ RX(\pi/2) = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & -i \\ -i & 1 \end{pmatrix} = e^{-i \pi/4} \sqrt{X} $$ Create new SX gate. ## Attributes ### 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.SXGate.base_class ""qiskit.circuit.library.SXGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-SX gate. One control returns a CSX gate. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [SingletonControlledGate](circuit_singleton#qiskit.circuit.singleton.SingletonControlledGate ""qiskit.circuit.singleton.SingletonControlledGate"") ### inverse Return inverse SX gate (i.e. SXdg). **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 [`SXdgGate`](qiskit.circuit.library.SXdgGate ""qiskit.circuit.library.SXdgGate""). **Returns** inverse of [`SXGate`](#qiskit.circuit.library.SXGate ""qiskit.circuit.library.SXGate""). **Return type** [SXdgGate](qiskit.circuit.library.SXdgGate ""qiskit.circuit.library.SXdgGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.SXGate.mdx "--- title: TdgGate description: API reference for qiskit.circuit.library.TdgGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.TdgGate --- # TdgGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") Single qubit T-adjoint gate (\~Z\*\*0.25). It induces a $-\pi/4$ phase. This is a non-Clifford gate and a fourth-root of Pauli-Z. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`tdg()`](qiskit.circuit.QuantumCircuit#tdg ""qiskit.circuit.QuantumCircuit.tdg"") method. **Matrix Representation:** $$ Tdg = \begin{pmatrix} 1 & 0 \\ 0 & e^{-i\pi/4} \end{pmatrix} $$ **Circuit symbol:** ```python ┌─────┐ q_0: ┤ Tdg ├ └─────┘ ``` Equivalent to a $-\pi/4$ radian rotation about the Z axis. Create new Tdg gate. ## Attributes ### 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.TdgGate.base_class ""qiskit.circuit.library.TdgGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse Tdg gate (i.e. T). **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 [`TGate`](qiskit.circuit.library.TGate ""qiskit.circuit.library.TGate""). **Returns** inverse of [`TdgGate`](#qiskit.circuit.library.TdgGate ""qiskit.circuit.library.TdgGate"") **Return type** [TGate](qiskit.circuit.library.TGate ""qiskit.circuit.library.TGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.TdgGate.mdx "--- title: TGate description: API reference for qiskit.circuit.library.TGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.TGate --- # TGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") Single qubit T gate (Z\*\*0.25). It induces a $\pi/4$ phase, and is sometimes called the pi/8 gate (because of how the RZ(pi/4) matrix looks like). This is a non-Clifford gate and a fourth-root of Pauli-Z. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`t()`](qiskit.circuit.QuantumCircuit#t ""qiskit.circuit.QuantumCircuit.t"") method. **Matrix Representation:** $$ T = \begin{pmatrix} 1 & 0 \\ 0 & e^{i\pi/4} \end{pmatrix} $$ **Circuit symbol:** ```python ┌───┐ q_0: ┤ T ├ └───┘ ``` Equivalent to a $\pi/4$ radian rotation about the Z axis. Create new T gate. ## Attributes ### 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.TGate.base_class ""qiskit.circuit.library.TGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse T gate (i.e. Tdg). **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 [`TdgGate`](qiskit.circuit.library.TdgGate ""qiskit.circuit.library.TdgGate""). **Returns** inverse of [`TGate`](#qiskit.circuit.library.TGate ""qiskit.circuit.library.TGate"") **Return type** [TdgGate](qiskit.circuit.library.TdgGate ""qiskit.circuit.library.TdgGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.TGate.mdx "--- title: TwoLocal description: API reference for qiskit.circuit.library.TwoLocal in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.TwoLocal --- # TwoLocal Bases: [`NLocal`](qiskit.circuit.library.NLocal ""qiskit.circuit.library.n_local.n_local.NLocal"") The two-local circuit. The two-local circuit is a parameterized circuit consisting of alternating rotation layers and entanglement layers. The rotation layers are single qubit gates applied on all qubits. The entanglement layer uses two-qubit gates to entangle the qubits according to a strategy set using `entanglement`. Both the rotation and entanglement gates can be specified as string (e.g. `'ry'` or `'cx'`), as gate-type (e.g. `RYGate` or `CXGate`) or as QuantumCircuit (e.g. a 1-qubit circuit or 2-qubit circuit). A set of default entanglement strategies is provided: * `'full'` entanglement is each qubit is entangled with all the others. * `'linear'` entanglement is qubit $i$ entangled with qubit $i + 1$, for all $i \in \{0, 1, ... , n - 2\}$, where $n$ is the total number of qubits. * `'reverse_linear'` entanglement is qubit $i$ entangled with qubit $i + 1$, for all $i \in \{n-2, n-3, ... , 1, 0\}$, where $n$ is the total number of qubits. Note that if `entanglement_blocks = 'cx'` then this option provides the same unitary as `'full'` with fewer entangling gates. * `'pairwise'` entanglement is one layer where qubit $i$ is entangled with qubit $i + 1$, for all even values of $i$, and then a second layer where qubit $i$ is entangled with qubit $i + 1$, for all odd values of $i$. * `'circular'` entanglement is linear entanglement but with an additional entanglement of the first and last qubit before the linear part. * `'sca'` (shifted-circular-alternating) entanglement is a generalized and modified version of the proposed circuit 14 in [Sim et al.](https://arxiv.org/abs/1905.10876). It consists of circular entanglement where the ‘long’ entanglement connecting the first with the last qubit is shifted by one each block. Furthermore the role of control and target qubits are swapped every block (therefore alternating). The entanglement can further be specified using an entangler map, which is a list of index pairs, such as ```python >>> entangler_map = [(0, 1), (1, 2), (2, 0)] ``` If different entanglements per block should be used, provide a list of entangler maps. See the examples below on how this can be used. ```python >>> entanglement = [entangler_map_layer_1, entangler_map_layer_2, ... ] ``` Barriers can be inserted in between the different layers for better visualization using the `insert_barriers` attribute. For each parameterized gate a new parameter is generated using a `ParameterVector`. The name of these parameters can be chosen using the `parameter_prefix`. **Examples** ```python >>> two = TwoLocal(3, 'ry', 'cx', 'linear', reps=2, insert_barriers=True) >>> print(two) # decompose the layers into standard gates ┌──────────┐ ░ ░ ┌──────────┐ ░ ░ ┌──────────┐ q_0: ┤ Ry(θ[0]) ├─░───■────────░─┤ Ry(θ[3]) ├─░───■────────░─┤ Ry(θ[6]) ├ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ q_1: ┤ Ry(θ[1]) ├─░─┤ X ├──■───░─┤ Ry(θ[4]) ├─░─┤ X ├──■───░─┤ Ry(θ[7]) ├ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ q_2: ┤ Ry(θ[2]) ├─░──────┤ X ├─░─┤ Ry(θ[5]) ├─░──────┤ X ├─░─┤ Ry(θ[8]) ├ └──────────┘ ░ └───┘ ░ └──────────┘ ░ └───┘ ░ └──────────┘ ``` ```python >>> two = TwoLocal(3, ['ry','rz'], 'cz', 'full', reps=1, insert_barriers=True) >>> qc = QuantumCircuit(3) >>> qc += two >>> print(qc.decompose().draw()) ┌──────────┐┌──────────┐ ░ ░ ┌──────────┐ ┌──────────┐ q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├─░──■──■─────░─┤ Ry(θ[6]) ├─┤ Rz(θ[9]) ├ ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤┌┴──────────┤ q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├─░──■──┼──■──░─┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├ ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤├───────────┤ q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├─░─────■──■──░─┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├ └──────────┘└──────────┘ ░ ░ └──────────┘└───────────┘ ``` ```python >>> entangler_map = [[0, 1], [1, 2], [2, 0]] # circular entanglement for 3 qubits >>> two = TwoLocal(3, 'x', 'crx', entangler_map, reps=1) >>> print(two) # note: no barriers inserted this time! ┌───┐ ┌──────────┐┌───┐ q_0: |0>┤ X ├─────■───────────────────────┤ Rx(θ[2]) ├┤ X ├ ├───┤┌────┴─────┐ ┌───┐└─────┬────┘└───┘ q_1: |0>┤ X ├┤ Rx(θ[0]) ├─────■──────┤ X ├──────┼────────── ├───┤└──────────┘┌────┴─────┐└───┘ │ ┌───┐ q_2: |0>┤ X ├────────────┤ Rx(θ[1]) ├───────────■─────┤ X ├ └───┘ └──────────┘ └───┘ ``` ```python >>> entangler_map = [[0, 3], [0, 2]] # entangle the first and last two-way >>> two = TwoLocal(4, [], 'cry', entangler_map, reps=1) >>> circuit = two + two >>> print(circuit.decompose().draw()) # note, that the parameters are the same! q_0: ─────■───────────■───────────■───────────■────── │ │ │ │ q_1: ─────┼───────────┼───────────┼───────────┼────── │ ┌────┴─────┐ │ ┌────┴─────┐ q_2: ─────┼──────┤ Ry(θ[1]) ├─────┼──────┤ Ry(θ[1]) ├ ┌────┴─────┐└──────────┘┌────┴─────┐└──────────┘ q_3: ┤ Ry(θ[0]) ├────────────┤ Ry(θ[0]) ├──────────── └──────────┘ └──────────┘ ``` ```python >>> layer_1 = [(0, 1), (0, 2)] >>> layer_2 = [(1, 2)] >>> two = TwoLocal(3, 'x', 'cx', [layer_1, layer_2], reps=2, insert_barriers=True) >>> print(two) ┌───┐ ░ ░ ┌───┐ ░ ░ ┌───┐ q_0: ┤ X ├─░───■────■───░─┤ X ├─░───────░─┤ X ├ ├───┤ ░ ┌─┴─┐ │ ░ ├───┤ ░ ░ ├───┤ q_1: ┤ X ├─░─┤ X ├──┼───░─┤ X ├─░───■───░─┤ X ├ ├───┤ ░ └───┘┌─┴─┐ ░ ├───┤ ░ ┌─┴─┐ ░ ├───┤ q_2: ┤ X ├─░──────┤ X ├─░─┤ X ├─░─┤ X ├─░─┤ X ├ └───┘ ░ └───┘ ░ └───┘ ░ └───┘ ░ └───┘ ``` **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits of the two-local circuit. * **rotation\_blocks** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*type*](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"") *|*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") *|*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*type*](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"") *|*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") *|*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] | None*) – The gates used in the rotation layer. Can be specified via the name of a gate (e.g. `'ry'`) or the gate type itself (e.g. [`RYGate`](qiskit.circuit.library.RYGate ""qiskit.circuit.library.RYGate"")). If only one gate is provided, the gate same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order. See the Examples section for more detail. * **entanglement\_blocks** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*type*](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"") *|*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") *|*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*type*](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"") *|*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") *|*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] | None*) – The gates used in the entanglement layer. Can be specified in the same format as `rotation_blocks`. * **entanglement** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]] | Callable\[\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*],* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – Specifies the entanglement structure. Can be a string (`'full'`, `'linear'`, `'reverse_linear'`, `'circular'` or `'sca'`), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to `'full'` entanglement. Note that if `entanglement_blocks = 'cx'`, then `'full'` entanglement provides the same unitary as `'reverse_linear'` but the latter option has fewer entangling gates. See the Examples section for more detail. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Specifies how often a block consisting of a rotation layer and entanglement layer is repeated. * **skip\_unentangled\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True`, the single qubit gates are only applied to qubits that are entangled with another qubit. If `False`, the single qubit gates are applied to each qubit in the ansatz. Defaults to `False`. * **skip\_final\_rotation\_layer** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `False`, a rotation layer is added at the end of the ansatz. If `True`, no rotation layer is added. * **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The parameterized gates require a parameter to be defined, for which we use instances of [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter""). The name of each parameter will be this specified prefix plus its index. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True`, barriers are inserted in between each layer. If `False`, no barriers are inserted. Defaults to `False`. * **initial\_state** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *| None*) – A [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") object to prepend to the circuit. * **flatten** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – Set this to `True` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you’re using this circuit for anything besides visualization its **strongly** recommended to set this flag to `True` to avoid a large performance overhead for parameter binding. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### entanglement Get the entanglement strategy. **Returns** The entanglement strategy, see [`get_entangler_map()`](#qiskit.circuit.library.TwoLocal.get_entangler_map ""qiskit.circuit.library.TwoLocal.get_entangler_map"") for more detail on how the format is interpreted. ### entanglement\_blocks The blocks in the entanglement layers. **Returns** The blocks in the entanglement layers. ### flatten Returns whether the circuit is wrapped in nested gates/instructions or flattened. ### global\_phase Return the global phase of the current circuit scope in radians. ### initial\_state Return the initial state that is added in front of the n-local circuit. **Returns** The initial state. ### insert\_barriers If barriers are inserted in between the layers or not. **Returns** `True`, if barriers are inserted in between the layers, `False` if not. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_layers Return the number of layers in the n-local circuit. **Returns** The number of layers in the circuit. ### num\_parameters ### num\_parameters\_settable The number of total parameters that can be set to distinct values. This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from `num_parameters` which counts the number of unique [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") objects currently in the circuit. **Returns** The number of parameters originally available in the circuit. This quantity does not require the circuit to be built yet. ### num\_qubits Returns the number of qubits in this circuit. **Returns** The number of qubits. ### 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. ### ordered\_parameters The parameters used in the underlying circuit. This includes float values and duplicates. **Examples** ```python >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] ``` **Returns** The parameters objects used in the circuit. ### parameter\_bounds The parameter bounds for the unbound parameters in the circuit. **Returns** A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If `None` is returned, problem is fully unbounded. ### parameters ### preferred\_init\_points The initial points for the parameters. Can be stored as initial guess in optimization. **Returns** The initial values for the parameters, or None, if none have been set. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### reps The number of times rotation and entanglement block are repeated. **Returns** The number of repetitions. ### rotation\_blocks The blocks in the rotation layers. **Returns** The blocks in the rotation layers. ## Methods ### get\_entangler\_map Overloading to handle the special case of 1 qubit where the entanglement are ignored. **Return type** [*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence ""(in Python v3.12)"")\[[*Sequence*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence ""(in Python v3.12)"")\[[int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")]] ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.TwoLocal.mdx "--- title: U1Gate description: API reference for qiskit.circuit.library.U1Gate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.U1Gate --- # U1Gate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Single-qubit rotation about the Z axis. This is a diagonal gate. It can be implemented virtually in hardware via framechanges (i.e. at zero error and duration). This gate is deprecated. Instead, the following replacements should be used $$ U1(\lambda) = P(\lambda)= U(0,0,\lambda) $$ ```python circuit = QuantumCircuit(1) circuit.p(lambda, 0) # or circuit.u(0, 0, lambda) ``` **Circuit symbol:** ```python ┌───────┐ q_0: ┤ U1(λ) ├ └───────┘ ``` **Matrix Representation:** $$ U1(\lambda) = \begin{pmatrix} 1 & 0 \\ 0 & e^{i\lambda} \end{pmatrix} $$ **Examples:** > $$ > U1(\lambda = \pi) = Z > $$ > > $$ > U1(\lambda = \pi/2) = S > $$ > > $$ > U1(\lambda = \pi/4) = T > $$ `RZGate`: This gate is equivalent to RZ up to a phase factor. > $$ > U1(\lambda) = e^{i{\lambda}/2} RZ(\lambda) > $$ `U3Gate`: U3 is a generalization of U2 that covers all single-qubit rotations, using two X90 pulses. Reference for virtual Z gate implementation: [1612.00858](https://arxiv.org/abs/1612.00858) Create new U1 gate. ## Attributes ### 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.U1Gate.base_class ""qiskit.circuit.library.U1Gate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-U1 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"") ### inverse Return inverted U1 gate ($U1(\lambda)^{\dagger} = U1(-\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 [`U1Gate`](#qiskit.circuit.library.U1Gate ""qiskit.circuit.library.U1Gate"") with inverse parameter values. **Returns** inverse gate. **Return type** [U1Gate](#qiskit.circuit.library.U1Gate ""qiskit.circuit.library.U1Gate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.U1Gate.mdx "--- title: U2Gate description: API reference for qiskit.circuit.library.U2Gate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.U2Gate --- # U2Gate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Single-qubit rotation about the X+Z axis. Implemented using one X90 pulse on IBM Quantum systems: This gate is deprecated. Instead, the following replacements should be used $$ U2(\phi, \lambda) = U\left(\frac{\pi}{2}, \phi, \lambda\right) $$ ```python circuit = QuantumCircuit(1) circuit.u(pi/2, phi, lambda) ``` **Circuit symbol:** ```python ┌─────────┐ q_0: ┤ U2(φ,λ) ├ └─────────┘ ``` **Matrix Representation:** $$ U2(\phi, \lambda) = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & -e^{i\lambda} \\ e^{i\phi} & e^{i(\phi+\lambda)} \end{pmatrix} $$ **Examples:** $$ U2(\phi,\lambda) = e^{i \frac{\phi + \lambda}{2}}RZ(\phi) RY\left(\frac{\pi}{2}\right) RZ(\lambda) = e^{- i\frac{\pi}{4}} P\left(\frac{\pi}{2} + \phi\right) \sqrt{X} P\left(\lambda- \frac{\pi}{2}\right) $$ $$ U2(0, \pi) = H $$ $$ U2(0, 0) = RY(\pi/2) $$ $$ U2(-\pi/2, \pi/2) = RX(\pi/2) $$ `U3Gate`: U3 is a generalization of U2 that covers all single-qubit rotations, using two X90 pulses. Create new U2 gate. ## Attributes ### 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.U2Gate.base_class ""qiskit.circuit.library.U2Gate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverted U2 gate. $U2(\phi, \lambda)^{\dagger} =U2(-\lambda-\pi, -\phi+\pi))$ **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 [`U2Gate`](#qiskit.circuit.library.U2Gate ""qiskit.circuit.library.U2Gate"") with inverse parameter values. **Returns** inverse gate. **Return type** [U2Gate](#qiskit.circuit.library.U2Gate ""qiskit.circuit.library.U2Gate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.U2Gate.mdx "--- title: U3Gate description: API reference for qiskit.circuit.library.U3Gate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.U3Gate --- # U3Gate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Generic single-qubit rotation gate with 3 Euler angles. This gate is deprecated. Instead, the following replacements should be used $$ U3(\theta, \phi, \lambda) = U(\theta, \phi, \lambda) $$ ```python circuit = QuantumCircuit(1) circuit.u(theta, phi, lambda) ``` **Circuit symbol:** ```python ┌───────────┐ q_0: ┤ U3(ϴ,φ,λ) ├ └───────────┘ ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} U3(\theta, \phi, \lambda) = \begin{pmatrix} \cos\left(\rotationangle\right) & -e^{i\lambda}\sin\left(\rotationangle\right) \\ e^{i\phi}\sin\left(\rotationangle\right) & e^{i(\phi+\lambda)}\cos\left(\rotationangle\right) \end{pmatrix} $$ The matrix representation shown here differs from the [OpenQASM 2.0 specification](https://doi.org/10.48550/arXiv.1707.03429) by a global phase of $e^{i(\phi+\lambda)/2}$. **Examples:** $$ U3(\theta, \phi, \lambda) = e^{-i \frac{\pi + \theta}{2}} P(\phi + \pi) \sqrt{X} P(\theta + \pi) \sqrt{X} P(\lambda) $$ $$ U3\left(\theta, -\frac{\pi}{2}, \frac{\pi}{2}\right) = RX(\theta) $$ $$ U3(\theta, 0, 0) = RY(\theta) $$ Create new U3 gate. ## Attributes ### 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.U3Gate.base_class ""qiskit.circuit.library.U3Gate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-U3 gate. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### inverse Return inverted U3 gate. $U3(\theta,\phi,\lambda)^{\dagger} =U3(-\theta,-\lambda,-\phi))$ **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 [`U3Gate`](#qiskit.circuit.library.U3Gate ""qiskit.circuit.library.U3Gate"") with inverse parameter values. **Returns** inverse gate. **Return type** [U3Gate](#qiskit.circuit.library.U3Gate ""qiskit.circuit.library.U3Gate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.U3Gate.mdx "--- title: UCGate description: API reference for qiskit.circuit.library.UCGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.UCGate --- # UCGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Uniformly controlled gate (also called multiplexed gate). These gates can have several control qubits and a single target qubit. If the k control qubits are in the state $|i\rangle$ (in the computational basis), a single-qubit unitary $U_i$ is applied to the target qubit. This gate is represented by a block-diagonal matrix, where each block is a $2\times 2$ unitary, that is $$ \begin{pmatrix} U_0 & 0 & \cdots & 0 \\ 0 & U_1 & \cdots & 0 \\ \vdots & & \ddots & \vdots \\ 0 & 0 & \cdots & U_{2^{k-1}} \end{pmatrix}. $$ The decomposition is based on Ref. \[1]. **References:** **\[1] Bergholm et al., Quantum circuits with uniformly controlled one-qubit gates (2005).** [Phys. Rev. A 71, 052330](https://journals.aps.org/pra/abstract/10.1103/PhysRevA.71.052330). **Parameters** * **gate\_list** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[np.ndarray]*) – List of two qubit unitaries $[U_0, ..., U_{2^{k-1}}]$, where each single-qubit unitary $U_i$ is given as a $2 \times 2$ numpy array. * **up\_to\_diagonal** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Determines if the gate is implemented up to a diagonal. or if it is decomposed completely (default: False). If the `UCGate` $U$ is decomposed up to a diagonal $D$, this means that the circuit implements a unitary $U'$ such that $D U' = U$. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – in case of bad input to the constructor ## Attributes ### 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.UCGate.base_class ""qiskit.circuit.library.UCGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return the inverse. This does not re-compute the decomposition for the multiplexer with the inverse of the gates but simply inverts the existing decomposition. **Return type** [*Gate*](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") ### validate\_parameter Uniformly controlled gate parameter has to be an ndarray. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.UCGate.mdx "--- title: UCPauliRotGate description: API reference for qiskit.circuit.library.UCPauliRotGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.UCPauliRotGate --- # UCPauliRotGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Uniformly controlled Pauli rotations. Implements the [`UCGate`](qiskit.circuit.library.UCGate ""qiskit.circuit.library.UCGate"") for the special case that all unitaries are Pauli rotations, $U_i = R_P(a_i)$ where $P \in \{X, Y, Z\}$ and $a_i \in \mathbb{R}$ is the rotation angle. **Parameters** * **angle\_list** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – List of rotation angles $[a_0, ..., a_{2^{k-1}}]$. * **rot\_axis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Rotation axis. Must be either of `""X""`, `""Y""` or `""Z""`. ## Attributes ### 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.UCPauliRotGate.base_class ""qiskit.circuit.library.UCPauliRotGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.UCPauliRotGate.mdx "--- title: UCRXGate description: API reference for qiskit.circuit.library.UCRXGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.UCRXGate --- # UCRXGate Bases: [`UCPauliRotGate`](qiskit.circuit.library.UCPauliRotGate ""qiskit.circuit.library.generalized_gates.uc_pauli_rot.UCPauliRotGate"") Uniformly controlled Pauli-X rotations. Implements the [`UCGate`](qiskit.circuit.library.UCGate ""qiskit.circuit.library.UCGate"") for the special case that all unitaries are Pauli-X rotations, $U_i = R_X(a_i)$ where $a_i \in \mathbb{R}$ is the rotation angle. **Parameters** **angle\_list** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – List of rotation angles $[a_0, ..., a_{2^{k-1}}]$. ## Attributes ### 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.UCRXGate.base_class ""qiskit.circuit.library.UCRXGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.UCRXGate.mdx "--- title: UCRYGate description: API reference for qiskit.circuit.library.UCRYGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.UCRYGate --- # UCRYGate Bases: [`UCPauliRotGate`](qiskit.circuit.library.UCPauliRotGate ""qiskit.circuit.library.generalized_gates.uc_pauli_rot.UCPauliRotGate"") Uniformly controlled Pauli-Y rotations. Implements the [`UCGate`](qiskit.circuit.library.UCGate ""qiskit.circuit.library.UCGate"") for the special case that all unitaries are Pauli-Y rotations, $U_i = R_Y(a_i)$ where $a_i \in \mathbb{R}$ is the rotation angle. **Parameters** **angle\_list** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – List of rotation angles $[a_0, ..., a_{2^{k-1}}]$. ## Attributes ### 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.UCRYGate.base_class ""qiskit.circuit.library.UCRYGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.UCRYGate.mdx "--- title: UCRZGate description: API reference for qiskit.circuit.library.UCRZGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.UCRZGate --- # UCRZGate Bases: [`UCPauliRotGate`](qiskit.circuit.library.UCPauliRotGate ""qiskit.circuit.library.generalized_gates.uc_pauli_rot.UCPauliRotGate"") Uniformly controlled Pauli-Z rotations. Implements the [`UCGate`](qiskit.circuit.library.UCGate ""qiskit.circuit.library.UCGate"") for the special case that all unitaries are Pauli-Z rotations, $U_i = R_Z(a_i)$ where $a_i \in \mathbb{R}$ is the rotation angle. **Parameters** **angle\_list** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – List of rotation angles $[a_0, ..., a_{2^{k-1}}]$. ## Attributes ### 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.UCRZGate.base_class ""qiskit.circuit.library.UCRZGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.UCRZGate.mdx "--- title: UGate description: API reference for qiskit.circuit.library.UGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.UGate --- # UGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Generic single-qubit rotation gate with 3 Euler angles. Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`u()`](qiskit.circuit.QuantumCircuit#u ""qiskit.circuit.QuantumCircuit.u"") method. **Circuit symbol:** ```python ┌──────────┐ q_0: ┤ U(ϴ,φ,λ) ├ └──────────┘ ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} U(\theta, \phi, \lambda) = \begin{pmatrix} \cos\left(\rotationangle\right) & -e^{i\lambda}\sin\left(\rotationangle\right) \\ e^{i\phi}\sin\left(\rotationangle\right) & e^{i(\phi+\lambda)}\cos\left(\rotationangle\right) \end{pmatrix} $$ The matrix representation shown here is the same as in the [OpenQASM 3.0 specification](https://openqasm.com/language/gates.html#built-in-gates), which differs from the [OpenQASM 2.0 specification](https://doi.org/10.48550/arXiv.1707.03429) by a global phase of $e^{i(\phi+\lambda)/2}$. **Examples:** $$ U\left(\theta, -\frac{\pi}{2}, \frac{\pi}{2}\right) = RX(\theta) $$ $$ U(\theta, 0, 0) = RY(\theta) $$ Create new U gate. ## Attributes ### 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.UGate.base_class ""qiskit.circuit.library.UGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-U gate. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### inverse Return inverted U gate. $U(\theta,\phi,\lambda)^{\dagger} =U(-\theta,-\lambda,-\phi))$ **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 [`UGate`](#qiskit.circuit.library.UGate ""qiskit.circuit.library.UGate"") with inverse parameter values. **Returns** inverse gate. **Return type** [UGate](#qiskit.circuit.library.UGate ""qiskit.circuit.library.UGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.UGate.mdx "--- title: UnitaryGate description: API reference for qiskit.circuit.library.UnitaryGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.UnitaryGate --- # UnitaryGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") Class quantum gates specified by a unitary matrix. **Example** We can create a unitary gate from a unitary matrix then add it to a quantum circuit. The matrix can also be directly applied to the quantum circuit, see [`QuantumCircuit.unitary()`](qiskit.circuit.QuantumCircuit#unitary ""qiskit.circuit.QuantumCircuit.unitary""). ```python from qiskit import QuantumCircuit from qiskit.circuit.library import UnitaryGate matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] gate = UnitaryGate(matrix) circuit = QuantumCircuit(2) circuit.append(gate, [0, 1]) ``` Create a gate from a numeric unitary matrix. **Parameters** * **data** ([*numpy.ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"") *|*[*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"") *| BaseOperator*) – Unitary operator. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Unitary name for backend \[Default: `None`]. * **check\_input** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to `False` this asserts the input is known to be unitary and the checking to validate this will be skipped. This should only ever be used if you know the input is unitary, setting this to `False` and passing in a non-unitary matrix will result unexpected behavior and errors. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If input data is not an N-qubit unitary operator. ## Attributes ### base\_class 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.UnitaryGate.base_class ""qiskit.circuit.library.UnitaryGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### adjoint Return the adjoint of the unitary. ### conjugate Return the conjugate of the unitary. ### control Return controlled version of gate. **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 is 1). * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Optional gate label. * **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 bit string (e.g. `""1011""`). 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 gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") | [AnnotatedOperation](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"") ### inverse Return the adjoint of the unitary. ### transpose Return the transpose of the unitary. ### validate\_parameter Unitary gate parameter has to be an ndarray. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.UnitaryGate.mdx "--- title: UnitaryOverlap description: API reference for qiskit.circuit.library.UnitaryOverlap in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.UnitaryOverlap --- # UnitaryOverlap Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") Circuit that returns the overlap between two unitaries $U_2^{\dag} U_1$. The input quantum circuits must represent unitary operations, since they must be invertible. If the inputs will have parameters, they are replaced by [`ParameterVector`](qiskit.circuit.ParameterVector ""qiskit.circuit.ParameterVector"")s with names “p1” (for circuit `unitary1`) and “p2” (for circuit `unitary_2`) in the output circuit. This circuit is usually employed in computing the fidelity: ```python .. math:: \left|\langle 0| U_2^{\dag} U_1|0\rangle\right|^{2} ``` by computing the probability of being in the all-zeros bit-string, or equivalently, the expectation value of projector $|0\rangle\langle 0|$. Example: ```python import numpy as np from qiskit.circuit.library import EfficientSU2, UnitaryOverlap from qiskit.primitives import Sampler # get two circuit to prepare states of which we comput the overlap circuit = EfficientSU2(2, reps=1) unitary1 = circuit.assign_parameters(np.random.random(circuit.num_parameters)) unitary2 = circuit.assign_parameters(np.random.random(circuit.num_parameters)) # create the overlap circuit overlap = UnitaryOverap(unitary1, unitary2) # sample from the overlap sampler = Sampler(options={""shots"": 100}) result = sampler.run(overlap).result() # the fidelity is the probability to measure 0 fidelity = result.quasi_dists[0].get(0, 0) ``` **Parameters** * **unitary1** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")) – Unitary acting on the ket vector. * **unitary2** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")) – Unitary whose inverse operates on the bra vector. * **prefix1** – The name of the parameter vector associated to `unitary1`, if it is parameterized. Defaults to `""p1""`. * **prefix2** – The name of the parameter vector associated to `unitary2`, if it is parameterized. Defaults to `""p2""`. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – Number of qubits in `unitary1` and `unitary2` does not match. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – Inputs contain measurements and/or resets. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.UnitaryOverlap.mdx "--- title: VBERippleCarryAdder description: API reference for qiskit.circuit.library.VBERippleCarryAdder in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.VBERippleCarryAdder --- # VBERippleCarryAdder Bases: `Adder` The VBE ripple carry adder \[1]. This circuit performs inplace addition of two equally-sized quantum registers. As an example, a classical adder circuit that performs full addition (i.e. including a carry-in bit) on two 2-qubit sized registers is as follows: ```python ┌────────┐ ┌───────────┐┌──────┐ cin_0: ┤0 ├───────────────────────┤0 ├┤0 ├ │ │ │ ││ │ a_0: ┤1 ├───────────────────────┤1 ├┤1 ├ │ │┌────────┐ ┌──────┐│ ││ Sum │ a_1: ┤ ├┤1 ├──■──┤1 ├┤ ├┤ ├ │ ││ │ │ │ ││ ││ │ b_0: ┤2 Carry ├┤ ├──┼──┤ ├┤2 Carry_dg ├┤2 ├ │ ││ │┌─┴─┐│ ││ │└──────┘ b_1: ┤ ├┤2 Carry ├┤ X ├┤2 Sum ├┤ ├──────── │ ││ │└───┘│ ││ │ cout_0: ┤ ├┤3 ├─────┤ ├┤ ├──────── │ ││ │ │ ││ │ helper_0: ┤3 ├┤0 ├─────┤0 ├┤3 ├──────── └────────┘└────────┘ └──────┘└───────────┘ ``` Here *Carry* and *Sum* gates correspond to the gates introduced in \[1]. *Carry\_dg* correspond to the inverse of the *Carry* gate. 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. This is different ordering as compared to Figure 2 in \[1], which leads to a different drawing of the circuit. **References:** \[1] 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 size of the register. * **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. **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 Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### num\_state\_qubits The number of state qubits, i.e. the number of bits in each input register. **Returns** The number of state qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.VBERippleCarryAdder.mdx "--- title: WeightedAdder description: API reference for qiskit.circuit.library.WeightedAdder in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.WeightedAdder --- # WeightedAdder Bases: `BlueprintCircuit` A circuit to compute the weighted sum of qubit registers. Given $n$ qubit basis states $q_0, \ldots, q_{n-1} \in \{0, 1\}$ and non-negative integer weights $\lambda_0, \ldots, \lambda_{n-1}$, this circuit performs the operation $$ |q_0 \ldots q_{n-1}\rangle |0\rangle_s \mapsto |q_0 \ldots q_{n-1}\rangle |\sum_{j=0}^{n-1} \lambda_j q_j\rangle_s $$ where $s$ is the number of sum qubits required. This can be computed as $$ s = 1 + \left\lfloor \log_2\left( \sum_{j=0}^{n-1} \lambda_j \right) \right\rfloor $$ or $s = 1$ if the sum of the weights is 0 (then the expression in the logarithm is invalid). For qubits in a circuit diagram, the first weight applies to the upper-most qubit. For an example where the state of 4 qubits is added into a sum register, the circuit can be schematically drawn as ```python ┌────────┐ state_0: ┤0 ├ | state_0 * weights[0] │ │ | state_1: ┤1 ├ | + state_1 * weights[1] │ │ | state_2: ┤2 ├ | + state_2 * weights[2] │ │ | state_3: ┤3 ├ | + state_3 * weights[3] │ │ sum_0: ┤4 ├ | │ Adder │ | sum_1: ┤5 ├ | = sum_0 * 2^0 + sum_1 * 2^1 + sum_2 * 2^2 │ │ | sum_2: ┤6 ├ | │ │ carry_0: ┤7 ├ │ │ carry_1: ┤8 ├ │ │ control_0: ┤9 ├ └────────┘ ``` Computes the weighted sum controlled by state qubits. **Parameters** * **num\_state\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of state qubits. * **weights** ([*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 weights, one for each state qubit. If none are provided they default to 1 for every qubit. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the circuit. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_carry\_qubits The number of carry qubits required to compute the sum. Note that this is not necessarily equal to the number of ancilla qubits, these can be queried using `num_ancilla_qubits`. **Returns** The number of carry qubits required to compute the sum. ### num\_clbits Return number of classical bits. ### num\_control\_qubits The number of additional control qubits required. Note that the total number of ancilla qubits can be obtained by calling the method `num_ancilla_qubits`. **Returns** The number of additional control qubits required (0 or 1). ### num\_parameters ### num\_qubits Return number of qubits. ### num\_state\_qubits The number of qubits to be summed. **Returns** The number of state qubits. ### num\_sum\_qubits The number of sum qubits in the circuit. **Returns** The number of qubits needed to represent the weighted sum of the qubits. ### 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. ### parameters ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### weights The weights for the qubit states. **Returns** The weight for the qubit states. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.WeightedAdder.mdx "--- title: XGate description: API reference for qiskit.circuit.library.XGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.XGate --- # XGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") The single-qubit Pauli-X gate ($\sigma_x$). Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`x()`](qiskit.circuit.QuantumCircuit#x ""qiskit.circuit.QuantumCircuit.x"") method. **Matrix Representation:** $$ X = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} $$ **Circuit symbol:** ```python ┌───┐ q_0: ┤ X ├ └───┘ ``` Equivalent to a $\pi$ radian rotation about the X axis. A global phase difference exists between the definitions of $RX(\pi)$ and $X$. $$ RX(\pi) = \begin{pmatrix} 0 & -i \\ -i & 0 \end{pmatrix} = -i X $$ The gate is equivalent to a classical bit flip. $$ |0\rangle \rightarrow |1\rangle \\ |1\rangle \rightarrow |0\rangle $$ Create new X gate. ## Attributes ### 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.XGate.base_class ""qiskit.circuit.library.XGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-X gate. One control returns a CX gate. Two controls returns a CCX gate. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### inverse Return inverted X 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** [XGate](#qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.XGate.mdx "--- title: XOR description: API reference for qiskit.circuit.library.XOR in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.XOR --- # XOR Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") An n\_qubit circuit for bitwise xor-ing the input with some integer `amount`. The `amount` is xor-ed in bitstring form with the input. This circuit can also represent addition by `amount` over the finite field GF(2). Return a circuit implementing bitwise xor. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the width of circuit. * **amount** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – the xor amount in decimal form. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – random seed in case a random xor is requested. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if the xor bitstring exceeds available qubits. **Reference Circuit:** ![../\_images/qiskit-circuit-library-XOR-1.png](/images/api/qiskit/1.0/qiskit-circuit-library-XOR-1.png) ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.XOR.mdx "--- title: XXMinusYYGate description: API reference for qiskit.circuit.library.XXMinusYYGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.XXMinusYYGate --- # XXMinusYYGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") XX-YY interaction gate. A 2-qubit parameterized XX-YY interaction. Its action is to induce a coherent rotation by some angle between $|00\rangle$ and $|11\rangle$. **Circuit Symbol:** ```python ┌───────────────┐ q_0: ┤0 ├ │ (XX-YY)(θ,β) │ q_1: ┤1 ├ └───────────────┘ ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} R_{XX-YY}(\theta, \beta) q_0, q_1 = RZ_1(\beta) \cdot \exp\left(-i \frac{\theta}{2} \frac{XX-YY}{2}\right) \cdot RZ_1(-\beta) = \begin{pmatrix} \cos\left(\rotationangle\right) & 0 & 0 & -i\sin\left(\rotationangle\right)e^{-i\beta} \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ -i\sin\left(\rotationangle\right)e^{i\beta} & 0 & 0 & \cos\left(\rotationangle\right) \end{pmatrix} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In the above example we apply the gate on (q\_0, q\_1) which results in adding the (optional) phase defined by $\beta$ on q\_1. Instead, if we apply it on (q\_1, q\_0), the phase is added on q\_0. If $\beta$ is set to its default value of $0$, the gate is equivalent in big and little endian. ```python ┌───────────────┐ q_0: ┤1 ├ │ (XX-YY)(θ,β) │ q_1: ┤0 ├ └───────────────┘ ``` $$ \newcommand{\rotationangle}{\frac{\theta}{2}} R_{XX-YY}(\theta, \beta) q_1, q_0 = RZ_0(\beta) \cdot \exp\left(-i \frac{\theta}{2} \frac{XX-YY}{2}\right) \cdot RZ_0(-\beta) = \begin{pmatrix} \cos\left(\rotationangle\right) & 0 & 0 & -i\sin\left(\rotationangle\right)e^{i\beta} \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ -i\sin\left(\rotationangle\right)e^{-i\beta} & 0 & 0 & \cos\left(\rotationangle\right) \end{pmatrix} $$ Create new XX-YY gate. **Parameters** * **theta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The rotation angle. * **beta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The phase angle. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The label of the gate. ## Attributes ### 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.XXMinusYYGate.base_class ""qiskit.circuit.library.XXMinusYYGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Inverse gate. **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 [`XXMinusYYGate`](#qiskit.circuit.library.XXMinusYYGate ""qiskit.circuit.library.XXMinusYYGate"") with inverse parameter values. **Returns** inverse gate. **Return type** [XXMinusYYGate](#qiskit.circuit.library.XXMinusYYGate ""qiskit.circuit.library.XXMinusYYGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.XXMinusYYGate.mdx "--- title: XXPlusYYGate description: API reference for qiskit.circuit.library.XXPlusYYGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.XXPlusYYGate --- # XXPlusYYGate Bases: [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") XX+YY interaction gate. A 2-qubit parameterized XX+YY interaction, also known as an XY gate. Its action is to induce a coherent rotation by some angle between $|01\rangle$ and $|10\rangle$. **Circuit Symbol:** ```python ┌───────────────┐ q_0: ┤0 ├ │ (XX+YY)(θ,β) │ q_1: ┤1 ├ └───────────────┘ ``` **Matrix Representation:** $$ \newcommand{\rotationangle}{\frac{\theta}{2}} R_{XX+YY}(\theta, \beta)\ q_0, q_1 = RZ_0(-\beta) \cdot \exp\left(-i \frac{\theta}{2} \frac{XX+YY}{2}\right) \cdot RZ_0(\beta) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos\left(\rotationangle\right) & -i\sin\left(\rotationangle\right)e^{-i\beta} & 0 \\ 0 & -i\sin\left(\rotationangle\right)e^{i\beta} & \cos\left(\rotationangle\right) & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} $$ In Qiskit’s convention, higher qubit indices are more significant (little endian convention). In the above example we apply the gate on (q\_0, q\_1) which results in adding the (optional) phase defined by $\beta$ on q\_0. Instead, if we apply it on (q\_1, q\_0), the phase is added on q\_1. If $\beta$ is set to its default value of $0$, the gate is equivalent in big and little endian. ```python ┌───────────────┐ q_0: ┤1 ├ │ (XX+YY)(θ,β) │ q_1: ┤0 ├ └───────────────┘ ``` $$ \newcommand{\rotationangle}{\frac{\theta}{2}} R_{XX+YY}(\theta, \beta)\ q_0, q_1 = RZ_1(-\beta) \cdot \exp\left(-i \frac{\theta}{2} \frac{XX+YY}{2}\right) \cdot RZ_1(\beta) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos\left(\rotationangle\right) & -i\sin\left(\rotationangle\right)e^{i\beta} & 0 \\ 0 & -i\sin\left(\rotationangle\right)e^{-i\beta} & \cos\left(\rotationangle\right) & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} $$ Create new XX+YY gate. **Parameters** * **theta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The rotation angle. * **beta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The phase angle. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The label of the gate. ## Attributes ### 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.XXPlusYYGate.base_class ""qiskit.circuit.library.XXPlusYYGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### inverse Return inverse XX+YY gate (i.e. with the negative rotation angle and same phase 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 [`XXPlusYYGate`](#qiskit.circuit.library.XXPlusYYGate ""qiskit.circuit.library.XXPlusYYGate"") with inverse parameter values. **Returns** inverse gate. **Return type** [XXPlusYYGate](#qiskit.circuit.library.XXPlusYYGate ""qiskit.circuit.library.XXPlusYYGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.XXPlusYYGate.mdx "--- title: YGate description: API reference for qiskit.circuit.library.YGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.YGate --- # YGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") The single-qubit Pauli-Y gate ($\sigma_y$). Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`y()`](qiskit.circuit.QuantumCircuit#y ""qiskit.circuit.QuantumCircuit.y"") method. **Matrix Representation:** $$ Y = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix} $$ **Circuit symbol:** ```python ┌───┐ q_0: ┤ Y ├ └───┘ ``` Equivalent to a $\pi$ radian rotation about the Y axis. A global phase difference exists between the definitions of $RY(\pi)$ and $Y$. $$ RY(\pi) = \begin{pmatrix} 0 & -1 \\ 1 & 0 \end{pmatrix} = -i Y $$ The gate is equivalent to a bit and phase flip. $$ |0\rangle \rightarrow i|1\rangle \\ |1\rangle \rightarrow -i|0\rangle $$ Create new Y gate. ## Attributes ### 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.YGate.base_class ""qiskit.circuit.library.YGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-Y gate. One control returns a CY gate. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### inverse Return inverted Y gate ($Y^{\dagger} = Y$) **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** [YGate](#qiskit.circuit.library.YGate ""qiskit.circuit.library.YGate"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.YGate.mdx "--- title: ZFeatureMap description: API reference for qiskit.circuit.library.ZFeatureMap in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.ZFeatureMap --- # ZFeatureMap Bases: [`PauliFeatureMap`](qiskit.circuit.library.PauliFeatureMap ""qiskit.circuit.library.data_preparation.pauli_feature_map.PauliFeatureMap"") The first order Pauli Z-evolution circuit. On 3 qubits and with 2 repetitions the circuit is represented by: ```python ┌───┐┌──────────────┐┌───┐┌──────────────┐ ┤ H ├┤ U1(2.0*x[0]) ├┤ H ├┤ U1(2.0*x[0]) ├ ├───┤├──────────────┤├───┤├──────────────┤ ┤ H ├┤ U1(2.0*x[1]) ├┤ H ├┤ U1(2.0*x[1]) ├ ├───┤├──────────────┤├───┤├──────────────┤ ┤ H ├┤ U1(2.0*x[2]) ├┤ H ├┤ U1(2.0*x[2]) ├ └───┘└──────────────┘└───┘└──────────────┘ ``` This is a sub-class of [`PauliFeatureMap`](qiskit.circuit.library.PauliFeatureMap ""qiskit.circuit.library.PauliFeatureMap"") where the Pauli strings are fixed as \[‘Z’]. As a result the first order expansion will be a circuit without entangling gates. **Examples** ```python >>> prep = ZFeatureMap(3, reps=3, insert_barriers=True) >>> print(prep) ┌───┐ ░ ┌──────────────┐ ░ ┌───┐ ░ ┌──────────────┐ ░ ┌───┐ ░ ┌──────────────┐ q_0: ┤ H ├─░─┤ U1(2.0*x[0]) ├─░─┤ H ├─░─┤ U1(2.0*x[0]) ├─░─┤ H ├─░─┤ U1(2.0*x[0]) ├ ├───┤ ░ ├──────────────┤ ░ ├───┤ ░ ├──────────────┤ ░ ├───┤ ░ ├──────────────┤ q_1: ┤ H ├─░─┤ U1(2.0*x[1]) ├─░─┤ H ├─░─┤ U1(2.0*x[1]) ├─░─┤ H ├─░─┤ U1(2.0*x[1]) ├ ├───┤ ░ ├──────────────┤ ░ ├───┤ ░ ├──────────────┤ ░ ├───┤ ░ ├──────────────┤ q_2: ┤ H ├─░─┤ U1(2.0*x[2]) ├─░─┤ H ├─░─┤ U1(2.0*x[2]) ├─░─┤ H ├─░─┤ U1(2.0*x[2]) ├ └───┘ ░ └──────────────┘ ░ └───┘ ░ └──────────────┘ ░ └───┘ ░ └──────────────┘ ``` ```python >>> data_map = lambda x: x[0]*x[0] + 1 # note: input is an array >>> prep = ZFeatureMap(3, reps=1, data_map_func=data_map) >>> print(prep) ┌───┐┌───────────────────────┐ q_0: ┤ H ├┤ U1(2.0*x[0]**2 + 2.0) ├ ├───┤├───────────────────────┤ q_1: ┤ H ├┤ U1(2.0*x[1]**2 + 2.0) ├ ├───┤├───────────────────────┤ q_2: ┤ H ├┤ U1(2.0*x[2]**2 + 2.0) ├ └───┘└───────────────────────┘ ``` ```python >>> classifier = ZFeatureMap(3, reps=1) + RY(3, reps=1) >>> print(classifier) ┌───┐┌──────────────┐┌──────────┐ ┌──────────┐ q_0: ┤ H ├┤ U1(2.0*x[0]) ├┤ RY(θ[0]) ├─■──■─┤ RY(θ[3]) ├──────────── ├───┤├──────────────┤├──────────┤ │ │ └──────────┘┌──────────┐ q_1: ┤ H ├┤ U1(2.0*x[1]) ├┤ RY(θ[1]) ├─■──┼──────■──────┤ RY(θ[4]) ├ ├───┤├──────────────┤├──────────┤ │ │ ├──────────┤ q_2: ┤ H ├┤ U1(2.0*x[2]) ├┤ RY(θ[2]) ├────■──────■──────┤ RY(θ[5]) ├ └───┘└──────────────┘└──────────┘ └──────────┘ ``` Create a new first-order Pauli-Z expansion circuit. **Parameters** * **feature\_dimension** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of features * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of repeated circuits. Defaults to 2, has a minimum value of 1. * **data\_map\_func** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[*[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")*],* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None*) – A mapping function for data x which can be supplied to override the default mapping from `self_product()`. * **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The prefix used if default parameters are generated. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, barriers are inserted in between the evolution instructions and hadamard layers. ## Attributes ### alpha The Pauli rotation factor (alpha). **Returns** The Pauli rotation factor. ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### entanglement Get the entanglement strategy. **Returns** The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted. ### entanglement\_blocks ### feature\_dimension Returns the feature dimension (which is equal to the number of qubits). **Returns** The feature dimension of this feature map. ### flatten Returns whether the circuit is wrapped in nested gates/instructions or flattened. ### global\_phase Return the global phase of the current circuit scope in radians. ### initial\_state Return the initial state that is added in front of the n-local circuit. **Returns** The initial state. ### insert\_barriers If barriers are inserted in between the layers or not. **Returns** `True`, if barriers are inserted in between the layers, `False` if not. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_layers Return the number of layers in the n-local circuit. **Returns** The number of layers in the circuit. ### num\_parameters ### num\_parameters\_settable The number of distinct parameters. ### num\_qubits Returns the number of qubits in this circuit. **Returns** The number of qubits. ### 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. ### ordered\_parameters The parameters used in the underlying circuit. This includes float values and duplicates. **Examples** ```python >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] ``` **Returns** The parameters objects used in the circuit. ### parameter\_bounds The parameter bounds for the unbound parameters in the circuit. **Returns** A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If `None` is returned, problem is fully unbounded. ### parameters ### paulis The Pauli strings used in the entanglement of the qubits. **Returns** The Pauli strings as list. ### preferred\_init\_points The initial points for the parameters. Can be stored as initial guess in optimization. **Returns** The initial values for the parameters, or None, if none have been set. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### reps The number of times rotation and entanglement block are repeated. **Returns** The number of repetitions. ### rotation\_blocks The blocks in the rotation layers. **Returns** The blocks in the rotation layers. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.ZFeatureMap.mdx "--- title: ZGate description: API reference for qiskit.circuit.library.ZGate in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.ZGate --- # ZGate Bases: [`SingletonGate`](circuit_singleton#qiskit.circuit.singleton.SingletonGate ""qiskit.circuit.singleton.SingletonGate"") The single-qubit Pauli-Z gate ($\sigma_z$). Can be applied to a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") with the [`z()`](qiskit.circuit.QuantumCircuit#z ""qiskit.circuit.QuantumCircuit.z"") method. **Matrix Representation:** $$ Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} $$ **Circuit symbol:** ```python ┌───┐ q_0: ┤ Z ├ └───┘ ``` Equivalent to a $\pi$ radian rotation about the Z axis. A global phase difference exists between the definitions of $RZ(\pi)$ and $Z$. $$ RZ(\pi) = \begin{pmatrix} -i & 0 \\ 0 & i \end{pmatrix} = -i Z $$ The gate is equivalent to a phase flip. $$ |0\rangle \rightarrow |0\rangle \\ |1\rangle \rightarrow -|1\rangle $$ Create new Z gate. ## Attributes ### 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.ZGate.base_class ""qiskit.circuit.library.ZGate.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. ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### control Return a (multi-)controlled-Z gate. One control returns a CZ gate. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate \[Default: `None`] * **ctrl\_state** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – control state expressed as integer, string (e.g.\`\`’110’`), or ``None`. If `None`, use all 1s. * **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the controlled gate can be implemented as an annotated gate. **Returns** controlled version of this gate. **Return type** [ControlledGate](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") ### inverse Return inverted Z 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** [ZGate](#qiskit.circuit.library.ZGate ""qiskit.circuit.library.ZGate"") ### power Raise gate to a power. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.ZGate.mdx "--- title: ZZFeatureMap description: API reference for qiskit.circuit.library.ZZFeatureMap in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.library.ZZFeatureMap --- # ZZFeatureMap Bases: [`PauliFeatureMap`](qiskit.circuit.library.PauliFeatureMap ""qiskit.circuit.library.data_preparation.pauli_feature_map.PauliFeatureMap"") Second-order Pauli-Z evolution circuit. For 3 qubits and 1 repetition and linear entanglement the circuit is represented by: ```python ┌───┐┌─────────────────┐ ┤ H ├┤ U1(2.0*φ(x[0])) ├──■────────────────────────────■──────────────────────────────────── ├───┤├─────────────────┤┌─┴─┐┌──────────────────────┐┌─┴─┐ ┤ H ├┤ U1(2.0*φ(x[1])) ├┤ X ├┤ U1(2.0*φ(x[0],x[1])) ├┤ X ├──■────────────────────────────■── ├───┤├─────────────────┤└───┘└──────────────────────┘└───┘┌─┴─┐┌──────────────────────┐┌─┴─┐ ┤ H ├┤ U1(2.0*φ(x[2])) ├──────────────────────────────────┤ X ├┤ U1(2.0*φ(x[1],x[2])) ├┤ X ├ └───┘└─────────────────┘ └───┘└──────────────────────┘└───┘ ``` where $\varphi$ is a classical non-linear function, which defaults to $\varphi(x) = x$ if and $\varphi(x,y) = (\pi - x)(\pi - y)$. **Examples** ```python >>> from qiskit.circuit.library import ZZFeatureMap >>> prep = ZZFeatureMap(2, reps=1) >>> print(prep) ┌───┐┌──────────────┐ q_0: ┤ H ├┤ U1(2.0*x[0]) ├──■───────────────────────────────────────■── ├───┤├──────────────┤┌─┴─┐┌─────────────────────────────────┐┌─┴─┐ q_1: ┤ H ├┤ U1(2.0*x[1]) ├┤ X ├┤ U1(2.0*(pi - x[0])*(pi - x[1])) ├┤ X ├ └───┘└──────────────┘└───┘└─────────────────────────────────┘└───┘ ``` ```python >>> from qiskit.circuit.library import EfficientSU2 >>> classifier = ZZFeatureMap(3) + EfficientSU2(3) >>> classifier.num_parameters 15 >>> classifier.parameters # 'x' for the data preparation, 'θ' for the SU2 parameters ParameterView([ ParameterVectorElement(x[0]), ParameterVectorElement(x[1]), ParameterVectorElement(x[2]), ParameterVectorElement(θ[0]), ParameterVectorElement(θ[1]), ParameterVectorElement(θ[2]), ParameterVectorElement(θ[3]), ParameterVectorElement(θ[4]), ParameterVectorElement(θ[5]), ParameterVectorElement(θ[6]), ParameterVectorElement(θ[7]), ParameterVectorElement(θ[8]), ParameterVectorElement(θ[9]), ParameterVectorElement(θ[10]), ParameterVectorElement(θ[11]), ParameterVectorElement(θ[12]), ParameterVectorElement(θ[13]), ParameterVectorElement(θ[14]), ParameterVectorElement(θ[15]), ParameterVectorElement(θ[16]), ParameterVectorElement(θ[17]), ParameterVectorElement(θ[18]), ParameterVectorElement(θ[19]), ParameterVectorElement(θ[20]), ParameterVectorElement(θ[21]), ParameterVectorElement(θ[22]), ParameterVectorElement(θ[23]) ]) >>> classifier.count_ops() OrderedDict([('ZZFeatureMap', 1), ('EfficientSU2', 1)]) ``` Create a new second-order Pauli-Z expansion. **Parameters** * **feature\_dimension** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of features. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of repeated circuits, has a min. value of 1. * **entanglement** ([*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)"")*\[*[*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)"")*]] |* [*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(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)"")*]]*) – Specifies the entanglement structure. Refer to [`NLocal`](qiskit.circuit.library.NLocal ""qiskit.circuit.library.NLocal"") for detail. * **data\_map\_func** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[*[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")*],* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None*) – A mapping function for data x. * **parameter\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The prefix used if default parameters are generated. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, barriers are inserted in between the evolution instructions and hadamard layers. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the feature dimension is smaller than 2. ## Attributes ### alpha The Pauli rotation factor (alpha). **Returns** The Pauli rotation factor. ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### data ### entanglement Get the entanglement strategy. **Returns** The entanglement strategy, see `get_entangler_map()` for more detail on how the format is interpreted. ### entanglement\_blocks ### feature\_dimension Returns the feature dimension (which is equal to the number of qubits). **Returns** The feature dimension of this feature map. ### flatten Returns whether the circuit is wrapped in nested gates/instructions or flattened. ### global\_phase Return the global phase of the current circuit scope in radians. ### initial\_state Return the initial state that is added in front of the n-local circuit. **Returns** The initial state. ### insert\_barriers If barriers are inserted in between the layers or not. **Returns** `True`, if barriers are inserted in between the layers, `False` if not. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_layers Return the number of layers in the n-local circuit. **Returns** The number of layers in the circuit. ### num\_parameters ### num\_parameters\_settable The number of distinct parameters. ### num\_qubits Returns the number of qubits in this circuit. **Returns** The number of qubits. ### 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. ### ordered\_parameters The parameters used in the underlying circuit. This includes float values and duplicates. **Examples** ```python >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] ``` **Returns** The parameters objects used in the circuit. ### parameter\_bounds The parameter bounds for the unbound parameters in the circuit. **Returns** A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If `None` is returned, problem is fully unbounded. ### parameters ### paulis The Pauli strings used in the entanglement of the qubits. **Returns** The Pauli strings as list. ### preferred\_init\_points The initial points for the parameters. Can be stored as initial guess in optimization. **Returns** The initial values for the parameters, or None, if none have been set. ### prefix ### qregs A list of the quantum registers associated with the circuit. ### qubits Returns a list of quantum bits in the order that the registers were added. ### reps The number of times rotation and entanglement block are repeated. **Returns** The number of repetitions. ### rotation\_blocks The blocks in the rotation layers. **Returns** The blocks in the rotation layers. ",repo/docs/api/qiskit/1.0\qiskit.circuit.library.ZZFeatureMap.mdx "--- 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 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 Unique string identifier for operation type. ### num\_clbits Number of classical bits. ### num\_qubits Number of qubits. ",repo/docs/api/qiskit/1.0\qiskit.circuit.Operation.mdx "--- 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 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 Returns the name of the [`Parameter`](#qiskit.circuit.Parameter ""qiskit.circuit.Parameter""). ### parameters Returns a set of the unbound Parameters in the expression. ### 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. ## Methods ### abs Absolute of a ParameterExpression ### arccos Arccos of a ParameterExpression ### arcsin Arcsin of a ParameterExpression ### arctan Arctan of a ParameterExpression ### assign 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. ### bind 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"") ### conjugate Return the conjugate. **Return type** [*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") ### cos Cosine of a ParameterExpression ### exp Exponential of a ParameterExpression ### gradient 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)"") ### is\_real Return whether the expression is real ### log Logarithm of a ParameterExpression ### 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)"") ### sign Sign of a ParameterExpression ### sin Sine of a ParameterExpression ### subs Substitute self with the corresponding parameter in `parameter_map`. ### 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. 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. ### tan Tangent of a ParameterExpression ",repo/docs/api/qiskit/1.0\qiskit.circuit.Parameter.mdx "--- 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 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 Returns a set of the unbound Parameters in the expression. ## Methods ### abs Absolute of a ParameterExpression ### arccos Arccos of a ParameterExpression ### arcsin Arcsin of a ParameterExpression ### arctan Arctan of a ParameterExpression ### assign 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"") ### bind 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"") ### conjugate Return the conjugate. **Return type** [*ParameterExpression*](#qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") ### cos Cosine of a ParameterExpression ### exp Exponential of a ParameterExpression ### gradient 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)"") ### is\_real Return whether the expression is real ### log Logarithm of a ParameterExpression ### 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)"") ### sign Sign of a ParameterExpression ### sin Sine of a ParameterExpression ### subs 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"") ### 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. 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. ### tan Tangent of a ParameterExpression ",repo/docs/api/qiskit/1.0\qiskit.circuit.ParameterExpression.mdx "--- 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 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 Returns the name of the ParameterVector. ### params Returns the list of parameters in the ParameterVector. ## Methods ### index Returns first index of value. ### resize 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. ",repo/docs/api/qiskit/1.0\qiskit.circuit.ParameterVector.mdx "--- title: PowerModifier description: API reference for qiskit.circuit.PowerModifier in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.PowerModifier --- # PowerModifier Bases: `Modifier` Power modifier: specifies that the operation is raised to the power `power`. ## Attributes ### power ",repo/docs/api/qiskit/1.0\qiskit.circuit.PowerModifier.mdx "--- title: QuantumCircuit description: API reference for qiskit.circuit.QuantumCircuit in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.QuantumCircuit --- # QuantumCircuit Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Create a new circuit. A circuit is a list of instructions bound to some registers. **Parameters** * **regs** (list([`Register`](qiskit.circuit.Register ""qiskit.circuit.Register"")) or list(`int`) or list(list([`Bit`](qiskit.circuit.Bit ""qiskit.circuit.Bit"")))) – The registers to be included in the circuit. * If a list of [`Register`](qiskit.circuit.Register ""qiskit.circuit.Register"") objects, represents the [`QuantumRegister`](qiskit.circuit.QuantumRegister ""qiskit.circuit.QuantumRegister"") and/or [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"") objects to include in the circuit. For example: > * `QuantumCircuit(QuantumRegister(4))` > * `QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))` > * `QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))` * If a list of `int`, the amount of qubits and/or classical bits to include in the circuit. It can either be a single int for just the number of quantum bits, or 2 ints for the number of quantum bits and classical bits, respectively. For example: > * `QuantumCircuit(4) # A QuantumCircuit with 4 qubits` > * `QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits` * If a list of python lists containing [`Bit`](qiskit.circuit.Bit ""qiskit.circuit.Bit"") objects, a collection of [`Bit`](qiskit.circuit.Bit ""qiskit.circuit.Bit"") s to be added to the circuit. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – the name of the quantum circuit. If not set, an automatically generated string will be assigned. * **global\_phase** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *or*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The global phase of the circuit in radians. * **metadata** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Arbitrary key value metadata to associate with the circuit. This gets stored as free-form data in a dict in the [`metadata`](#qiskit.circuit.QuantumCircuit.metadata ""qiskit.circuit.QuantumCircuit.metadata"") attribute. It will not be directly used in the circuit. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if the circuit name, if given, is not valid. **Examples** Construct a simple Bell state circuit. ```python from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.draw('mpl') ``` ![../\_images/qiskit-circuit-QuantumCircuit-1.png](/images/api/qiskit/1.0/qiskit-circuit-QuantumCircuit-1.png) Construct a 5-qubit GHZ circuit. ```python from qiskit import QuantumCircuit qc = QuantumCircuit(5) qc.h(0) qc.cx(0, range(1, 5)) qc.measure_all() ``` Construct a 4-qubit Bernstein-Vazirani circuit using registers. ```python from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl') ``` ![../\_images/qiskit-circuit-QuantumCircuit-2.png](/images/api/qiskit/1.0/qiskit-circuit-QuantumCircuit-2.png) ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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`](#qiskit.circuit.QuantumCircuit.data ""qiskit.circuit.QuantumCircuit.data""). **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – When circuit is not scheduled. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ## Methods ### add\_bits Add Bits to the circuit. ### add\_calibration Register a low-level, custom pulse definition for the given gate. **Parameters** * **gate** (*Union\[*[*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"")*,* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – Gate information. * **qubits** (*Union\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, Tuple\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – List of qubits to be measured. * **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"")) – Schedule information. * **params** (*Optional\[List\[Union\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*,* [*Parameter*](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")*]]]*) – A list of parameters. **Raises** [**Exception**](https://docs.python.org/3/library/exceptions.html#Exception ""(in Python v3.12)"") – if the gate is of type string and params is None. ### add\_register Add registers. ### append Append one or more instructions to the end of the circuit, modifying the circuit in place. The `qargs` and `cargs` will be expanded and broadcast according to the rules of the given [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction""), and any non-[`Bit`](qiskit.circuit.Bit ""qiskit.circuit.Bit"") specifiers (such as integer indices) will be resolved into the relevant instances. If a [`CircuitInstruction`](qiskit.circuit.CircuitInstruction ""qiskit.circuit.CircuitInstruction"") is given, it will be unwrapped, verified in the context of this circuit, and a new object will be appended to the circuit. In this case, you may not pass `qargs` or `cargs` separately. **Parameters** * **instruction** ([*Operation*](qiskit.circuit.Operation ""qiskit.circuit.Operation"") *|*[*CircuitInstruction*](qiskit.circuit.CircuitInstruction ""qiskit.circuit.CircuitInstruction"")) – [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") instance to append, or a [`CircuitInstruction`](qiskit.circuit.CircuitInstruction ""qiskit.circuit.CircuitInstruction"") with all its context. * **qargs** (*Sequence\[QubitSpecifier] | None*) – specifiers of the [`Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")s to attach instruction to. * **cargs** (*Sequence\[ClbitSpecifier] | None*) – specifiers of the [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")s to attach instruction to. **Returns** a handle to the [`CircuitInstruction`](qiskit.circuit.CircuitInstruction ""qiskit.circuit.CircuitInstruction"")s that were actually added to the circuit. **Return type** [qiskit.circuit.InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if the operation passed is not an instance of [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") . ### assign\_parameters Assign parameters to new parameters or values. If `parameters` is passed as a dictionary, the keys should be [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") instances in the current circuit. The values of the dictionary can either be numeric values or new parameter objects. If `parameters` is passed as a list or array, the elements are assigned to the current parameters in the order of [`parameters`](#qiskit.circuit.QuantumCircuit.parameters ""qiskit.circuit.QuantumCircuit.parameters"") which is sorted alphabetically (while respecting the ordering in [`ParameterVector`](qiskit.circuit.ParameterVector ""qiskit.circuit.ParameterVector"") objects). The values can be assigned to the current circuit object or to a copy of it. When `parameters` is given as a mapping, it is permissible to have keys that are strings of the parameter names; these will be looked up using [`get_parameter()`](#qiskit.circuit.QuantumCircuit.get_parameter ""qiskit.circuit.QuantumCircuit.get_parameter""). You can also have keys that are [`ParameterVector`](qiskit.circuit.ParameterVector ""qiskit.circuit.ParameterVector"") instances, and in this case, the dictionary value should be a sequence of values of the same length as the vector. If you use either of these cases, you must leave the setting `flat_input=False`; changing this to `True` enables the fast path, where all keys must be [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") instances. **Parameters** * **parameters** – Either a dictionary or iterable specifying the new parameter values. * **inplace** – If False, a copy of the circuit with the bound parameters is returned. If True the circuit instance itself is modified. * **flat\_input** – If `True` and `parameters` is a mapping type, it is assumed to be exactly a mapping of `{parameter: value}`. By default (`False`), the mapping may also contain [`ParameterVector`](qiskit.circuit.ParameterVector ""qiskit.circuit.ParameterVector"") keys that point to a corresponding sequence of values, and these will be unrolled during the mapping, or string keys, which will be converted to [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") instances using [`get_parameter()`](#qiskit.circuit.QuantumCircuit.get_parameter ""qiskit.circuit.QuantumCircuit.get_parameter""). * **strict** – If `False`, any parameters given in the mapping that are not used in the circuit will be ignored. If `True` (the default), an error will be raised indicating a logic error. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – If parameters is a dict and contains parameters not present in the circuit. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If parameters is a list/array and the length mismatches the number of free parameters in the circuit. **Returns** A copy of the circuit with bound parameters if `inplace` is False, otherwise None. **Examples** Create a parameterized circuit and assign the parameters in-place. ```python from qiskit.circuit import QuantumCircuit, Parameter circuit = QuantumCircuit(2) params = [Parameter('A'), Parameter('B'), Parameter('C')] circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) circuit.draw('mpl') circuit.assign_parameters({params[0]: params[2]}, inplace=True) circuit.draw('mpl') ``` ![../\_images/qiskit-circuit-QuantumCircuit-3\_00.png](/images/api/qiskit/1.0/qiskit-circuit-QuantumCircuit-3_00.png) ![../\_images/qiskit-circuit-QuantumCircuit-3\_01.png](/images/api/qiskit/1.0/qiskit-circuit-QuantumCircuit-3_01.png) Bind the values out-of-place by list and get a copy of the original circuit. ```python from qiskit.circuit import QuantumCircuit, ParameterVector circuit = QuantumCircuit(2) params = ParameterVector('P', 2) circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) bound_circuit = circuit.assign_parameters([1, 2]) bound_circuit.draw('mpl') circuit.draw('mpl') ``` ![../\_images/qiskit-circuit-QuantumCircuit-4\_00.png](/images/api/qiskit/1.0/qiskit-circuit-QuantumCircuit-4_00.png) ![../\_images/qiskit-circuit-QuantumCircuit-4\_01.png](/images/api/qiskit/1.0/qiskit-circuit-QuantumCircuit-4_01.png) ### barrier Apply [`Barrier`](qiskit.circuit.library.Barrier ""qiskit.circuit.library.Barrier""). If `qargs` is empty, applies to all qubits in the circuit. **Parameters** * **qargs** (*QubitSpecifier*) – Specification for one or more qubit arguments. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The string label of the barrier. **Returns** handle to the added instructions. **Return type** [qiskit.circuit.InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### break\_loop Apply [`BreakLoopOp`](qiskit.circuit.BreakLoopOp ""qiskit.circuit.BreakLoopOp""). If you are using the context-manager “builder” forms of [`if_test()`](#qiskit.circuit.QuantumCircuit.if_test ""qiskit.circuit.QuantumCircuit.if_test""), [`for_loop()`](#qiskit.circuit.QuantumCircuit.for_loop ""qiskit.circuit.QuantumCircuit.for_loop"") or [`while_loop()`](#qiskit.circuit.QuantumCircuit.while_loop ""qiskit.circuit.QuantumCircuit.while_loop""), you can only call this method if you are within a loop context, because otherwise the “resource width” of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of [`if_test()`](#qiskit.circuit.QuantumCircuit.if_test ""qiskit.circuit.QuantumCircuit.if_test"") and [`if_else()`](#qiskit.circuit.QuantumCircuit.if_else ""qiskit.circuit.QuantumCircuit.if_else""). Take care that the [`BreakLoopOp`](qiskit.circuit.BreakLoopOp ""qiskit.circuit.BreakLoopOp"") instruction must span all the resources of its containing loop, not just the immediate scope. **Returns** A handle to the instruction created. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if this method was called within a builder context, but not contained within a loop. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### cast Best effort to cast value to type. Otherwise, returns the value. **Return type** *S* | *T* ### cbit\_argument\_conversion Converts several classical bit representations (such as indexes, range, etc.) into a list of classical bits. **Parameters** **clbit\_representation** (*Object*) – representation to expand **Returns** Where each tuple is a classical bit. **Return type** List([tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) ### ccx Apply [`CCXGate`](qiskit.circuit.library.CCXGate ""qiskit.circuit.library.CCXGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit1** (*QubitSpecifier*) – The qubit(s) used as the first control. * **control\_qubit2** (*QubitSpecifier*) – The qubit(s) used as the second control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### ccz Apply [`CCZGate`](qiskit.circuit.library.CCZGate ""qiskit.circuit.library.CCZGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit1** (*QubitSpecifier*) – The qubit(s) used as the first control. * **control\_qubit2** (*QubitSpecifier*) – The qubit(s) used as the second control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘10’). Defaults to controlling on the ‘11’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### ch Apply [`CHGate`](qiskit.circuit.library.CHGate ""qiskit.circuit.library.CHGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### clear Clear all instructions in self. Clearing the circuits will keep the metadata and calibrations. ### cls\_instances Return the current number of instances of this class, useful for auto naming. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### cls\_prefix Return the prefix to use for auto naming. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### compose Compose circuit with `other` circuit or instruction, optionally permuting wires. `other` can be narrower or of equal width to `self`. **Parameters** * **other** ([*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") *or*[*QuantumCircuit*](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – (sub)circuit or instruction to compose onto self. If not a [`QuantumCircuit`](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""), this can be anything that [`append`](#qiskit.circuit.QuantumCircuit.append ""qiskit.circuit.QuantumCircuit.append"") will accept. * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – qubits of self to compose onto. * **clbits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(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)"")*]*) – clbits of self to compose onto. * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, front composition will be performed. This is not possible within control-flow builder context managers. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, modify the object. Otherwise return composed circuit. * **wrap** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, wraps the other circuit into a gate (or instruction, depending on whether it contains only unitary instructions) before composing it onto self. **Returns** the composed circuit (returns None if inplace==True). **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if no correct wire mapping can be made between the two circuits, such as if `other` is wider than `self`. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if trying to emit a new circuit while `self` has a partially built control-flow context active, such as the context-manager forms of [`if_test()`](#qiskit.circuit.QuantumCircuit.if_test ""qiskit.circuit.QuantumCircuit.if_test""), [`for_loop()`](#qiskit.circuit.QuantumCircuit.for_loop ""qiskit.circuit.QuantumCircuit.for_loop"") and [`while_loop()`](#qiskit.circuit.QuantumCircuit.while_loop ""qiskit.circuit.QuantumCircuit.while_loop""). * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if trying to compose to the front of a circuit when a control-flow builder block is active; there is no clear meaning to this action. **Examples** ```python >>> lhs.compose(rhs, qubits=[3, 2], inplace=True) ``` ```python ┌───┐ ┌─────┐ ┌───┐ lqr_1_0: ───┤ H ├─── rqr_0: ──■──┤ Tdg ├ lqr_1_0: ───┤ H ├─────────────── ├───┤ ┌─┴─┐└─────┘ ├───┤ lqr_1_1: ───┤ X ├─── rqr_1: ┤ X ├─────── lqr_1_1: ───┤ X ├─────────────── ┌──┴───┴──┐ └───┘ ┌──┴───┴──┐┌───┐ lqr_1_2: ┤ U1(0.1) ├ + = lqr_1_2: ┤ U1(0.1) ├┤ X ├─────── └─────────┘ └─────────┘└─┬─┘┌─────┐ lqr_2_0: ─────■───── lqr_2_0: ─────■───────■──┤ Tdg ├ ┌─┴─┐ ┌─┴─┐ └─────┘ lqr_2_1: ───┤ X ├─── lqr_2_1: ───┤ X ├─────────────── └───┘ └───┘ lcr_0: 0 ═══════════ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════ lcr_1: 0 ═══════════════════════ ``` ### continue\_loop Apply [`ContinueLoopOp`](qiskit.circuit.ContinueLoopOp ""qiskit.circuit.ContinueLoopOp""). If you are using the context-manager “builder” forms of [`if_test()`](#qiskit.circuit.QuantumCircuit.if_test ""qiskit.circuit.QuantumCircuit.if_test""), [`for_loop()`](#qiskit.circuit.QuantumCircuit.for_loop ""qiskit.circuit.QuantumCircuit.for_loop"") or [`while_loop()`](#qiskit.circuit.QuantumCircuit.while_loop ""qiskit.circuit.QuantumCircuit.while_loop""), you can only call this method if you are within a loop context, because otherwise the “resource width” of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of [`if_test()`](#qiskit.circuit.QuantumCircuit.if_test ""qiskit.circuit.QuantumCircuit.if_test"") and [`if_else()`](#qiskit.circuit.QuantumCircuit.if_else ""qiskit.circuit.QuantumCircuit.if_else""). Take care that the [`ContinueLoopOp`](qiskit.circuit.ContinueLoopOp ""qiskit.circuit.ContinueLoopOp"") instruction must span all the resources of its containing loop, not just the immediate scope. **Returns** A handle to the instruction created. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if this method was called within a builder context, but not contained within a loop. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### control Control this circuit on `num_ctrl_qubits` qubits. **Parameters** * **num\_ctrl\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of control qubits. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – An optional label to give the controlled operation for visualization. * **ctrl\_state** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – 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** The controlled version of this circuit. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – If the circuit contains a non-unitary operation and cannot be controlled. ### copy Copy the circuit. **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 deepcopy of the current circuit, with the specified name **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### copy\_empty\_like Return a copy of self with the same structure but empty. **That structure includes:** * name, calibrations and other metadata * global phase * all the qubits and clbits, including the registers **Parameters** **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name for the copied circuit. If None, then the name stays the same. **Returns** An empty copy of self. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### count\_ops Count each operation kind in the circuit. **Returns** a breakdown of how many operations of each kind, sorted by amount. **Return type** OrderedDict ### cp Apply [`CPhaseGate`](qiskit.circuit.library.CPhaseGate ""qiskit.circuit.library.CPhaseGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** (*ParameterValueType*) – The angle of the rotation. * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### crx Apply [`CRXGate`](qiskit.circuit.library.CRXGate ""qiskit.circuit.library.CRXGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** (*ParameterValueType*) – The angle of the rotation. * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### cry Apply [`CRYGate`](qiskit.circuit.library.CRYGate ""qiskit.circuit.library.CRYGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** (*ParameterValueType*) – The angle of the rotation. * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### crz Apply [`CRZGate`](qiskit.circuit.library.CRZGate ""qiskit.circuit.library.CRZGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** (*ParameterValueType*) – The angle of the rotation. * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### cs Apply [`CSGate`](qiskit.circuit.library.CSGate ""qiskit.circuit.library.CSGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### csdg Apply [`CSdgGate`](qiskit.circuit.library.CSdgGate ""qiskit.circuit.library.CSdgGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### cswap Apply [`CSwapGate`](qiskit.circuit.library.CSwapGate ""qiskit.circuit.library.CSwapGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the control. * **target\_qubit1** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **target\_qubit2** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. `'1'`). Defaults to controlling on the `'1'` state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### csx Apply [`CSXGate`](qiskit.circuit.library.CSXGate ""qiskit.circuit.library.CSXGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### cu Apply [`CUGate`](qiskit.circuit.library.CUGate ""qiskit.circuit.library.CUGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** (*ParameterValueType*) – The $\theta$ rotation angle of the gate. * **phi** (*ParameterValueType*) – The $\phi$ rotation angle of the gate. * **lam** (*ParameterValueType*) – The $\lambda$ rotation angle of the gate. * **gamma** (*ParameterValueType*) – The global phase applied of the U gate, if applied. * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### cx Apply [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the control. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### cy Apply [`CYGate`](qiskit.circuit.library.CYGate ""qiskit.circuit.library.CYGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the controls. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### cz Apply [`CZGate`](qiskit.circuit.library.CZGate ""qiskit.circuit.library.CZGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit** (*QubitSpecifier*) – The qubit(s) used as the controls. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. * **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*) – The control state in decimal, or as a bitstring (e.g. ‘1’). Defaults to controlling on the ‘1’ state. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### dcx Apply [`DCXGate`](qiskit.circuit.library.DCXGate ""qiskit.circuit.library.DCXGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **qubit1** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. * **qubit2** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### decompose Call a decomposition pass on this circuit, to decompose one level (shallow decompose). **Parameters** * **gates\_to\_decompose** ([*type*](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"") *or*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*(*[*type*](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"")*,* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*)*) – Optional subset of gates to decompose. Can be a gate type, such as `HGate`, or a gate name, such as ‘h’, or a gate label, such as ‘My H Gate’, or a list of any combination of these. If a gate name is entered, it will decompose all gates with that name, whether the gates have labels or not. Defaults to all gates in circuit. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional number of times the circuit should be decomposed. For instance, `reps=2` equals calling `circuit.decompose().decompose()`. can decompose specific gates specific time **Returns** a circuit one level decomposed **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### delay Apply [`Delay`](qiskit.circuit.Delay ""qiskit.circuit.Delay""). If qarg is `None`, applies to all qubits. When applying to multiple qubits, delays with the same duration will be created. **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)"") *or*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – duration of the delay. * **qarg** (*Object*) – qubit argument to apply this delay. * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – unit of the duration. Supported units: `'s'`, `'ms'`, `'us'`, `'ns'`, `'ps'`, and `'dt'`. Default is `'dt'`, i.e. integer time unit depending on the target backend. **Returns** handle to the added instructions. **Return type** [qiskit.circuit.InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if arguments have bad format. ### depth >)""> Return circuit depth (i.e., length of critical path). **Parameters** **filter\_function** (*callable*) – A function to filter instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). Instructions for which the function returns False are ignored in the computation of the circuit depth. By default filters out “directives”, such as barrier or snapshot. **Returns** Depth of circuit. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") **Notes** The circuit depth and the DAG depth need not be the same. ### draw Draw the quantum circuit. Use the output parameter to choose the drawing format: **text**: ASCII art TextDrawing that can be printed in the console. **mpl**: images with color rendered purely in Python using matplotlib. **latex**: high-quality images compiled via latex. **latex\_source**: raw uncompiled latex output. Support for [`Expr`](circuit_classical#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.Expr"") nodes in conditions and `SwitchCaseOp.target` fields is preliminary and incomplete. The `text` and `mpl` drawers will make a best-effort attempt to show data dependencies, but the LaTeX-based drawers will skip these completely. **Parameters** * **output** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Select the output method to use for drawing the circuit. Valid choices are `text`, `mpl`, `latex`, `latex_source`. By default the text drawer is used unless the user config file (usually `~/.qiskit/settings.conf`) has an alternative backend set as the default. For example, `circuit_drawer = latex`. If the output kwarg is set, that backend will always be used over the default in the user config file. * **scale** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – Scale of image to draw (shrink if `< 1.0`). Only used by the `mpl`, `latex` and `latex_source` outputs. Defaults to `1.0`. * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – File path to save image to. Defaults to `None` (result not saved in a file). * **style** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Style name, file name of style JSON file, or a dictionary specifying the style. * The supported style names are `""iqp""` (default), `""iqp-dark""`, `""clifford""`, `""textbook""` and `""bw""`. * If given a JSON file, e.g. `my_style.json` or `my_style` (the `.json` extension may be omitted), this function attempts to load the style dictionary from that location. Note, that the JSON file must completely specify the visualization specifications. The file is searched for in `qiskit/visualization/circuit/styles`, the current working directory, and the location specified in `~/.qiskit/settings.conf`. * If a dictionary, every entry overrides the default configuration. If the `""name""` key is given, the default configuration is given by that style. For example, `{""name"": ""textbook"", ""subfontsize"": 5}` loads the `""texbook""` style and sets the subfontsize (e.g. the gate angles) to `5`. * If `None` the default style `""iqp""` is used or, if given, the default style specified in `~/.qiskit/settings.conf`. * **interactive** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – When set to `True`, show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the text or the `latex_source` output type this has no effect and will be silently ignored. Defaults to `False`. * **reverse\_bits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – When set to `True`, reverse the bit order inside registers for the output visualization. Defaults to `False` unless the user config file (usually `~/.qiskit/settings.conf`) has an alternative value set. For example, `circuit_reverse_bits = True`. * **plot\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Enable/disable drawing barriers in the output circuit. Defaults to `True`. * **justify** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Options are `left`, `right` or `none`. If anything else is supplied, it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. `none` results in each gate being placed in its own column. * **vertical\_compression** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – `high`, `medium` or `low`. It merges the lines generated by the text output so the drawing will take less vertical room. Default is `medium`. Only used by the `text` output, will be silently ignored otherwise. * **idle\_wires** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Include idle wires (wires with no circuit elements) in output visualization. Default is `True`. * **with\_layout** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Include layout information, with labels on the physical layout. Default is `True`. * **fold** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Sets pagination. It can be disabled using -1. In `text`, sets the length of the lines. This is useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using `shutil.get_terminal_size()`. However, if running in jupyter, the default line length is set to 80 characters. In `mpl`, it is the number of (visual) layers before folding. Default is 25. * **ax** (*Any | None*) – Only used by the mpl backend. An optional `matplotlib.axes.Axes` object to be used for the visualization output. If none is specified, a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. * **initial\_state** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Adds $|0\rangle$ in the beginning of the qubit wires and $0$ to classical wires. Default is `False`. * **cregbundle** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If set to `True`, bundle classical registers. Default is `True`, except for when `output` is set to `""text""`. * **wire\_order** ([*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 integers used to reorder the display of the bits. The list must have an entry for every bit with the bits in the range 0 to (`num_qubits` + `num_clbits`). * **expr\_len** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of characters to display if an [`Expr`](circuit_classical#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.Expr"") is used for the condition in a [`ControlFlowOp`](qiskit.circuit.ControlFlowOp ""qiskit.circuit.ControlFlowOp""). If this number is exceeded, the string will be truncated at that number and ‘…’ added to the end. **Returns** `TextDrawing` or `matplotlib.figure` or `PIL.Image` or [`str`](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)""): * **`TextDrawing` (if `output='text'`)** A drawing that can be printed as ascii art. * **`matplotlib.figure.Figure` (if `output='mpl'`)** A matplotlib figure object for the circuit diagram. * **`PIL.Image` (if `output='latex`’)** An in-memory representation of the image of the circuit diagram. * **`str` (if `output='latex_source'`)** The LaTeX source code for visualizing the circuit diagram. **Raises** * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – when an invalid output method is selected * [**ImportError**](https://docs.python.org/3/library/exceptions.html#ImportError ""(in Python v3.12)"") – when the output methods requires non-installed libraries. **Example** ```python from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qc = QuantumCircuit(1, 1) qc.h(0) qc.measure(0, 0) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'}) ``` ![../\_images/qiskit-circuit-QuantumCircuit-5.png](/images/api/qiskit/1.0/qiskit-circuit-QuantumCircuit-5.png) ### ecr Apply [`ECRGate`](qiskit.circuit.library.ECRGate ""qiskit.circuit.library.ECRGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **qubit1** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubits to apply the gate to. * **qubit2** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubits to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### find\_bit Find locations in the circuit which can be used to reference a given [`Bit`](qiskit.circuit.Bit ""qiskit.circuit.Bit""). **Parameters** **bit** ([*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")) – The bit to locate. **Returns** **A 2-tuple. The first element (`index`)** contains the index at which the `Bit` can be found (in either [`qubits`](#qiskit.circuit.QuantumCircuit.qubits ""qiskit.circuit.QuantumCircuit.qubits""), [`clbits`](#qiskit.circuit.QuantumCircuit.clbits ""qiskit.circuit.QuantumCircuit.clbits""), depending on its type). The second element (`registers`) is a list of `(register, index)` pairs with an entry for each [`Register`](qiskit.circuit.Register ""qiskit.circuit.Register"") in the circuit which contains the [`Bit`](qiskit.circuit.Bit ""qiskit.circuit.Bit"") (and the index in the [`Register`](qiskit.circuit.Register ""qiskit.circuit.Register"") at which it can be found). **Return type** namedtuple([int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)""), List\[Tuple([Register](qiskit.circuit.Register ""qiskit.circuit.Register""), [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)""))]) **Notes** The circuit index of an [`AncillaQubit`](qiskit.circuit.AncillaQubit ""qiskit.circuit.AncillaQubit"") will be its index in [`qubits`](#qiskit.circuit.QuantumCircuit.qubits ""qiskit.circuit.QuantumCircuit.qubits""), not [`ancillas`](#qiskit.circuit.QuantumCircuit.ancillas ""qiskit.circuit.QuantumCircuit.ancillas""). **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – If the supplied [`Bit`](qiskit.circuit.Bit ""qiskit.circuit.Bit"") was of an unknown type. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – If the supplied [`Bit`](qiskit.circuit.Bit ""qiskit.circuit.Bit"") could not be found on the circuit. **Return type** *BitLocations* ### for\_loop Create a `for` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of `label`), it will create a [`ForLoopOp`](qiskit.circuit.ForLoopOp ""qiskit.circuit.ForLoopOp"") with the given `body`. If `body` (and `qubits` and `clbits`) are *not* passed, then this acts as a context manager, which, when entered, provides a loop variable (unless one is given, in which case it will be reused) and will automatically build a [`ForLoopOp`](qiskit.circuit.ForLoopOp ""qiskit.circuit.ForLoopOp"") when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example: ```python from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)) as i: qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) ``` **Parameters** * **indexset** (*Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – A collection of integers to loop over. Always necessary. * **loop\_parameter** (*Optional\[*[*Parameter*](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")*]*) – The parameter used within `body` to which the values from `indexset` will be assigned. In the context-manager form, if this argument is not supplied, then a loop parameter will be allocated for you and returned as the value of the `with` statement. This will only be bound into the circuit if it is used within the body. If this argument is `None` in the manual form of this method, `body` will be repeated once for each of the items in `indexset` but their values will be ignored. * **body** (*Optional\[*[*QuantumCircuit*](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]*) – The loop body to be repeatedly executed. Omit this to use the context-manager mode. * **qubits** (*Optional\[Sequence\[QubitSpecifier]]*) – The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. * **clbits** (*Optional\[Sequence\[ClbitSpecifier]]*) – The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. * **label** (*Optional\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – The string label of the instruction in the circuit. **Returns** depending on the call signature, either a context manager for creating the for loop (it will automatically be added to the circuit at the end of the block), or an [`InstructionSet`](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") handle to the appended loop operation. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") or ForLoopContext **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if an incorrect calling convention is used. ### from\_instructions Construct a circuit from an iterable of CircuitInstructions. **Parameters** * **instructions** (*Iterable\[*[*CircuitInstruction*](qiskit.circuit.CircuitInstruction ""qiskit.circuit.CircuitInstruction"") *|*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")*] |* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")*, Iterable\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*]] |* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")*, Iterable\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*], Iterable\[*[*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*]]]*) – The instructions to add to the circuit. * **qubits** (*Iterable\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*]*) – Any qubits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of qubits. * **clbits** (*Iterable\[*[*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*]*) – Any classical bits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of classical bits. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The name of the circuit. * **global\_phase** (*ParameterValueType*) – The global phase of the circuit in radians. * **metadata** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *| None*) – Arbitrary key value metadata to associate with the circuit. **Returns** The quantum circuit. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### from\_qasm\_file Read an OpenQASM 2.0 program from a file and convert to an instance of [`QuantumCircuit`](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). **Parameters** **path** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Path to the file for an OpenQASM 2 program **Returns** The QuantumCircuit object for the input OpenQASM 2. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") [`qasm2.load()`](qasm2#qiskit.qasm2.load ""qiskit.qasm2.load""): the complete interface to the OpenQASM 2 importer. ### from\_qasm\_str Convert a string containing an OpenQASM 2.0 program to a [`QuantumCircuit`](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). **Parameters** **qasm\_str** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A string containing an OpenQASM 2.0 program. **Returns** The QuantumCircuit object for the input OpenQASM 2 **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") [`qasm2.loads()`](qasm2#qiskit.qasm2.loads ""qiskit.qasm2.loads""): the complete interface to the OpenQASM 2 importer. ### get\_instructions Get instructions matching name. **Parameters** **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of instruction to. **Returns** list of (instruction, qargs, cargs). **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")([tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) ### get\_parameter Retrieve a compile-time parameter that is accessible in this circuit scope by name. **Parameters** * **name** – the name of the parameter to retrieve. * **default** – if given, this value will be returned if the parameter is not present. If it is not given, a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError ""(in Python v3.12)"") is raised instead. **Returns** The corresponding parameter. **Raises** [**KeyError**](https://docs.python.org/3/library/exceptions.html#KeyError ""(in Python v3.12)"") – if no default is given, but the parameter does not exist in the circuit. **Examples** Retrieve a parameter by name from a circuit: ```python from qiskit.circuit import QuantumCircuit, Parameter my_param = Parameter(""my_param"") # Create a parametrised circuit. qc = QuantumCircuit(1) qc.rx(my_param, 0) # We can use 'my_param' as a parameter, but let's say we've lost the Python object # and need to retrieve it. my_param_again = qc.get_parameter(""my_param"") assert my_param is my_param_again ``` Get a variable from a circuit by name, returning some default if it is not present: ```python assert qc.get_parameter(""my_param"", None) is my_param assert qc.get_parameter(""unknown_param"", None) is None ``` ### h Apply [`HGate`](qiskit.circuit.library.HGate ""qiskit.circuit.library.HGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### has\_calibration\_for Return True if the circuit has a calibration defined for the instruction context. In this case, the operation does not need to be translated to the device basis. ### has\_parameter Check whether a parameter object exists in this circuit. **Parameters** **name\_or\_param** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*Parameter*](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")) – the parameter, or name of a parameter to check. If this is a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") node, the parameter must be exactly the given one for this function to return `True`. **Returns** whether a matching parameter is assignable in this circuit. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") **[`QuantumCircuit.get_parameter()`](#qiskit.circuit.QuantumCircuit.get_parameter ""qiskit.circuit.QuantumCircuit.get_parameter"")** Retrieve the [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") instance from this circuit by name. ### has\_register Test if this circuit has the register r. **Parameters** **register** ([*Register*](qiskit.circuit.Register ""qiskit.circuit.Register"")) – a quantum or classical register. **Returns** True if the register is contained in this circuit. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### id Apply [`IGate`](qiskit.circuit.library.IGate ""qiskit.circuit.library.IGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### if\_else Apply [`IfElseOp`](qiskit.circuit.IfElseOp ""qiskit.circuit.IfElseOp""). This method does not have an associated context-manager form, because it is already handled by the [`if_test()`](#qiskit.circuit.QuantumCircuit.if_test ""qiskit.circuit.QuantumCircuit.if_test"") method. You can use the `else` part of that with something such as: ```python from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) with qc.if_test((bits[2], 0)) as else_: qc.h(0) with else_: qc.x(0) ``` **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)"")*] |* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*,* [*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*]*) – 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"")) – The circuit body to be run if `condition` is true. * **false\_body** ([*QuantumCircuit*](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – The circuit to be run if `condition` is false. * **qubits** (*Sequence\[QubitSpecifier]*) – The circuit qubits over which the if/else should be run. * **clbits** (*Sequence\[ClbitSpecifier]*) – The circuit clbits over which the if/else should be run. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the instruction in the circuit. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – If the provided condition references Clbits outside the enclosing circuit. **Returns** A handle to the instruction created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### if\_test Create an `if` statement on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of `label`), it will create a [`IfElseOp`](qiskit.circuit.IfElseOp ""qiskit.circuit.IfElseOp"") with the given `true_body`, and there will be no branch for the `false` condition (see also the [`if_else()`](#qiskit.circuit.QuantumCircuit.if_else ""qiskit.circuit.QuantumCircuit.if_else"") method). However, if `true_body` (and `qubits` and `clbits`) are *not* passed, then this acts as a context manager, which can be used to build `if` statements. The return value of the `with` statement is a chainable context manager, which can be used to create subsequent `else` blocks. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example: ```python from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Qubit(), Clbit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.h(0) qc.cx(0, 1) qc.measure(0, 1) with qc.if_test((bits[3], 0)) as else_: qc.x(2) with else_: qc.h(2) qc.z(2) ``` **Parameters** * **condition** (*Tuple\[Union\[*[*ClassicalRegister*](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"")*,* [*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*],* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – 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** (*Optional\[*[*QuantumCircuit*](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]*) – The circuit body to be run if `condition` is true. * **qubits** (*Optional\[Sequence\[QubitSpecifier]]*) – The circuit qubits over which the if/else should be run. * **clbits** (*Optional\[Sequence\[ClbitSpecifier]]*) – The circuit clbits over which the if/else should be run. * **label** (*Optional\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – The string label of the instruction in the circuit. **Returns** depending on the call signature, either a context manager for creating the `if` block (it will automatically be added to the circuit at the end of the block), or an [`InstructionSet`](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") handle to the appended conditional operation. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") or IfContext **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – If the provided condition references Clbits outside the enclosing circuit. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if an incorrect calling convention is used. **Returns** A handle to the instruction created. ### initialize Initialize qubits in a specific state. Qubit initialization is done by first resetting the qubits to $|0\rangle$ followed by calling [`StatePreparation`](qiskit.circuit.library.StatePreparation ""qiskit.circuit.library.StatePreparation"") class to prepare the qubits in a specified state. Both these steps are included in the [`Initialize`](qiskit.circuit.library.Initialize ""qiskit.circuit.library.Initialize"") instruction. **Parameters** * **params** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *| Sequence\[*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*] |* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The state to initialize to, can be either of the following. * Statevector or vector of complex amplitudes to initialize to. * Labels of basis states of the Pauli eigenstates Z, X, Y. See [`Statevector.from_label()`](qiskit.quantum_info.Statevector#from_label ""qiskit.quantum_info.Statevector.from_label""). Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label ‘01’ initializes the qubit zero to $|1\rangle$ and the qubit one to $|0\rangle$. * An integer that is used as a bitmap indicating which qubits to initialize to $|1\rangle$. Example: setting params to 5 would initialize qubit 0 and qubit 2 to $|1\rangle$ and qubit 1 to $|0\rangle$. * **qubits** (*Sequence\[QubitSpecifier] | None*) – Qubits to initialize. If `None` the initialization is applied to all qubits in the circuit. * **normalize** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to normalize an input array to a unit vector. **Returns** A handle to the instructions created. **Examples** Prepare a qubit in the state $(|0\rangle - |1\rangle) / \sqrt{2}$. ```python import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(1) circuit.initialize([1/np.sqrt(2), -1/np.sqrt(2)], 0) circuit.draw() ``` output: ```python ┌──────────────────────────────┐ q_0: ┤ Initialize(0.70711,-0.70711) ├ └──────────────────────────────┘ ``` Initialize from a string two qubits in the state $|10\rangle$. The order of the labels is reversed with respect to qubit index. More information about labels for basis states are in [`Statevector.from_label()`](qiskit.quantum_info.Statevector#from_label ""qiskit.quantum_info.Statevector.from_label""). ```python import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.initialize('01', circuit.qubits) circuit.draw() ``` output: ```python ┌──────────────────┐ q_0: ┤0 ├ │ Initialize(0,1) │ q_1: ┤1 ├ └──────────────────┘ ``` Initialize two qubits from an array of complex amplitudes. ```python import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits) circuit.draw() ``` output: ```python ┌────────────────────────────────────┐ q_0: ┤0 ├ │ Initialize(0,0.70711,-0.70711j,0) │ q_1: ┤1 ├ └────────────────────────────────────┘ ``` ### inverse Invert (take adjoint of) this circuit. This is done by recursively inverting all gates. **Parameters** **annotated** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – indicates whether the inverse gate can be implemented as an annotated gate. **Returns** the inverted circuit **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if the circuit cannot be inverted. **Examples** input: ```python ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ ``` output: ```python ┌───┐ q_0: ──────■──────┤ H ├ ┌─────┴─────┐└───┘ q_1: ┤ RX(-1.57) ├───── └───────────┘ ``` ### iswap Apply [`iSwapGate`](qiskit.circuit.library.iSwapGate ""qiskit.circuit.library.iSwapGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **qubit1** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubits to apply the gate to. * **qubit2** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubits to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### mcp Apply [`MCPhaseGate`](qiskit.circuit.library.MCPhaseGate ""qiskit.circuit.library.MCPhaseGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **lam** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The angle of the rotation. * **control\_qubits** ([*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – The qubits used as the controls. * **target\_qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) targeted by the gate. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### mcrx Apply Multiple-Controlled X rotation gate **Parameters** * **self** ([*QuantumCircuit*](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – The QuantumCircuit object to apply the mcrx gate on. * **theta** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – angle theta * **q\_controls** ([*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.QuantumRegister"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*(*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*)*) – The list of control qubits * **q\_target** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")) – The target qubit * **use\_basis\_gates** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – use p, u, cx **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – parameter errors ### mcry Apply Multiple-Controlled Y rotation gate **Parameters** * **self** ([*QuantumCircuit*](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – The QuantumCircuit object to apply the mcry gate on. * **theta** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – angle theta * **q\_controls** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*(*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*)*) – The list of control qubits * **q\_target** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")) – The target qubit * **q\_ancillae** ([*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.QuantumRegister"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*(*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.QuantumRegister"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*)*) – The list of ancillary qubits. * **mode** (*string*) – The implementation mode to use * **use\_basis\_gates** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – use p, u, cx **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – parameter errors ### mcrz Apply Multiple-Controlled Z rotation gate **Parameters** * **self** ([*QuantumCircuit*](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – The QuantumCircuit object to apply the mcrz gate on. * **lam** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – angle lambda * **q\_controls** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*(*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*)*) – The list of control qubits * **q\_target** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")) – The target qubit * **use\_basis\_gates** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – use p, u, cx **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – parameter errors ### mcx Apply [`MCXGate`](qiskit.circuit.library.MCXGate ""qiskit.circuit.library.MCXGate""). The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: * `'noancilla'`: Requires 0 ancilla qubits. * `'recursion'`: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. * `'v-chain'`: Requires 2 less ancillas than the number of control qubits. * `'v-chain-dirty'`: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubits** (*Sequence\[QubitSpecifier]*) – The qubits used as the controls. * **target\_qubit** (*QubitSpecifier*) – The qubit(s) targeted by the gate. * **ancilla\_qubits** (*QubitSpecifier | Sequence\[QubitSpecifier] | None*) – The qubits used as the ancillae, if the mode requires them. * **mode** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The choice of mode, explained further above. **Returns** A handle to the instructions created. **Raises** * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – if the given mode is not known, or if too few ancilla qubits are passed. * [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – if no ancilla qubits are passed, but some are needed. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### measure Measure a quantum bit (`qubit`) in the Z basis into a classical bit (`cbit`). When a quantum state is measured, a qubit is projected in the computational (Pauli Z) basis to either $\lvert 0 \rangle$ or $\lvert 1 \rangle$. The classical bit `cbit` indicates the result of that projection as a `0` or a `1` respectively. This operation is non-reversible. **Parameters** * **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – qubit(s) to measure. * **cbit** ([*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.classicalregister.Clbit"") *|*[*ClassicalRegister*](qiskit.circuit.ClassicalRegister ""qiskit.circuit.classicalregister.ClassicalRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.classicalregister.Clbit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – classical bit(s) to place the measurement result(s) in. **Returns** handle to the added instructions. **Return type** [qiskit.circuit.InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if arguments have bad format. **Examples** In this example, a qubit is measured and the result of that measurement is stored in the classical bit (usually expressed in diagrams as a double line): ```python from qiskit import QuantumCircuit circuit = QuantumCircuit(1, 1) circuit.h(0) circuit.measure(0, 0) circuit.draw() ``` ```python ┌───┐┌─┐ q: ┤ H ├┤M├ └───┘└╥┘ c: 1/══════╩═ 0 ``` It is possible to call `measure` with lists of `qubits` and `cbits` as a shortcut for one-to-one measurement. These two forms produce identical results: ```python circuit = QuantumCircuit(2, 2) circuit.measure([0,1], [0,1]) ``` ```python circuit = QuantumCircuit(2, 2) circuit.measure(0, 0) circuit.measure(1, 1) ``` Instead of lists, you can use [`QuantumRegister`](qiskit.circuit.QuantumRegister ""qiskit.circuit.QuantumRegister"") and [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"") under the same logic. ```python from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qreg = QuantumRegister(2, ""qreg"") creg = ClassicalRegister(2, ""creg"") circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg, creg) ``` This is equivalent to: ```python circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg[0], creg[0]) circuit.measure(qreg[1], creg[1]) ``` ### measure\_active Adds measurement to all non-idle qubits. Creates a new ClassicalRegister with a size equal to the number of non-idle qubits being measured. Returns a new circuit with measurements if inplace=False. **Parameters** **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – All measurements inplace or return new circuit. **Returns** Returns circuit with measurements when inplace = False. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### measure\_all Adds measurement to all qubits. By default, adds new classical bits in a [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"") to store these measurements. If `add_bits=False`, the results of the measurements will instead be stored in the already existing classical bits, with qubit `n` being measured into classical bit `n`. Returns a new circuit with measurements if `inplace=False`. **Parameters** * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – All measurements inplace or return new circuit. * **add\_bits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to add new bits to store the results. **Returns** Returns circuit with measurements when `inplace=False`. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `add_bits=False` but there are not enough classical bits. ### ms Apply [`MSGate`](qiskit.circuit.library.MSGate ""qiskit.circuit.library.MSGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The angle of the rotation. * **qubits** ([*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – The qubits to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### num\_connected\_components How many non-entangled subcircuits can the circuit be factored to. **Parameters** **unitary\_only** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Compute only unitary part of graph. **Returns** Number of connected components in circuit. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### num\_nonlocal\_gates Return number of non-local gates (i.e. involving 2+ qubits). Conditional nonlocal gates are also included. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### num\_tensor\_factors Computes the number of tensor factors in the unitary (quantum) part of the circuit only. **Notes** This is here for backwards compatibility, and will be removed in a future release of Qiskit. You should call num\_unitary\_factors instead. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### num\_unitary\_factors Computes the number of tensor factors in the unitary (quantum) part of the circuit only. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### p Apply [`PhaseGate`](qiskit.circuit.library.PhaseGate ""qiskit.circuit.library.PhaseGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – THe angle of the rotation. * **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### pauli Apply [`PauliGate`](qiskit.circuit.library.PauliGate ""qiskit.circuit.library.PauliGate""). **Parameters** * **pauli\_string** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A string representing the Pauli operator to apply, e.g. ‘XX’. * **qubits** ([*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – The qubits to apply this gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### power Raise this circuit to the power of `power`. If `power` is a positive integer and `matrix_power` is `False`, this implementation defaults to calling `repeat`. Otherwise, if the circuit is unitary, the matrix is computed to calculate the matrix power. **Parameters** * **power** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The power to raise this circuit to. * **matrix\_power** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, the circuit is converted to a matrix and then the matrix power is computed. If False, and `power` is a positive integer, the implementation defaults to `repeat`. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – If the circuit needs to be converted to a gate but it is not unitary. **Returns** A circuit implementing this circuit raised to the power of `power`. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### prepare\_state Prepare qubits in a specific state. This class implements a state preparing unitary. Unlike [`initialize()`](#qiskit.circuit.QuantumCircuit.initialize ""qiskit.circuit.QuantumCircuit.initialize"") it does not reset the qubits first. **Parameters** * **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *| Sequence\[*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*] |* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The state to initialize to, can be either of the following. * Statevector or vector of complex amplitudes to initialize to. * Labels of basis states of the Pauli eigenstates Z, X, Y. See [`Statevector.from_label()`](qiskit.quantum_info.Statevector#from_label ""qiskit.quantum_info.Statevector.from_label""). Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label ‘01’ initializes the qubit zero to $|1\rangle$ and the qubit one to $|0\rangle$. * An integer that is used as a bitmap indicating which qubits to initialize to $|1\rangle$. Example: setting params to 5 would initialize qubit 0 and qubit 2 to $|1\rangle$ and qubit 1 to $|0\rangle$. * **qubits** (*Sequence\[QubitSpecifier] | None*) – Qubits to initialize. If `None` the initialization is applied to all qubits in the circuit. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – An optional label for the gate * **normalize** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to normalize an input array to a unit vector. **Returns** A handle to the instruction that was just initialized **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") **Examples** Prepare a qubit in the state $(|0\rangle - |1\rangle) / \sqrt{2}$. ```python import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(1) circuit.prepare_state([1/np.sqrt(2), -1/np.sqrt(2)], 0) circuit.draw() ``` output: ```python ┌─────────────────────────────────────┐ q_0: ┤ State Preparation(0.70711,-0.70711) ├ └─────────────────────────────────────┘ ``` Prepare from a string two qubits in the state $|10\rangle$. The order of the labels is reversed with respect to qubit index. More information about labels for basis states are in [`Statevector.from_label()`](qiskit.quantum_info.Statevector#from_label ""qiskit.quantum_info.Statevector.from_label""). ```python import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.prepare_state('01', circuit.qubits) circuit.draw() ``` output: ```python ┌─────────────────────────┐ q_0: ┤0 ├ │ State Preparation(0,1) │ q_1: ┤1 ├ └─────────────────────────┘ ``` Initialize two qubits from an array of complex amplitudes .. code-block: ```python import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.prepare_state([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits) circuit.draw() ``` output: ```python ┌───────────────────────────────────────────┐ q_0: ┤0 ├ │ State Preparation(0,0.70711,-0.70711j,0) │ q_1: ┤1 ├ └───────────────────────────────────────────┘ ``` ### qbit\_argument\_conversion Converts several qubit representations (such as indexes, range, etc.) into a list of qubits. **Parameters** **qubit\_representation** (*Object*) – representation to expand **Returns** the resolved instances of the qubits. **Return type** List([Qubit](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")) ### qubit\_duration Return the duration between the start and stop time of the first and last instructions, excluding delays, over the supplied qubits. Its time unit is `self.unit`. **Parameters** **\*qubits** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Qubits within `self` to include. **Returns** Return the duration between the first start and last stop time of non-delay instructions **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### qubit\_start\_time Return the start time of the first instruction, excluding delays, over the supplied qubits. Its time unit is `self.unit`. Return 0 if there are no instructions over qubits **Parameters** * **\*qubits** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Qubits within `self` to include. Integers are allowed for qubits, indicating * **self.qubits.** (*indices of*) – **Returns** Return the start time of the first instruction, excluding delays, over the qubits **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `self` is a not-yet scheduled circuit. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### qubit\_stop\_time Return the stop time of the last instruction, excluding delays, over the supplied qubits. Its time unit is `self.unit`. Return 0 if there are no instructions over qubits **Parameters** * **\*qubits** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Qubits within `self` to include. Integers are allowed for qubits, indicating * **self.qubits.** (*indices of*) – **Returns** Return the stop time of the last instruction, excluding delays, over the qubits **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `self` is a not-yet scheduled circuit. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### r Apply [`RGate`](qiskit.circuit.library.RGate ""qiskit.circuit.library.RGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The angle of the rotation. * **phi** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The angle of the axis of rotation in the x-y plane. * **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### rcccx Apply [`RC3XGate`](qiskit.circuit.library.RC3XGate ""qiskit.circuit.library.RC3XGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit1** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) used as the first control. * **control\_qubit2** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) used as the second control. * **control\_qubit3** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) used as the third control. * **target\_qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) targeted by the gate. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### rccx Apply [`RCCXGate`](qiskit.circuit.library.RCCXGate ""qiskit.circuit.library.RCCXGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **control\_qubit1** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) used as the first control. * **control\_qubit2** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) used as the second control. * **target\_qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) targeted by the gate. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### remove\_final\_measurements Removes final measurements and barriers on all qubits if they are present. Deletes the classical registers that were used to store the values from these measurements that become idle as a result of this operation, and deletes classical bits that are referenced only by removed registers, or that aren’t referenced at all but have become idle as a result of this operation. Measurements and barriers are considered final if they are followed by no other operations (aside from other measurements or barriers.) **Parameters** **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – All measurements removed inplace or return new circuit. **Returns** Returns the resulting circuit when `inplace=False`, else None. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### repeat Repeat this circuit `reps` times. **Parameters** **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – How often this circuit should be repeated. **Returns** A circuit containing `reps` repetitions of this circuit. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### reset Reset the quantum bit(s) to their default state. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – qubit(s) to reset. **Returns** handle to the added instruction. **Return type** [qiskit.circuit.InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### reverse\_bits Return a circuit with the opposite order of wires. The circuit is “vertically” flipped. If a circuit is defined over multiple registers, the resulting circuit will have the same registers but with their order flipped. This method is useful for converting a circuit written in little-endian convention to the big-endian equivalent, and vice versa. **Returns** the circuit with reversed bit order. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **Examples** input: ```python ┌───┐ a_0: ┤ H ├──■───────────────── └───┘┌─┴─┐ a_1: ─────┤ X ├──■──────────── └───┘┌─┴─┐ a_2: ──────────┤ X ├──■─────── └───┘┌─┴─┐ b_0: ───────────────┤ X ├──■── └───┘┌─┴─┐ b_1: ────────────────────┤ X ├ └───┘ ``` output: ```python ┌───┐ b_0: ────────────────────┤ X ├ ┌───┐└─┬─┘ b_1: ───────────────┤ X ├──■── ┌───┐└─┬─┘ a_0: ──────────┤ X ├──■─────── ┌───┐└─┬─┘ a_1: ─────┤ X ├──■──────────── ┌───┐└─┬─┘ a_2: ┤ H ├──■───────────────── └───┘ ``` ### reverse\_ops Reverse the circuit by reversing the order of instructions. This is done by recursively reversing all instructions. It does not invert (adjoint) any gate. **Returns** the reversed circuit. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **Examples** input: ```python ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ ``` output: ```python ┌───┐ q_0: ─────■──────┤ H ├ ┌────┴─────┐└───┘ q_1: ┤ RX(1.57) ├───── └──────────┘ ``` ### rv Apply [`RVGate`](qiskit.circuit.library.RVGate ""qiskit.circuit.library.RVGate""). For the full matrix form of this gate, see the underlying gate documentation. Rotation around an arbitrary rotation axis $v$, where $|v|$ is the angle of rotation in radians. **Parameters** * **vx** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – x-component of the rotation axis. * **vy** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – y-component of the rotation axis. * **vz** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – z-component of the rotation axis. * **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### rx Apply [`RXGate`](qiskit.circuit.library.RXGate ""qiskit.circuit.library.RXGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** (*ParameterValueType*) – The rotation angle of the gate. * **qubit** (*QubitSpecifier*) – The qubit(s) to apply the gate to. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### rxx Apply [`RXXGate`](qiskit.circuit.library.RXXGate ""qiskit.circuit.library.RXXGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The angle of the rotation. * **qubit1** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. * **qubit2** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### ry Apply [`RYGate`](qiskit.circuit.library.RYGate ""qiskit.circuit.library.RYGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** (*ParameterValueType*) – The rotation angle of the gate. * **qubit** (*QubitSpecifier*) – The qubit(s) to apply the gate to. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### ryy Apply [`RYYGate`](qiskit.circuit.library.RYYGate ""qiskit.circuit.library.RYYGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The rotation angle of the gate. * **qubit1** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. * **qubit2** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### rz Apply [`RZGate`](qiskit.circuit.library.RZGate ""qiskit.circuit.library.RZGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **phi** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The rotation angle of the gate. * **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### rzx Apply [`RZXGate`](qiskit.circuit.library.RZXGate ""qiskit.circuit.library.RZXGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The rotation angle of the gate. * **qubit1** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. * **qubit2** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### rzz Apply [`RZZGate`](qiskit.circuit.library.RZZGate ""qiskit.circuit.library.RZZGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The rotation angle of the gate. * **qubit1** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. * **qubit2** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### s Apply [`SGate`](qiskit.circuit.library.SGate ""qiskit.circuit.library.SGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### sdg Apply [`SdgGate`](qiskit.circuit.library.SdgGate ""qiskit.circuit.library.SdgGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### size >)""> Returns total number of instructions in circuit. **Parameters** **filter\_function** (*callable*) – a function to filter out some instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). By default filters out “directives”, such as barrier or snapshot. **Returns** Total number of gate operations. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### swap Apply [`SwapGate`](qiskit.circuit.library.SwapGate ""qiskit.circuit.library.SwapGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **qubit1** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubits to apply the gate to. * **qubit2** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubits to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### switch Create a `switch`/`case` structure on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of `label`), it will create a [`SwitchCaseOp`](qiskit.circuit.SwitchCaseOp ""qiskit.circuit.SwitchCaseOp"") with the given case structure. If `cases` (and `qubits` and `clbits`) are *not* passed, then this acts as a context manager, which will automatically build a [`SwitchCaseOp`](qiskit.circuit.SwitchCaseOp ""qiskit.circuit.SwitchCaseOp"") when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage: ```python from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister qreg = QuantumRegister(3) creg = ClassicalRegister(3) qc = QuantumCircuit(qreg, creg) qc.h([0, 1, 2]) qc.measure([0, 1, 2], [0, 1, 2]) with qc.switch(creg) as case: with case(0): qc.x(0) with case(1, 2): qc.z(1) with case(case.DEFAULT): qc.cx(0, 1) ``` **Parameters** * **target** (*Union\[*[*ClassicalRegister*](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"")*,* [*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*]*) – The classical value to switch one. This must be integer-like. * **cases** (*Iterable\[Tuple\[*[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")*,* [*QuantumCircuit*](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]]*) – A sequence of case specifiers. Each tuple defines one case body (the second item). The first item of the tuple can be either a single integer value, the special value [`CASE_DEFAULT`](circuit#qiskit.circuit.CASE_DEFAULT ""qiskit.circuit.CASE_DEFAULT""), or a tuple of several integer values. Each of the integer values will be tried in turn; control will then pass to the body corresponding to the first match. [`CASE_DEFAULT`](circuit#qiskit.circuit.CASE_DEFAULT ""qiskit.circuit.CASE_DEFAULT"") matches all possible values. Omit in context-manager form. * **qubits** (*Sequence\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*]*) – The circuit qubits over which all case bodies execute. Omit in context-manager form. * **clbits** (*Sequence\[*[*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*]*) – The circuit clbits over which all case bodies execute. Omit in context-manager form. * **label** (*Optional\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – The string label of the instruction in the circuit. **Returns** If used in context-manager mode, then this should be used as a `with` resource, which will return an object that can be repeatedly entered to produce cases for the switch statement. If the full form is used, then this returns a handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") or SwitchCaseContext **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if an incorrect calling convention is used. ### sx Apply [`SXGate`](qiskit.circuit.library.SXGate ""qiskit.circuit.library.SXGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### sxdg Apply [`SXdgGate`](qiskit.circuit.library.SXdgGate ""qiskit.circuit.library.SXdgGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### t Apply [`TGate`](qiskit.circuit.library.TGate ""qiskit.circuit.library.TGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### tdg Apply [`TdgGate`](qiskit.circuit.library.TdgGate ""qiskit.circuit.library.TdgGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### tensor Tensor `self` with `other`. Remember that in the little-endian convention the leftmost operation will be at the bottom of the circuit. See also [the docs](/build/circuit-construction) for more information. ```python ┌────────┐ ┌─────┐ ┌─────┐ q_0: ┤ bottom ├ ⊗ q_0: ┤ top ├ = q_0: ─┤ top ├── └────────┘ └─────┘ ┌┴─────┴─┐ q_1: ┤ bottom ├ └────────┘ ``` **Parameters** * **other** ([*QuantumCircuit*](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – The other circuit to tensor this circuit with. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, modify the object. Otherwise return composed circuit. **Return type** [*QuantumCircuit*](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") | None **Examples** ```python from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl') ``` ![../\_images/qiskit-circuit-QuantumCircuit-6.png](/images/api/qiskit/1.0/qiskit-circuit-QuantumCircuit-6.png) **Returns** The tensored circuit (returns None if inplace==True). **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### to\_gate Create a Gate out of this circuit. **Parameters** * **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. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Optional gate label. **Returns** a composite gate encapsulating this circuit (can be decomposed back) **Return type** [Gate](qiskit.circuit.Gate ""qiskit.circuit.Gate"") ### to\_instruction Create an Instruction out of this circuit. **Parameters** * **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. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Optional gate label. **Returns** a composite instruction encapsulating this circuit (can be decomposed back) **Return type** [qiskit.circuit.Instruction](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") ### u Apply [`UGate`](qiskit.circuit.library.UGate ""qiskit.circuit.library.UGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **theta** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The $\theta$ rotation angle of the gate. * **phi** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The $\phi$ rotation angle of the gate. * **lam** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The $\lambda$ rotation angle of the gate. * **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### unitary Apply unitary gate specified by `obj` to `qubits`. **Parameters** * **obj** (*np.ndarray |* [*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"") *| BaseOperator*) – Unitary operator. * **qubits** (*Sequence\[QubitSpecifier]*) – The circuit qubits to apply the transformation to. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Unitary name for backend \[Default: None]. **Returns** The quantum circuit. **Return type** [QuantumCircuit](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **Example** Apply a gate specified by a unitary matrix to a quantum circuit ```python from qiskit import QuantumCircuit matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] circuit = QuantumCircuit(2) circuit.unitary(matrix, [0, 1]) ``` ### while\_loop Create a `while` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of `label`), it will create a `WhileLoopOp` with the given `body`. If `body` (and `qubits` and `clbits`) are *not* passed, then this acts as a context manager, which will automatically build a `WhileLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage: ```python from qiskit.circuit import QuantumCircuit, Clbit, Qubit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) with qc.while_loop((bits[2], 0)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) ``` **Parameters** * **condition** (*Tuple\[Union\[*[*ClassicalRegister*](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"")*,* [*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*],* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – An equality condition to be checked prior to executing `body`. The left-hand side of the condition must be a [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"") or a [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit""), and the right-hand side must be an integer or boolean. * **body** (*Optional\[*[*QuantumCircuit*](#qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]*) – The loop body to be repeatedly executed. Omit this to use the context-manager mode. * **qubits** (*Optional\[Sequence\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*]]*) – The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. * **clbits** (*Optional\[Sequence\[*[*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*]]*) – The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. * **label** (*Optional\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – The string label of the instruction in the circuit. **Returns** If used in context-manager mode, then this should be used as a `with` resource, which will infer the block content and operands on exit. If the full form is used, then this returns a handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") or WhileLoopContext **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if an incorrect calling convention is used. ### width Return number of qubits plus clbits in circuit. **Returns** Width of circuit. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### x Apply [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** * **qubit** (*QubitSpecifier*) – The qubit(s) to apply the gate to. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The string label of the gate in the circuit. **Returns** A handle to the instructions created. **Return type** [InstructionSet](qiskit.circuit.InstructionSet ""qiskit.circuit.InstructionSet"") ### y Apply [`YGate`](qiskit.circuit.library.YGate ""qiskit.circuit.library.YGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ### z Apply [`ZGate`](qiskit.circuit.library.ZGate ""qiskit.circuit.library.ZGate""). For the full matrix form of this gate, see the underlying gate documentation. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.quantumregister.QuantumRegister"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*slice*](https://docs.python.org/3/library/functions.html#slice ""(in Python v3.12)"") *|*[*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.quantumregister.Qubit"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubit(s) to apply the gate to. **Returns** A handle to the instructions created. **Return type** [*InstructionSet*](qiskit.circuit.InstructionSet ""qiskit.circuit.instructionset.InstructionSet"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.QuantumCircuit.mdx "--- title: QuantumRegister description: API reference for qiskit.circuit.QuantumRegister in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.QuantumRegister --- # QuantumRegister Bases: [`Register`](qiskit.circuit.Register ""qiskit.circuit.register.Register"") Implement a quantum register. Create a new generic register. Either the `size` or the `bits` argument must be provided. If `size` is not None, the register will be pre-populated with bits of the correct type. **Parameters** * **size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional. The number of bits to include in the register. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Optional. The name of the register. If not provided, a unique name will be auto-generated from the register type. * **bits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")*]*) – Optional. A list of Bit() instances to be used to populate the register. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if both the `size` and `bits` arguments are provided, or if neither are. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `size` is not valid. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `name` is not a valid name according to the OpenQASM spec. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `bits` contained duplicated bits. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `bits` contained bits of an incorrect type. ## Attributes ### instances\_counter ### name Get the register name. ### prefix ### size Get the register size. ## Methods ### index Find the index of the provided bit within this register. ",repo/docs/api/qiskit/1.0\qiskit.circuit.QuantumRegister.mdx "--- title: Qubit description: API reference for qiskit.circuit.Qubit in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.Qubit --- # Qubit Bases: [`Bit`](qiskit.circuit.Bit ""qiskit.circuit.bit.Bit"") Implement a quantum bit. Creates a qubit. **Parameters** * **register** ([*QuantumRegister*](qiskit.circuit.QuantumRegister ""qiskit.circuit.QuantumRegister"")) – Optional. A quantum register containing the bit. * **index** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional. The index of the bit in its containing register. **Raises** [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if the provided register is not a valid [`QuantumRegister`](qiskit.circuit.QuantumRegister ""qiskit.circuit.QuantumRegister"") ",repo/docs/api/qiskit/1.0\qiskit.circuit.Qubit.mdx "--- title: Register description: API reference for qiskit.circuit.Register in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.circuit.Register --- # Register Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Implement a generic register. This class should not be instantiated directly. This is just a superclass for [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"") and [`QuantumRegister`](qiskit.circuit.QuantumRegister ""qiskit.circuit.QuantumRegister""). Create a new generic register. Either the `size` or the `bits` argument must be provided. If `size` is not None, the register will be pre-populated with bits of the correct type. **Parameters** * **size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional. The number of bits to include in the register. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Optional. The name of the register. If not provided, a unique name will be auto-generated from the register type. * **bits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")*]*) – Optional. A list of Bit() instances to be used to populate the register. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if both the `size` and `bits` arguments are provided, or if neither are. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `size` is not valid. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `name` is not a valid name according to the OpenQASM spec. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `bits` contained duplicated bits. * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – if `bits` contained bits of an incorrect type. ## Attributes ### bit\_type ### instances\_counter ### name Get the register name. ### prefix ### size Get the register size. ## Methods ### index Find the index of the provided bit within this register. ",repo/docs/api/qiskit/1.0\qiskit.circuit.Register.mdx "--- 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 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)"")) – instruction’s qubit width * **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s clbit width * **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")*]*) – list of parameters * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – instruction’s duration. it must be integer if `unit` is ‘dt’ * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – time unit of duration * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or None*) – An optional label for identifying the instruction. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – when the register is not in the correct format. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – when the optional label is provided, but it is not a string. ## Attributes ### base\_class 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. ### blocks ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params return instruction params. ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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. ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### 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. **[`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. ### 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. **[`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. **Return type** Iterable\[Tuple\[Tuple, [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")]] ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### replace\_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"") ### 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"") ### soft\_compare 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)"") ### 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. ### validate\_parameter Instruction parameters has no validation or normalization. ",repo/docs/api/qiskit/1.0\qiskit.circuit.SwitchCaseOp.mdx "--- 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 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)"")) – instruction’s qubit width * **num\_clbits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – instruction’s clbit width * **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*|*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*|ndarray|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")*]*) – list of parameters * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – instruction’s duration. it must be integer if `unit` is ‘dt’ * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – time unit of duration * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or None*) – An optional label for identifying the instruction. **Raises** * [**CircuitError**](circuit#qiskit.circuit.CircuitError ""qiskit.circuit.CircuitError"") – when the register is not in the correct format. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – when the optional label is provided, but it is not a string. ## Attributes ### base\_class 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. ### blocks ### condition The classical condition on the instruction. ### condition\_bits Get Clbits in condition. ### decompositions Get the decompositions of the instruction from the SessionEquivalenceLibrary. ### definition Return definition in terms of other basic gates. ### duration Get the duration. ### label Return instruction label ### 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. ### name Return the name. ### num\_clbits Return the number of clbits. ### num\_qubits Return the number of qubits. ### params ### unit Get the time unit of duration. ## Methods ### add\_decomposition Add a decomposition of the instruction to the SessionEquivalenceLibrary. ### assemble Assemble a QasmQobjInstruction ### broadcast\_arguments 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. ### c\_if Set a classical equality condition on this instruction between the register or cbit `classical` and value `val`. This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition; it does not stack. ### copy 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"") ### inverse 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. ### is\_parameterized Return True .IFF. instruction is parameterized else False ### repeat 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. ### replace\_blocks Replace blocks and return new instruction. :param blocks: Tuple of QuantumCircuits to replace in instruction. **Returns** New ControlFlowOp with replaced blocks. ### 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"") ### soft\_compare 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)"") ### 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. ### validate\_parameter Instruction parameters has no validation or normalization. ",repo/docs/api/qiskit/1.0\qiskit.circuit.WhileLoopOp.mdx "--- title: DAGCircuit description: API reference for qiskit.dagcircuit.DAGCircuit in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.dagcircuit.DAGCircuit --- # DAGCircuit Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Quantum circuit as a directed acyclic graph. There are 3 types of nodes in the graph: inputs, outputs, and operations. The nodes are connected by directed edges that correspond to qubits and bits. Create an empty circuit. ## Attributes ### calibrations Return calibration dictionary. **The custom pulse definition of a given gate is of the form** \{‘gate\_name’: \{(qubits, params): schedule}} ### global\_phase Return the global phase of the circuit. ### node\_counter Returns the number of nodes in the dag. ### wires Return a list of the wires in order. ## Methods ### add\_calibration Register a low-level, custom pulse definition for the given gate. **Parameters** * **gate** (*Union\[*[*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"")*,* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – Gate information. * **qubits** (*Union\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, Tuple\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – List of qubits to be measured. * **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"")) – Schedule information. * **params** (*Optional\[List\[Union\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*,* [*Parameter*](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")*]]]*) – A list of parameters. **Raises** [**Exception**](https://docs.python.org/3/library/exceptions.html#Exception ""(in Python v3.12)"") – if the gate is of type string and params is None. ### add\_clbits Add individual clbit wires. ### add\_creg Add all wires in a classical register. ### add\_qreg Add all wires in a quantum register. ### add\_qubits Add individual qubit wires. ### ancestors Returns set of the ancestors of a node as DAGOpNodes and DAGInNodes. ### apply\_operation\_back Apply an operation to the output of the circuit. **Parameters** * **op** ([*qiskit.circuit.Operation*](qiskit.circuit.Operation ""qiskit.circuit.Operation"")) – the operation associated with the DAG node * **qargs** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*]*) – qubits that op will be applied to * **cargs** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*]*) – cbits that op will be applied to * **check** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True` (default), this function will enforce that the [`DAGCircuit`](#qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") data-structure invariants are maintained (all `qargs` are [`Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")s, all are in the DAG, etc). If `False`, the caller *must* uphold these invariants itself, but the cost of several checks will be skipped. This is most useful when building a new DAG from a source of known-good nodes. **Returns** the node for the op that was added to the dag **Return type** [DAGOpNode](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"") **Raises** [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – if a leaf node is connected to multiple outputs ### apply\_operation\_front Apply an operation to the input of the circuit. **Parameters** * **op** ([*qiskit.circuit.Operation*](qiskit.circuit.Operation ""qiskit.circuit.Operation"")) – the operation associated with the DAG node * **qargs** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*]*) – qubits that op will be applied to * **cargs** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*]*) – cbits that op will be applied to * **check** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True` (default), this function will enforce that the [`DAGCircuit`](#qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") data-structure invariants are maintained (all `qargs` are [`Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")s, all are in the DAG, etc). If `False`, the caller *must* uphold these invariants itself, but the cost of several checks will be skipped. This is most useful when building a new DAG from a source of known-good nodes. **Returns** the node for the op that was added to the dag **Return type** [DAGOpNode](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"") **Raises** [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – if initial nodes connected to multiple out edges ### bfs\_successors Returns an iterator of tuples of (DAGNode, \[DAGNodes]) where the DAGNode is the current node and \[DAGNode] is its successors in BFS order. ### classical\_predecessors Returns iterator of the predecessors of a node that are connected by a classical edge as DAGOpNodes and DAGInNodes. ### classical\_successors Returns iterator of the successors of a node that are connected by a classical edge as DAGOpNodes and DAGInNodes. ### collect\_1q\_runs Return a set of non-conditional runs of 1q “op” nodes. ### collect\_2q\_runs Return a set of non-conditional runs of 2q “op” nodes. ### collect\_runs Return a set of non-conditional runs of “op” nodes with the given names. For example, “… h q\[0]; cx q\[0],q\[1]; cx q\[0],q\[1]; h q\[1]; ..” would produce the tuple of cx nodes as an element of the set returned from a call to collect\_runs(\[“cx”]). If instead the cx nodes were “cx q\[0],q\[1]; cx q\[1],q\[0];”, the method would still return the pair in a tuple. The namelist can contain names that are not in the circuit’s basis. Nodes must have only one successor to continue the run. ### compose Compose the `other` circuit onto the output of this circuit. A subset of input wires of `other` are mapped to a subset of output wires of this circuit. `other` can be narrower or of equal width to `self`. **Parameters** * **other** ([*DAGCircuit*](#qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – circuit to compose with self * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – qubits of self to compose onto. * **clbits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(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)"")*]*) – clbits of self to compose onto. * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, front composition will be performed (not implemented yet) * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, modify the object. Otherwise return composed circuit. **Returns** the composed dag (returns None if inplace==True). **Return type** [DAGCircuit](#qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – if `other` is wider or there are duplicate edge mappings. ### copy\_empty\_like Return a copy of self with the same structure but empty. **That structure includes:** * name and other metadata * global phase * duration * all the qubits and clbits, including the registers. **Returns** An empty copy of self. **Return type** [DAGCircuit](#qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### count\_ops Count the occurrences of operation names. **Parameters** **recurse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if `True` (default), then recurse into control-flow operations. In all cases, this counts only the number of times the operation appears in any possible block; both branches of if-elses are counted, and for- and while-loop blocks are only counted once. **Returns** a mapping of operation names to the number of times it appears. **Return type** Mapping\[[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)"")] ### count\_ops\_longest\_path Count the occurrences of operation names on the longest path. Returns a dictionary of counts keyed on the operation name. ### depth Return the circuit depth. If there is control flow present, this count may only be an estimate, as the complete control-flow path cannot be statically known. **Parameters** **recurse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if `True`, then recurse into control-flow operations. For loops with known-length iterators are counted as if the loop had been manually unrolled (*i.e.* with each iteration of the loop body written out explicitly). If-else blocks take the longer case of the two branches. While loops are counted as if the loop body runs once only. Defaults to `False` and raises [`DAGCircuitError`](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") if any control flow is present, to avoid silently returning a nonsensical number. **Returns** the circuit depth **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") **Raises** * [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – if not a directed acyclic graph * [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – if unknown control flow is present in a recursive call, or any control flow is present in a non-recursive call. ### descendants Returns set of the descendants of a node as DAGOpNodes and DAGOutNodes. ### draw Draws the dag circuit. This function needs [Graphviz](https://www.graphviz.org/) to be installed. Graphviz is not a python package and can’t be pip installed (the `graphviz` package on PyPI is a Python interface library for Graphviz and does not actually install Graphviz). You can refer to [the Graphviz documentation](https://www.graphviz.org/download/) on how to install it. **Parameters** * **scale** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – scaling factor * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – file path to save image to (format inferred from name) * **style** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – ‘plain’: B\&W graph; ‘color’ (default): color input/output/op nodes **Returns** if in Jupyter notebook and not saving to file, otherwise None. **Return type** Ipython.display.Image ### edges Iterator for edge values and source and dest node This works by returning the output edges from the specified nodes. If no nodes are specified all edges from the graph are returned. **Parameters** **nodes** ([*DAGOpNode*](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")*,* [*DAGInNode*](qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")*, or* [*DAGOutNode*](qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")*|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*(*[*DAGOpNode*](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")*,* [*DAGInNode*](qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")*, or* [*DAGOutNode*](qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")) – Either a list of nodes or a single input node. If none is specified, all edges are returned from the graph. **Yields** *edge* – **the edge in the same format as out\_edges the tuple** (source node, destination node, edge data) ### find\_bit Finds locations in the circuit, by mapping the Qubit and Clbit to positional index BitLocations is defined as: BitLocations = namedtuple(“BitLocations”, (“index”, “registers”)) **Parameters** **bit** ([*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")) – The bit to locate. **Returns** **A 2-tuple. The first element (`index`)** contains the index at which the `Bit` can be found (in either `qubits`, `clbits`, depending on its type). The second element (`registers`) is a list of `(register, index)` pairs with an entry for each `Register` in the circuit which contains the `Bit` (and the index in the `Register` at which it can be found). **Return type** namedtuple(int, List\[Tuple(Register, int)]) **Raises:** DAGCircuitError: If the supplied `Bit` was of an unknown type. DAGCircuitError: If the supplied `Bit` could not be found on the circuit. ### front\_layer Return a list of op nodes in the first layer of this dag. ### gate\_nodes Get the list of gate nodes in the dag. **Returns** the list of DAGOpNodes that represent gates. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[DAGOpNode](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")] ### has\_calibration\_for Return True if the dag has a calibration defined for the node operation. In this case, the operation does not need to be translated to the device basis. ### idle\_wires Return idle wires. **Parameters** **ignore** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*(*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*)*) – List of node names to ignore. Default: \[] **Yields** *Bit* – Bit in idle wire. **Raises** [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – If the DAG is invalid ### is\_predecessor Checks if a second node is in the predecessors of node. ### is\_successor Checks if a second node is in the successors of node. ### layers Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit. A layer is a circuit whose gates act on disjoint qubits, i.e., a layer has depth 1. The total number of layers equals the circuit depth d. The layers are indexed from 0 to d-1 with the earliest layer at index 0. The layers are constructed using a greedy algorithm. Each returned layer is a dict containing \{“graph”: circuit graph, “partition”: list of qubit lists}. The returned layer contains new (but semantically equivalent) DAGOpNodes, DAGInNodes, and DAGOutNodes. These are not the same as nodes of the original dag, but are equivalent via DAGNode.semantic\_eq(node1, node2). TODO: Gates that use the same cbits will end up in different layers as this is currently implemented. This may not be the desired behavior. ### longest\_path Returns the longest path in the dag as a list of DAGOpNodes, DAGInNodes, and DAGOutNodes. ### multi\_qubit\_ops Get list of 3+ qubit operations. Ignore directives like snapshot and barrier. ### multigraph\_layers Yield layers of the multigraph. ### named\_nodes Get the set of “op” nodes with the given name. ### node Get the node in the dag. **Parameters** **node\_id** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Node identifier. **Returns** the node. **Return type** node ### nodes Iterator for node values. **Yields** *node* – the node. ### nodes\_on\_wire Iterator for nodes that affect a given wire. **Parameters** * **wire** ([*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")) – the wire to be looked at. * **only\_ops** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if only the ops nodes are wanted; otherwise, all nodes are returned. **Yields** *Iterator* – the successive nodes on the given wire **Raises** [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – if the given wire doesn’t exist in the DAG ### num\_clbits Return the total number of classical bits used by the circuit. ### num\_qubits Return the total number of qubits used by the circuit. num\_qubits() replaces former use of width(). DAGCircuit.width() now returns qubits + clbits for consistency with Circuit.width() \[qiskit-terra #2564]. ### num\_tensor\_factors Compute how many components the circuit can decompose into. ### op\_nodes Get the list of “op” nodes in the dag. **Parameters** * **op** ([*Type*](circuit_classical#qiskit.circuit.classical.types.Type ""qiskit.circuit.classical.types.Type"")) – [`qiskit.circuit.Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation"") subclass op nodes to return. If None, return all op nodes. * **include\_directives** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – include barrier, snapshot etc. **Returns** the list of node ids containing the given op. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[DAGOpNode](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")] ### predecessors Returns iterator of the predecessors of a node as DAGOpNodes and DAGInNodes. ### properties Return a dictionary of circuit properties. ### quantum\_causal\_cone Returns causal cone of a qubit. A qubit’s causal cone is the set of qubits that can influence the output of that qubit through interactions, whether through multi-qubit gates or operations. Knowing the causal cone of a qubit can be useful when debugging faulty circuits, as it can help identify which wire(s) may be causing the problem. This method does not consider any classical data dependency in the `DAGCircuit`, classical bit wires are ignored for the purposes of building the causal cone. **Parameters** **qubit** ([*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")) – The output qubit for which we want to find the causal cone. **Returns** The set of qubits whose interactions affect `qubit`. **Return type** Set\[[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")] ### quantum\_predecessors Returns iterator of the predecessors of a node that are connected by a quantum edge as DAGOpNodes and DAGInNodes. ### quantum\_successors Returns iterator of the successors of a node that are connected by a quantum edge as Opnodes and DAGOutNodes. ### remove\_all\_ops\_named Remove all operation nodes with the given name. ### remove\_ancestors\_of Remove all of the ancestor operation nodes of node. ### remove\_clbits Remove classical bits from the circuit. All bits MUST be idle. Any registers with references to at least one of the specified bits will also be removed. **Parameters** **clbits** (*List\[*[*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*]*) – The bits to remove. **Raises** [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – a clbit is not a [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit""), is not in the circuit, or is not idle. ### remove\_cregs Remove classical registers from the circuit, leaving underlying bits in place. **Raises** * [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – a creg is not a ClassicalRegister, or is not in * **the circuit.** – ### remove\_descendants\_of Remove all of the descendant operation nodes of node. ### remove\_nonancestors\_of Remove all of the non-ancestors operation nodes of node. ### remove\_nondescendants\_of Remove all of the non-descendants operation nodes of node. ### remove\_op\_node Remove an operation node n. Add edges from predecessors to successors. ### remove\_qregs Remove classical registers from the circuit, leaving underlying bits in place. **Raises** * [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – a qreg is not a QuantumRegister, or is not in * **the circuit.** – ### remove\_qubits Remove quantum bits from the circuit. All bits MUST be idle. Any registers with references to at least one of the specified bits will also be removed. **Parameters** **qubits** (*List\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*]*) – The bits to remove. **Raises** [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – a qubit is not a [`Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.Qubit""), is not in the circuit, or is not idle. ### replace\_block\_with\_op Replace a block of nodes with a single node. This is used to consolidate a block of DAGOpNodes into a single operation. A typical example is a block of gates being consolidated into a single `UnitaryGate` representing the unitary matrix of the block. **Parameters** * **node\_block** (*List\[*[*DAGNode*](qiskit.dagcircuit.DAGNode ""qiskit.dagcircuit.DAGNode"")*]*) – A list of dag nodes that represents the node block to be replaced * **op** ([*qiskit.circuit.Operation*](qiskit.circuit.Operation ""qiskit.circuit.Operation"")) – The operation to replace the block with * **wire\_pos\_map** (*Dict\[*[*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The dictionary mapping the bits to their positions in the output `qargs` or `cargs`. This is necessary to reconstruct the arg order over multiple gates in the combined single op node. If a [`Bit`](qiskit.circuit.Bit ""qiskit.circuit.Bit"") is not in the dictionary, it will not be added to the args; this can be useful when dealing with control-flow operations that have inherent bits in their `condition` or `target` fields. * **cycle\_check** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – When set to True this method will check that replacing the provided `node_block` with a single node would introduce a cycle (which would invalidate the `DAGCircuit`) and will raise a `DAGCircuitError` if a cycle would be introduced. This checking comes with a run time penalty. If you can guarantee that your input `node_block` is a contiguous block and won’t introduce a cycle when it’s contracted to a single node, this can be set to `False` to improve the runtime performance of this method. **Raises** [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – if `cycle_check` is set to `True` and replacing the specified block introduces a cycle or if `node_block` is empty. **Returns** The op node that replaces the block. **Return type** [DAGOpNode](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"") ### reverse\_ops Reverse the operations in the `self` circuit. **Returns** the reversed dag. **Return type** [DAGCircuit](#qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### separable\_circuits Decompose the circuit into sets of qubits with no gates connecting them. **Parameters** **remove\_idle\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Flag denoting whether to remove idle qubits from the separated circuits. If `False`, each output circuit will contain the same number of qubits as `self`. **Returns** **The circuits resulting from separating `self` into sets** of disconnected qubits **Return type** List\[[DAGCircuit](#qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")] Each [`DAGCircuit`](#qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") instance returned by this method will contain the same number of clbits as `self`. The global phase information in `self` will not be maintained in the subcircuits returned by this method. ### serial\_layers Yield a layer for all gates of this circuit. A serial layer is a circuit with one gate. The layers have the same structure as in layers(). ### size Return the number of operations. If there is control flow present, this count may only be an estimate, as the complete control-flow path cannot be statically known. **Parameters** **recurse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if `True`, then recurse into control-flow operations. For loops with known-length iterators are counted unrolled. If-else blocks sum both of the two branches. While loops are counted as if the loop body runs once only. Defaults to `False` and raises [`DAGCircuitError`](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") if any control flow is present, to avoid silently returning a mostly meaningless number. **Returns** the circuit size **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") **Raises** [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – if an unknown [`ControlFlowOp`](qiskit.circuit.ControlFlowOp ""qiskit.circuit.ControlFlowOp"") is present in a call with `recurse=True`, or any control flow is present in a non-recursive call. ### substitute\_node Replace an DAGOpNode with a single operation. qargs, cargs and conditions for the new operation will be inferred from the node to be replaced. The new operation will be checked to match the shape of the replaced operation. **Parameters** * **node** ([*DAGOpNode*](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")) – Node to be replaced * **op** ([*qiskit.circuit.Operation*](qiskit.circuit.Operation ""qiskit.circuit.Operation"")) – The [`qiskit.circuit.Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation"") instance to be added to the DAG * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Optional, default False. If True, existing DAG node will be modified to include op. Otherwise, a new DAG node will be used. * **propagate\_condition** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Optional, default True. If True, a condition on the `node` to be replaced will be applied to the new `op`. This is the legacy behaviour. If either node is a control-flow operation, this will be ignored. If the `op` already has a condition, [`DAGCircuitError`](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") is raised. **Returns** the new node containing the added operation. **Return type** [DAGOpNode](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"") **Raises** * [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – If replacement operation was incompatible with * **location**\*\* of \*\***target node.** – ### substitute\_node\_with\_dag Replace one node with dag. **Parameters** * **node** ([*DAGOpNode*](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")) – node to substitute * **input\_dag** ([*DAGCircuit*](#qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – circuit that will substitute the node * **wires** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")*] | Dict\[*[*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")*,* [*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")*]*) – gives an order for (qu)bits in the input circuit. If a list, then the bits refer to those in the `input_dag`, and the order gets matched to the node wires by qargs first, then cargs, then conditions. If a dictionary, then a mapping of bits in the `input_dag` to those that the `node` acts on. * **propagate\_condition** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True` (default), then any `condition` attribute on the operation within `node` is propagated to each node in the `input_dag`. If `False`, then the `input_dag` is assumed to faithfully implement suitable conditional logic already. This is ignored for [`ControlFlowOp`](qiskit.circuit.ControlFlowOp ""qiskit.circuit.ControlFlowOp"")s (i.e. treated as if it is `False`); replacements of those must already fulfill the same conditional logic or this function would be close to useless for them. **Returns** maps node IDs from input\_dag to their new node incarnations in self. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") **Raises** [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – if met with unexpected predecessor/successors ### successors Returns iterator of the successors of a node as DAGOpNodes and DAGOutNodes. ### swap\_nodes Swap connected nodes e.g. due to commutation. **Parameters** * **node1** (*OpNode*) – predecessor node * **node2** (*OpNode*) – successor node **Raises** [**DAGCircuitError**](dagcircuit#qiskit.dagcircuit.DAGCircuitError ""qiskit.dagcircuit.DAGCircuitError"") – if either node is not an OpNode or nodes are not connected ### topological\_nodes Yield nodes in topological order. **Parameters** **key** (*Callable*) – A callable which will take a DAGNode object and return a string sort key. If not specified the `sort_key` attribute will be used as the sort key for each node. **Returns** node in topological order **Return type** generator([DAGOpNode](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode""), [DAGInNode](qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode""), or [DAGOutNode](qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")) ### topological\_op\_nodes Yield op nodes in topological order. Allowed to pass in specific key to break ties in top order **Parameters** **key** (*Callable*) – A callable which will take a DAGNode object and return a string sort key. If not specified the `sort_key` attribute will be used as the sort key for each node. **Returns** op node in topological order **Return type** generator([DAGOpNode](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")) ### two\_qubit\_ops Get list of 2 qubit operations. Ignore directives like snapshot and barrier. ### width Return the total number of qubits + clbits used by the circuit. This function formerly returned the number of qubits by the calculation return len(self.\_wires) - self.num\_clbits() but was changed by issue #2564 to return number of qubits + clbits with the new function DAGCircuit.num\_qubits replacing the former semantic of DAGCircuit.width(). ",repo/docs/api/qiskit/1.0\qiskit.dagcircuit.DAGCircuit.mdx "--- title: DAGDependency description: API reference for qiskit.dagcircuit.DAGDependency in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.dagcircuit.DAGDependency --- # DAGDependency Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Object to represent a quantum circuit as a Directed Acyclic Graph (DAG) via operation dependencies (i.e. lack of commutation). The nodes in the graph are operations represented by quantum gates. The edges correspond to non-commutation between two operations (i.e. a dependency). A directed edge from node A to node B means that operation A does not commute with operation B. The object’s methods allow circuits to be constructed. The nodes in the graph have the following attributes: ‘operation’, ‘successors’, ‘predecessors’. **Example:** Bell circuit with no measurement. ```python ┌───┐ qr_0: ┤ H ├──■── └───┘┌─┴─┐ qr_1: ─────┤ X ├ └───┘ ``` The dependency DAG for the above circuit is represented by two nodes. The first one corresponds to Hadamard gate, the second one to the CNOT gate as the gates do not commute there is an edge between the two nodes. **Reference:** \[1] Iten, R., Moyard, R., Metger, T., Sutter, D. and Woerner, S., 2020. Exact and practical pattern matching for quantum circuit optimization. [arXiv:1909.05270](https://arxiv.org/abs/1909.05270) Create an empty DAGDependency. ## Attributes ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}`. ### global\_phase Return the global phase of the circuit. ## Methods ### add\_clbits Add individual clbit wires. ### add\_creg Add clbits in a classical register. ### add\_op\_node Add a DAGDepNode to the graph and update the edges. **Parameters** * **operation** ([*qiskit.circuit.Operation*](qiskit.circuit.Operation ""qiskit.circuit.Operation"")) – operation as a quantum gate * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*]*) – list of qubits on which the operation acts * **cargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Clbit*](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"")*]*) – list of classical wires to attach to ### add\_qreg Add qubits in a quantum register. ### add\_qubits Add individual qubit wires. ### copy Function to copy a DAGDependency object. :returns: a copy of a DAGDependency object. :rtype: DAGDependency ### depth Return the circuit depth. :returns: the circuit depth :rtype: int ### direct\_predecessors Direct predecessors id of a given node as sorted list. **Parameters** **node\_id** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – label of considered node. **Returns** direct predecessors id as a sorted list **Return type** List ### direct\_successors Direct successors id of a given node as sorted list. **Parameters** **node\_id** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – label of considered node. **Returns** direct successors id as a sorted list **Return type** List ### draw Draws the DAGDependency graph. This function needs pydot \<[https://github.com/erocarrera/pydot](https://github.com/erocarrera/pydot)>, which in turn needs Graphviz \<[https://www.graphviz.org/](https://www.graphviz.org/)>\` to be installed. **Parameters** * **scale** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – scaling factor * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – file path to save image to (format inferred from name) * **style** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – ‘plain’: B\&W graph ‘color’ (default): color input/output/op nodes **Returns** if in Jupyter notebook and not saving to file, otherwise None. **Return type** Ipython.display.Image ### get\_all\_edges Enumeration of all edges. **Returns** corresponding to the label. **Return type** List ### get\_edges Edge enumeration between two nodes through method get\_all\_edge\_data. **Parameters** * **src\_id** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – label of the first node. * **dest\_id** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – label of the second node. **Returns** corresponding to all edges between the two nodes. **Return type** List ### get\_in\_edges Enumeration of all incoming edges for a given node. **Parameters** **node\_id** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – label of considered node. **Returns** corresponding incoming edges data. **Return type** List ### get\_node **Parameters** **node\_id** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – label of considered node. **Returns** corresponding to the label. **Return type** node ### get\_nodes **Returns** iterator over all the nodes. **Return type** generator([dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) ### get\_out\_edges Enumeration of all outgoing edges for a given node. **Parameters** **node\_id** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – label of considered node. **Returns** corresponding outgoing edges data. **Return type** List ### predecessors Predecessors id of a given node as sorted list. **Parameters** **node\_id** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – label of considered node. **Returns** all predecessors id as a sorted list **Return type** List ### replace\_block\_with\_op Replace a block of nodes with a single node. This is used to consolidate a block of DAGDepNodes into a single operation. A typical example is a block of CX and SWAP gates consolidated into a LinearFunction. This function is an adaptation of a similar function from DAGCircuit. It is important that such consolidation preserves commutativity assumptions present in DAGDependency. As an example, suppose that every node in a block \[A, B, C, D] commutes with another node E. Let F be the consolidated node, F = A o B o C o D. Then F also commutes with E, and thus the result of replacing \[A, B, C, D] by F results in a valid DAGDependency. That is, any deduction about commutativity in consolidated DAGDependency is correct. On the other hand, suppose that at least one of the nodes, say B, does not commute with E. Then the consolidated DAGDependency would imply that F does not commute with E. Even though F and E may actually commute, it is still safe to assume that they do not. That is, the current implementation of consolidation may lead to suboptimal but not to incorrect results. **Parameters** * **node\_block** (*List\[*[*DAGDepNode*](qiskit.dagcircuit.DAGDepNode ""qiskit.dagcircuit.DAGDepNode"")*]*) – A list of dag nodes that represents the node block to be replaced * **op** ([*qiskit.circuit.Operation*](qiskit.circuit.Operation ""qiskit.circuit.Operation"")) – The operation to replace the block with * **wire\_pos\_map** (*Dict\[*[*Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The dictionary mapping the qarg to the position. This is necessary to reconstruct the qarg order over multiple gates in the combined single op node. * **cycle\_check** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – When set to True this method will check that replacing the provided `node_block` with a single node would introduce a cycle (which would invalidate the `DAGDependency`) and will raise a `DAGDependencyError` if a cycle would be introduced. This checking comes with a run time penalty. If you can guarantee that your input `node_block` is a contiguous block and won’t introduce a cycle when it’s contracted to a single node, this can be set to `False` to improve the runtime performance of this method. **Raises** [**DAGDependencyError**](dagcircuit#qiskit.dagcircuit.DAGDependencyError ""qiskit.dagcircuit.DAGDependencyError"") – if `cycle_check` is set to `True` and replacing the specified block introduces a cycle or if `node_block` is empty. ### size Returns the number of gates in the circuit ### successors Successors id of a given node as sorted list. **Parameters** **node\_id** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – label of considered node. **Returns** all successors id as a sorted list **Return type** List ### to\_retworkx Returns the DAGDependency in retworkx format. ### topological\_nodes Yield nodes in topological order. **Returns** node in topological order. **Return type** generator([DAGNode](qiskit.dagcircuit.DAGNode ""qiskit.dagcircuit.DAGNode"")) ",repo/docs/api/qiskit/1.0\qiskit.dagcircuit.DAGDependency.mdx "--- title: DAGDepNode description: API reference for qiskit.dagcircuit.DAGDepNode in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.dagcircuit.DAGDepNode --- # DAGDepNode Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Object to represent the information at a node in the DAGDependency(). It is used as the return value from \*\_nodes() functions and can be supplied to functions that take a node. ## Attributes ### type ### name ### cargs ### sort\_key ### node\_id ### successors ### predecessors ### reachable ### matchedwith ### isblocked ### successorstovisit ### qindices ### cindices ### op Returns the Instruction object corresponding to the op for the node, else None ### qargs Returns list of Qubit, else an empty list. ## Methods ### copy Function to copy a DAGDepNode object. :returns: a copy of a DAGDepNode object. :rtype: DAGDepNode ### semantic\_eq Check if DAG nodes are considered equivalent, e.g., as a node\_match for nx.is\_isomorphic. **Parameters** * **node1** ([*DAGDepNode*](#qiskit.dagcircuit.DAGDepNode ""qiskit.dagcircuit.DAGDepNode"")) – A node to compare. * **node2** ([*DAGDepNode*](#qiskit.dagcircuit.DAGDepNode ""qiskit.dagcircuit.DAGDepNode"")) – The other node to compare. **Returns** If node1 == node2 **Return type** [Bool](circuit_classical#qiskit.circuit.classical.types.Bool ""qiskit.circuit.classical.types.Bool"") ",repo/docs/api/qiskit/1.0\qiskit.dagcircuit.DAGDepNode.mdx "--- title: DAGInNode description: API reference for qiskit.dagcircuit.DAGInNode in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.dagcircuit.DAGInNode --- # DAGInNode Bases: [`DAGNode`](qiskit.dagcircuit.DAGNode ""qiskit.dagcircuit.dagnode.DAGNode"") Object to represent an incoming wire node in the DAGCircuit. Create an incoming node ## Attributes ### wire ### sort\_key ## Methods ### semantic\_eq Check if DAG nodes are considered equivalent, e.g., as a node\_match for [`rustworkx.is_isomorphic_node_match()`](https://www.rustworkx.org/apiref/rustworkx.is_isomorphic_node_match.html#rustworkx.is_isomorphic_node_match ""(in rustworkx v0.14)""). **Parameters** * **node1** ([*DAGOpNode*](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")*,* [*DAGInNode*](#qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")*,* [*DAGOutNode*](qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")) – A node to compare. * **node2** ([*DAGOpNode*](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")*,* [*DAGInNode*](#qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")*,* [*DAGOutNode*](qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")) – The other node to compare. * **bit\_indices1** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Dictionary mapping Bit instances to their index within the circuit containing node1 * **bit\_indices2** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Dictionary mapping Bit instances to their index within the circuit containing node2 **Returns** If node1 == node2 **Return type** [Bool](circuit_classical#qiskit.circuit.classical.types.Bool ""qiskit.circuit.classical.types.Bool"") ",repo/docs/api/qiskit/1.0\qiskit.dagcircuit.DAGInNode.mdx "--- title: DAGNode description: API reference for qiskit.dagcircuit.DAGNode in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.dagcircuit.DAGNode --- # DAGNode Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Parent class for DAGOpNode, DAGInNode, and DAGOutNode. Create a node ## Methods ### semantic\_eq Check if DAG nodes are considered equivalent, e.g., as a node\_match for [`rustworkx.is_isomorphic_node_match()`](https://www.rustworkx.org/apiref/rustworkx.is_isomorphic_node_match.html#rustworkx.is_isomorphic_node_match ""(in rustworkx v0.14)""). **Parameters** * **node1** ([*DAGOpNode*](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")*,* [*DAGInNode*](qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")*,* [*DAGOutNode*](qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")) – A node to compare. * **node2** ([*DAGOpNode*](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")*,* [*DAGInNode*](qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")*,* [*DAGOutNode*](qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")) – The other node to compare. * **bit\_indices1** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Dictionary mapping Bit instances to their index within the circuit containing node1 * **bit\_indices2** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Dictionary mapping Bit instances to their index within the circuit containing node2 **Returns** If node1 == node2 **Return type** [Bool](circuit_classical#qiskit.circuit.classical.types.Bool ""qiskit.circuit.classical.types.Bool"") ",repo/docs/api/qiskit/1.0\qiskit.dagcircuit.DAGNode.mdx "--- title: DAGOpNode description: API reference for qiskit.dagcircuit.DAGOpNode in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.dagcircuit.DAGOpNode --- # DAGOpNode Bases: [`DAGNode`](qiskit.dagcircuit.DAGNode ""qiskit.dagcircuit.dagnode.DAGNode"") Object to represent an Instruction at a node in the DAGCircuit. Create an Instruction node ## Attributes ### op ### qargs ### cargs ### sort\_key ### name Returns the Instruction name corresponding to the op for this node ## Methods ### semantic\_eq Check if DAG nodes are considered equivalent, e.g., as a node\_match for [`rustworkx.is_isomorphic_node_match()`](https://www.rustworkx.org/apiref/rustworkx.is_isomorphic_node_match.html#rustworkx.is_isomorphic_node_match ""(in rustworkx v0.14)""). **Parameters** * **node1** ([*DAGOpNode*](#qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")*,* [*DAGInNode*](qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")*,* [*DAGOutNode*](qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")) – A node to compare. * **node2** ([*DAGOpNode*](#qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")*,* [*DAGInNode*](qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")*,* [*DAGOutNode*](qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")) – The other node to compare. * **bit\_indices1** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Dictionary mapping Bit instances to their index within the circuit containing node1 * **bit\_indices2** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Dictionary mapping Bit instances to their index within the circuit containing node2 **Returns** If node1 == node2 **Return type** [Bool](circuit_classical#qiskit.circuit.classical.types.Bool ""qiskit.circuit.classical.types.Bool"") ",repo/docs/api/qiskit/1.0\qiskit.dagcircuit.DAGOpNode.mdx "--- title: DAGOutNode description: API reference for qiskit.dagcircuit.DAGOutNode in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.dagcircuit.DAGOutNode --- # DAGOutNode Bases: [`DAGNode`](qiskit.dagcircuit.DAGNode ""qiskit.dagcircuit.dagnode.DAGNode"") Object to represent an outgoing wire node in the DAGCircuit. Create an outgoing node ## Attributes ### wire ### sort\_key ## Methods ### semantic\_eq Check if DAG nodes are considered equivalent, e.g., as a node\_match for [`rustworkx.is_isomorphic_node_match()`](https://www.rustworkx.org/apiref/rustworkx.is_isomorphic_node_match.html#rustworkx.is_isomorphic_node_match ""(in rustworkx v0.14)""). **Parameters** * **node1** ([*DAGOpNode*](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")*,* [*DAGInNode*](qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")*,* [*DAGOutNode*](#qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")) – A node to compare. * **node2** ([*DAGOpNode*](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")*,* [*DAGInNode*](qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")*,* [*DAGOutNode*](#qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")) – The other node to compare. * **bit\_indices1** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Dictionary mapping Bit instances to their index within the circuit containing node1 * **bit\_indices2** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Dictionary mapping Bit instances to their index within the circuit containing node2 **Returns** If node1 == node2 **Return type** [Bool](circuit_classical#qiskit.circuit.classical.types.Bool ""qiskit.circuit.classical.types.Bool"") ",repo/docs/api/qiskit/1.0\qiskit.dagcircuit.DAGOutNode.mdx "--- title: BaseController description: API reference for qiskit.passmanager.BaseController in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.passmanager.BaseController --- # BaseController Bases: `Task`, [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Base class of controller. A controller is built with a collection of pass manager tasks, and a subclass provides a custom logic to choose next task to run. Note a controller can be nested into another controller, and a controller itself doesn’t provide any subroutine to modify the input IR. Create new flow controller. **Parameters** **options** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any] | None*) – Option for this flow controller. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### iter\_tasks A custom logic to choose a next task to run. Controller subclass can consume the state to build a proper task pipeline. The updated state after a task execution will be fed back in as the “return” value of any `yield` statements. This indicates the order of task execution is only determined at running time. This method is not allowed to mutate the given state object. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – The state of the passmanager workflow at the beginning of this flow controller’s execution. * **state** – the state of pass manager after the execution of the last task that was yielded. The generator does not need to inspect this if it is irrelevant to its logic, nor update it. **Yields** *Task* – Next task to run. **Return type** [*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator ""(in Python v3.12)"")\[*Task*, [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState""), None] ",repo/docs/api/qiskit/1.0\qiskit.passmanager.BaseController.mdx "--- title: BasePassManager description: API reference for qiskit.passmanager.BasePassManager in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.passmanager.BasePassManager --- # BasePassManager Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Pass manager base class. Initialize an empty pass manager object. **Parameters** * **tasks** (*Task |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[Task]*) – A pass set to be added to the pass manager schedule. * **max\_iteration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of iterations the schedule will be looped if the condition is not met. ## Methods ### append Append tasks to the schedule of passes. **Parameters** **tasks** (*Task |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[Task]*) – A set of pass manager tasks to be added to schedule. **Raises** [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – When any element of tasks is not a subclass of passmanager Task. ### remove Removes a particular pass in the scheduler. **Parameters** **index** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Pass index to remove, based on the position in `passes()`. **Raises** [**PassManagerError**](passmanager#qiskit.passmanager.PassManagerError ""qiskit.passmanager.PassManagerError"") – If the index is not found. ### replace Replace a particular pass in the scheduler. **Parameters** * **index** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Task index to replace, based on the position in `tasks()` * **tasks** (*Task |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[Task]*) – A set of pass manager tasks to be added to schedule. **Raises** * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – When any element of tasks is not a subclass of passmanager Task. * [**PassManagerError**](passmanager#qiskit.passmanager.PassManagerError ""qiskit.passmanager.PassManagerError"") – If the index is not found. ### run Run all the passes on the specified `in_programs`. **Parameters** * **in\_programs** (*Any |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[Any]*) – Input programs to transform via all the registered passes. A single input object cannot be a Python builtin list object. A list object is considered as multiple input objects to optimize. * **callback** (*Callable*) – A callback function that will be called after each pass execution. The function will be called with 4 keyword arguments: ```python task (GenericPass): the pass being run passmanager_ir (Any): depending on pass manager subclass property_set (PropertySet): the property set running_time (float): the time to execute the pass count (int): the index for the pass execution ``` The exact arguments pass 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 you define a function that will take in kwargs dict and access the variables. For example: ```python def callback_func(**kwargs): task = kwargs['task'] passmanager_ir = kwargs['passmanager_ir'] property_set = kwargs['property_set'] running_time = kwargs['running_time'] count = kwargs['count'] ... ``` * **num\_processes** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of parallel processes to launch 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. * **kwargs** – Arbitrary arguments passed to the compiler frontend and backend. **Returns** The transformed program(s). **Return type** Any ### to\_flow\_controller Linearize this manager into a single [`FlowControllerLinear`](qiskit.passmanager.FlowControllerLinear ""qiskit.passmanager.FlowControllerLinear""), so that it can be nested inside another pass manager. **Returns** A linearized pass manager. **Return type** [*FlowControllerLinear*](qiskit.passmanager.FlowControllerLinear ""qiskit.passmanager.flow_controllers.FlowControllerLinear"") ",repo/docs/api/qiskit/1.0\qiskit.passmanager.BasePassManager.mdx "--- title: ConditionalController description: API reference for qiskit.passmanager.ConditionalController in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.passmanager.ConditionalController --- # ConditionalController Bases: [`BaseController`](qiskit.passmanager.BaseController ""qiskit.passmanager.base_tasks.BaseController"") A flow controller runs the pipeline once if the condition is true, or does nothing if the condition is false. Create new flow controller. **Parameters** **options** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any] | None*) – Option for this flow controller. ## Attributes ### passes Alias of tasks for backward compatibility. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### iter\_tasks A custom logic to choose a next task to run. Controller subclass can consume the state to build a proper task pipeline. The updated state after a task execution will be fed back in as the “return” value of any `yield` statements. This indicates the order of task execution is only determined at running time. This method is not allowed to mutate the given state object. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – The state of the passmanager workflow at the beginning of this flow controller’s execution. * **state** – the state of pass manager after the execution of the last task that was yielded. The generator does not need to inspect this if it is irrelevant to its logic, nor update it. **Yields** *Task* – Next task to run. **Return type** [*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator ""(in Python v3.12)"")\[*Task*, [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState""), None] ",repo/docs/api/qiskit/1.0\qiskit.passmanager.ConditionalController.mdx "--- title: DoWhileController description: API reference for qiskit.passmanager.DoWhileController in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.passmanager.DoWhileController --- # DoWhileController Bases: [`BaseController`](qiskit.passmanager.BaseController ""qiskit.passmanager.base_tasks.BaseController"") Run the given tasks in a loop until the `do_while` condition on the property set becomes `False`. The given tasks will always run at least once, and on iteration of the loop, all the tasks will be run (with the exception of a failure state being set). Create new flow controller. **Parameters** **options** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any] | None*) – Option for this flow controller. ## Attributes ### passes Alias of tasks for backward compatibility. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### iter\_tasks A custom logic to choose a next task to run. Controller subclass can consume the state to build a proper task pipeline. The updated state after a task execution will be fed back in as the “return” value of any `yield` statements. This indicates the order of task execution is only determined at running time. This method is not allowed to mutate the given state object. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – The state of the passmanager workflow at the beginning of this flow controller’s execution. * **state** – the state of pass manager after the execution of the last task that was yielded. The generator does not need to inspect this if it is irrelevant to its logic, nor update it. **Yields** *Task* – Next task to run. **Return type** [*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator ""(in Python v3.12)"")\[*Task*, [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState""), None] ",repo/docs/api/qiskit/1.0\qiskit.passmanager.DoWhileController.mdx "--- title: FlowControllerLinear description: API reference for qiskit.passmanager.FlowControllerLinear in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.passmanager.FlowControllerLinear --- # FlowControllerLinear Bases: [`BaseController`](qiskit.passmanager.BaseController ""qiskit.passmanager.base_tasks.BaseController"") A standard flow controller that runs tasks one after the other. Create new flow controller. **Parameters** **options** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any] | None*) – Option for this flow controller. ## Attributes ### passes Alias of tasks for backward compatibility. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### iter\_tasks A custom logic to choose a next task to run. Controller subclass can consume the state to build a proper task pipeline. The updated state after a task execution will be fed back in as the “return” value of any `yield` statements. This indicates the order of task execution is only determined at running time. This method is not allowed to mutate the given state object. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – The state of the passmanager workflow at the beginning of this flow controller’s execution. * **state** – the state of pass manager after the execution of the last task that was yielded. The generator does not need to inspect this if it is irrelevant to its logic, nor update it. **Yields** *Task* – Next task to run. **Return type** [*Generator*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator ""(in Python v3.12)"")\[*Task*, [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState""), None] ",repo/docs/api/qiskit/1.0\qiskit.passmanager.FlowControllerLinear.mdx "--- title: GenericPass description: API reference for qiskit.passmanager.GenericPass in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.passmanager.GenericPass --- # GenericPass Bases: `Task`, [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Base class of a single pass manager task. A pass instance can read and write to the provided [`PropertySet`](qiskit.passmanager.PropertySet ""qiskit.passmanager.PropertySet""), and may modify the input pass manager IR. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run optimization task. **Parameters** **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. **Returns** Optimized Qiskit IR. **Return type** [*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.passmanager.GenericPass.mdx "--- title: PassManagerState description: API reference for qiskit.passmanager.PassManagerState in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.passmanager.PassManagerState --- # PassManagerState Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A portable container object that pass manager tasks communicate through generator. This object can contain every information about the running pass manager workflow, except for the IR object being optimized. The data structure consists of two elements; one for the status of the workflow itself, and another one for the additional information about the IR analyzed through pass executions. This container aims at just providing a robust interface for the `Task.execute()`, and no logic that modifies the container elements must be implemented. This object is mutable, and might be mutated by pass executions. ## Attributes ### workflow\_status Status of the current compilation workflow. ### property\_set Information about IR being optimized. ",repo/docs/api/qiskit/1.0\qiskit.passmanager.PassManagerState.mdx "--- title: PropertySet description: API reference for qiskit.passmanager.PropertySet in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.passmanager.PropertySet --- # PropertySet Bases: [`dict`](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") A default dictionary-like object. ## Methods ### clear ### copy ### fromkeys Create a new dictionary with keys from iterable and values set to value. ### get Return the value for key if key is in the dictionary, else default. ### items ### keys ### pop If key is not found, default is returned if given, otherwise KeyError is raised ### popitem Remove and return a (key, value) pair as a 2-tuple. Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty. ### setdefault Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. ### update If E is present and has a .keys() method, then does: for k in E: D\[k] = E\[k] If E is present and lacks a .keys() method, then does: for k, v in E: D\[k] = v In either case, this is followed by: for k in F: D\[k] = F\[k] ### values ",repo/docs/api/qiskit/1.0\qiskit.passmanager.PropertySet.mdx "--- title: WorkflowStatus description: API reference for qiskit.passmanager.WorkflowStatus in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.passmanager.WorkflowStatus --- # WorkflowStatus , previous_run=RunState.FAIL)"" modifiers=""class""> Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Collection of compilation status of workflow, i.e. pass manager run. This data structure is initialized when the pass manager is run, and recursively handed over to underlying tasks. Each pass will update this status once after being executed, and the lifetime of the workflow status object is the time during which the pass manager is running. ## Attributes ### count Current number of pass execution. ### previous\_run Status of the latest pass run. ### completed\_passes Passes already run that have not been invalidated. ",repo/docs/api/qiskit/1.0\qiskit.passmanager.WorkflowStatus.mdx "--- title: BackendEstimator description: API reference for qiskit.primitives.BackendEstimator in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.BackendEstimator --- # BackendEstimator Bases: [`BaseEstimatorV1`](qiskit.primitives.BaseEstimatorV1 ""qiskit.primitives.base.base_estimator.BaseEstimatorV1"")\[[`PrimitiveJob`](qiskit.primitives.PrimitiveJob ""qiskit.primitives.primitive_job.PrimitiveJob"")\[[`EstimatorResult`](qiskit.primitives.EstimatorResult ""qiskit.primitives.base.estimator_result.EstimatorResult"")]] Evaluates expectation value using Pauli rotation gates. The [`BackendEstimator`](#qiskit.primitives.BackendEstimator ""qiskit.primitives.BackendEstimator"") class is a generic implementation of the `BaseEstimator` interface that is used to wrap a [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") (or [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"")) object in the `BaseEstimator` API. It facilitates using backends that do not provide a native `BaseEstimator` implementation in places that work with `BaseEstimator`. However, if you’re using a provider that has a native implementation of `BaseEstimator`, it is a better choice to leverage that native implementation as it will likely include additional optimizations and be a more efficient implementation. The generic nature of this class precludes doing any provider- or backend-specific optimizations. Initialize a new BackendEstimator instance **Parameters** * **backend** ([*BackendV1*](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") *|*[*BackendV2*](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"")) – Required: the backend to run the primitive on * **options** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *| None*) – Default options. * **abelian\_grouping** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether the observable should be grouped into commuting * **bound\_pass\_manager** ([*PassManager*](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") *| None*) – An optional pass manager to run after parameter binding. * **skip\_transpilation** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If this is set to True the internal compilation of the input circuits is skipped and the circuit objects will be directly executed when this object is called. ## Attributes ### backend Returns: The backend which this estimator object based on ### options Return options values for the estimator. **Returns** options ### preprocessed\_circuits Transpiled quantum circuits produced by preprocessing :returns: List of the transpiled quantum circuit ### transpile\_options Return the transpiler options for transpiling the circuits. ### transpiled\_circuits Transpiled quantum circuits. :returns: List of the transpiled quantum circuit **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the instance has been closed. ## Methods ### run Run the job of the estimation of expectation value(s). `circuits`, `observables`, and `parameter_values` should have the same length. The i-th element of the result is the expectation of observable ```python obs = observables[i] ``` for the state prepared by ```python circ = circuits[i] ``` with bound parameters ```python values = parameter_values[i]. ``` **Parameters** * **circuits** (*Sequence\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] |* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – one or more circuit objects. * **observables** (*Sequence\[BaseOperator |* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*] | BaseOperator |* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – one or more observable objects. Several formats are allowed; importantly, `str` should follow the string representation format for [`Pauli`](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") objects. * **parameter\_values** (*Sequence\[Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]] | Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] |* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – concrete parameters to be bound. * **run\_options** – runtime options used for circuit execution. **Returns** The job object of EstimatorResult. **Raises** * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – Invalid argument type given. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – Invalid argument values given. **Return type** T ### set\_options Set options values for the estimator. **Parameters** **\*\*fields** – The fields to update the options ### set\_transpile\_options Set the transpiler options for transpiler. :param \*\*fields: The fields to update the options ",repo/docs/api/qiskit/1.0\qiskit.primitives.BackendEstimator.mdx "--- title: BackendSampler description: API reference for qiskit.primitives.BackendSampler in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.BackendSampler --- # BackendSampler Bases: [`BaseSamplerV1`](qiskit.primitives.BaseSamplerV1 ""qiskit.primitives.base.base_sampler.BaseSamplerV1"")\[[`PrimitiveJob`](qiskit.primitives.PrimitiveJob ""qiskit.primitives.primitive_job.PrimitiveJob"")\[[`SamplerResult`](qiskit.primitives.SamplerResult ""qiskit.primitives.base.sampler_result.SamplerResult"")]] A `BaseSampler` implementation that provides an interface for leveraging the sampler interface from any backend. This class provides a sampler interface from any backend and doesn’t do any measurement mitigation, it just computes the probability distribution from the counts. It facilitates using backends that do not provide a native `BaseSampler` implementation in places that work with `BaseSampler`. However, if you’re using a provider that has a native implementation of `BaseSampler`, it is a better choice to leverage that native implementation as it will likely include additional optimizations and be a more efficient implementation. The generic nature of this class precludes doing any provider- or backend-specific optimizations. Initialize a new BackendSampler **Parameters** * **backend** ([*BackendV1*](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") *|*[*BackendV2*](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"")) – Required: the backend to run the sampler primitive on * **options** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *| None*) – Default options. * **bound\_pass\_manager** ([*PassManager*](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") *| None*) – An optional pass manager to run after parameter binding. * **skip\_transpilation** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If this is set to True the internal compilation of the input circuits is skipped and the circuit objects will be directly executed when this objected is called. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If backend is not provided ## Attributes ### backend Returns: The backend which this sampler object based on ### options Return options values for the estimator. **Returns** options ### preprocessed\_circuits Preprocessed quantum circuits produced by preprocessing :returns: List of the transpiled quantum circuit **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the instance has been closed. ### transpile\_options Return the transpiler options for transpiling the circuits. ### transpiled\_circuits Transpiled quantum circuits. :returns: List of the transpiled quantum circuit **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the instance has been closed. ## Methods ### run Run the job of the sampling of bitstrings. **Parameters** * **circuits** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *| Sequence\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]*) – One of more circuit objects. * **parameter\_values** (*Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | Sequence\[Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]] | None*) – Parameters to be bound to the circuit. * **run\_options** – Backend runtime options used for circuit execution. **Returns** The job object of the result of the sampler. The i-th result corresponds to `circuits[i]` evaluated with parameters bound as `parameter_values[i]`. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – Invalid arguments are given. **Return type** T ### set\_options Set options values for the estimator. **Parameters** **\*\*fields** – The fields to update the options ### set\_transpile\_options Set the transpiler options for transpiler. :param \*\*fields: The fields to update the options. **Returns** self. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the instance has been closed. ",repo/docs/api/qiskit/1.0\qiskit.primitives.BackendSampler.mdx "--- title: BaseEstimator description: API reference for qiskit.primitives.BaseEstimator in_page_toc_min_heading_level: 1 python_api_type: attribute python_api_name: qiskit.primitives.BaseEstimator --- # BaseEstimator alias of [`BaseEstimatorV1`](qiskit.primitives.BaseEstimatorV1 ""qiskit.primitives.base.base_estimator.BaseEstimatorV1"") ",repo/docs/api/qiskit/1.0\qiskit.primitives.BaseEstimator.mdx "--- title: BaseEstimatorV1 description: API reference for qiskit.primitives.BaseEstimatorV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.BaseEstimatorV1 --- # BaseEstimatorV1 Bases: `BasePrimitive`, [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic ""(in Python v3.12)"")\[`T`] Estimator V1 base class. Base class for Estimator that 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 [ ] 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 [ , # , # ] 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}"") ``` Creating an instance of an Estimator, or using one in a `with` context opens a session that holds resources until the instance is `close()` ed or the context is exited. **Parameters** **options** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *| None*) – Default options. ## Attributes ### options Return options values for the estimator. **Returns** options ## Methods ### run Run the job of the estimation of expectation value(s). `circuits`, `observables`, and `parameter_values` should have the same length. The i-th element of the result is the expectation of observable ```python obs = observables[i] ``` for the state prepared by ```python circ = circuits[i] ``` with bound parameters ```python values = parameter_values[i]. ``` **Parameters** * **circuits** (*Sequence\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] |* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – one or more circuit objects. * **observables** (*Sequence\[BaseOperator |* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*] | BaseOperator |* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – one or more observable objects. Several formats are allowed; importantly, `str` should follow the string representation format for [`Pauli`](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") objects. * **parameter\_values** (*Sequence\[Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]] | Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] |* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – concrete parameters to be bound. * **run\_options** – runtime options used for circuit execution. **Returns** The job object of EstimatorResult. **Raises** * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – Invalid argument type given. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – Invalid argument values given. **Return type** T ### set\_options Set options values for the estimator. **Parameters** **\*\*fields** – The fields to update the options ",repo/docs/api/qiskit/1.0\qiskit.primitives.BaseEstimatorV1.mdx "--- title: BaseEstimatorV2 description: API reference for qiskit.primitives.BaseEstimatorV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.BaseEstimatorV2 --- # BaseEstimatorV2 Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Estimator V2 base class. An estimator estimates expectation values for provided quantum circuit and observable combinations. An Estimator implementation must treat the [`run()`](#qiskit.primitives.BaseEstimatorV2.run ""qiskit.primitives.BaseEstimatorV2.run"") method `precision=None` kwarg as using a default `precision` value. The default value and methods to set it can be determined by the Estimator implementor. ## Methods ### run Estimate expectation values for each provided pub (Primitive Unified Bloc). **Parameters** * **pubs** (*Iterable\[EstimatorPubLike]*) – An iterable of pub-like objects, such as tuples `(circuit, observables)` or `(circuit, observables, parameter_values)`. * **precision** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – The target precision for expectation value estimates of each run Estimator Pub that does not specify its own precision. If None the estimator’s default precision value will be used. **Returns** A job object that contains results. **Return type** [BasePrimitiveJob](qiskit.primitives.BasePrimitiveJob ""qiskit.primitives.BasePrimitiveJob"")\[[PrimitiveResult](qiskit.primitives.PrimitiveResult ""qiskit.primitives.PrimitiveResult"")\[[PubResult](qiskit.primitives.PubResult ""qiskit.primitives.PubResult"")]] ",repo/docs/api/qiskit/1.0\qiskit.primitives.BaseEstimatorV2.mdx "--- title: BasePrimitiveJob description: API reference for qiskit.primitives.BasePrimitiveJob in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.BasePrimitiveJob --- # BasePrimitiveJob Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)""), [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic ""(in Python v3.12)"")\[`ResultT`, `StatusT`] Primitive job abstract base class. Initializes the primitive job. **Parameters** * **job\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A unique id in the context of the primitive used to run the job. * **kwargs** – Any key value metadata to associate with this job. ## Methods ### cancel Attempt to cancel the job. ### cancelled Return whether the job has been cancelled. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### done Return whether the job has successfully run. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### in\_final\_state Return whether the job is in a final job state such as `DONE` or `ERROR`. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### job\_id Return a unique id identifying the job. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### result Return the results of the job. **Return type** *ResultT* ### running Return whether the job is actively running. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### status Return the status of the job. **Return type** *StatusT* ",repo/docs/api/qiskit/1.0\qiskit.primitives.BasePrimitiveJob.mdx "--- title: BaseSampler description: API reference for qiskit.primitives.BaseSampler in_page_toc_min_heading_level: 1 python_api_type: attribute python_api_name: qiskit.primitives.BaseSampler --- # BaseSampler alias of [`BaseSamplerV1`](qiskit.primitives.BaseSamplerV1 ""qiskit.primitives.base.base_sampler.BaseSamplerV1"") ",repo/docs/api/qiskit/1.0\qiskit.primitives.BaseSampler.mdx "--- title: BaseSamplerV1 description: API reference for qiskit.primitives.BaseSamplerV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.BaseSamplerV1 --- # BaseSamplerV1 Bases: `BasePrimitive`, [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic ""(in Python v3.12)"")\[`T`] Sampler V1 base class Base class of Sampler that calculates 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]) ``` **Parameters** **options** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *| None*) – Default options. ## Attributes ### options Return options values for the estimator. **Returns** options ## Methods ### run Run the job of the sampling of bitstrings. **Parameters** * **circuits** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *| Sequence\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]*) – One of more circuit objects. * **parameter\_values** (*Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | Sequence\[Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]] | None*) – Parameters to be bound to the circuit. * **run\_options** – Backend runtime options used for circuit execution. **Returns** The job object of the result of the sampler. The i-th result corresponds to `circuits[i]` evaluated with parameters bound as `parameter_values[i]`. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – Invalid arguments are given. **Return type** T ### set\_options Set options values for the estimator. **Parameters** **\*\*fields** – The fields to update the options ",repo/docs/api/qiskit/1.0\qiskit.primitives.BaseSamplerV1.mdx "--- title: BaseSamplerV2 description: API reference for qiskit.primitives.BaseSamplerV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.BaseSamplerV2 --- # BaseSamplerV2 Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Sampler V2 base class. A Sampler returns samples of quantum circuit outputs. All sampler implementations must implement default value for the `shots` in the [`run()`](#qiskit.primitives.BaseSamplerV2.run ""qiskit.primitives.BaseSamplerV2.run"") method if `None` is given both as a `kwarg` and in all of the pubs. ## Methods ### run Run and collect samples from each pub. **Parameters** * **pubs** (*Iterable\[SamplerPubLike]*) – An iterable of pub-like objects. For example, a list of circuits or tuples `(circuit, parameter_values)`. * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The total number of shots to sample for each sampler pub that does not specify its own shots. If `None`, the primitive’s default shots value will be used, which can vary by implementation. **Returns** The job object of Sampler’s result. **Return type** [BasePrimitiveJob](qiskit.primitives.BasePrimitiveJob ""qiskit.primitives.BasePrimitiveJob"")\[[PrimitiveResult](qiskit.primitives.PrimitiveResult ""qiskit.primitives.PrimitiveResult"")\[[PubResult](qiskit.primitives.PubResult ""qiskit.primitives.PubResult"")]] ",repo/docs/api/qiskit/1.0\qiskit.primitives.BaseSamplerV2.mdx "--- title: BitArray description: API reference for qiskit.primitives.BitArray in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.BitArray --- # BitArray Bases: `ShapedMixin` Stores an array of bit values. This object contains a single, contiguous block of data that represents an array of bitstrings. The last axis is over packed bits, the second last axis is over shots, and the preceding axes correspond to the shape of the pub that was executed to sample these bits. **Parameters** * **array** (*NDArray\[np.uint8]*) – The `uint8` data array. * **num\_bits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – How many bit are in each outcome. **Raises** * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – If the input is not a NumPy array with type `numpy.uint8`. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the input array has fewer than two axes, or the size of the last axis is not the smallest number of bytes that can contain `num_bits`. ## Attributes ### array The raw NumPy array of data. ### ndim ### num\_bits The number of bits in the register that this array stores data for. For example, a `ClassicalRegister(5, ""meas"")` would result in `num_bits=5`. ### num\_shots The number of shots sampled from the register in each configuration. More precisely, the length of the second last axis of [`array`](#qiskit.primitives.BitArray.array ""qiskit.primitives.BitArray.array""). ### shape ### size ## Methods ### bitcount Compute the number of ones appearing in the binary representation of each shot. **Returns** A `numpy.uint64`-array with shape `(*shape, num_shots)`. **Return type** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*dtype*](https://numpy.org/doc/stable/reference/generated/numpy.dtype.html#numpy.dtype ""(in NumPy v1.26)"")\[*uint64*]] ### from\_bool\_array Construct a new bit array from an array of bools. **Parameters** * **array** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")*\[*[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")*,* [*dtype*](https://numpy.org/doc/stable/reference/generated/numpy.dtype.html#numpy.dtype ""(in NumPy v1.26)"")*\[*[*bool\_*](https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.bool_ ""(in NumPy v1.26)"")*]]*) – The array to convert, with “bitstrings” along the last axis. * **order** ([*Literal*](https://docs.python.org/3/library/typing.html#typing.Literal ""(in Python v3.12)"")*\['big', 'little']*) – One of `""big""` or `""little""`, indicating whether `array[..., 0]` correspond to the most significant bits or the least significant bits of each bitstring, respectively. **Returns** A new bit array. **Return type** [*BitArray*](#qiskit.primitives.BitArray ""qiskit.primitives.containers.bit_array.BitArray"") ### from\_counts Construct a new bit array from one or more `Counts`-like objects. The `counts` can have keys that are (uniformly) integers, hexstrings, or bitstrings. Their values represent numbers of occurrences of that value. **Parameters** * **counts** (*Mapping\[*[*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)"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | Iterable\[Mapping\[*[*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)"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – One or more counts-like mappings with the same number of shots. * **num\_bits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The desired number of bits per shot. If unset, the biggest value found sets this value. **Returns** A new bit array with shape `()` for single input counts, or `(N,)` for an iterable of $N$ counts. **Raises** * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If different mappings have different numbers of shots. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If no counts dictionaries are supplied. **Return type** [BitArray](#qiskit.primitives.BitArray ""qiskit.primitives.BitArray"") ### from\_samples Construct a new bit array from an iterable of bitstrings, hexstrings, or integers. All samples are assumed to be integers if the first one is. Strings are all assumed to be bitstrings whenever the first string doesn’t start with `""0x""`. Consider pairing this method with [`reshape()`](#qiskit.primitives.BitArray.reshape ""qiskit.primitives.BitArray.reshape"") if your samples represent nested data. **Parameters** * **samples** (*Iterable\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*] | Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – A list of bitstrings, a list of integers, or a list of hexstrings. * **num\_bits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The desired number of bits per sample. If unset, the biggest sample provided is used to determine this value. **Returns** A new bit array. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If no strings are given. **Return type** [BitArray](#qiskit.primitives.BitArray ""qiskit.primitives.BitArray"") ### get\_bitstrings Return a list of bitstrings. **Parameters** **loc** ([*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)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, ...] | None*) – Which entry of this array to return a dictionary for. If `None`, counts from all positions in this array are unioned together. **Returns** A list of bitstrings. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")] ### get\_counts Return a counts dictionary with bitstring keys. **Parameters** **loc** ([*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)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, ...] | None*) – Which entry of this array to return a dictionary for. If `None`, counts from all positions in this array are unioned together. **Returns** A dictionary mapping bitstrings to the number of occurrences of that bitstring. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#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)"")] ### get\_int\_counts Return a counts dictionary, where bitstrings are stored as `int`s. **Parameters** **loc** ([*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)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, ...] | None*) – Which entry of this array to return a dictionary for. If `None`, counts from all positions in this array are unioned together. **Returns** A dictionary mapping `ints` to the number of occurrences of that `int`. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")\[[int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)""), [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")] ### reshape Return a new reshaped bit array. The [`num_shots`](#qiskit.primitives.BitArray.num_shots ""qiskit.primitives.BitArray.num_shots"") axis is either included or excluded from the reshaping procedure depending on which picture the new shape is compatible with. For example, for a bit array with shape `(20, 5)` and `64` shots, a reshape to `(100,)` would leave the number of shots intact, whereas a reshape to `(200, 32)` would change the number of shots to `32`. **Parameters** **\*shape** ([*int*](https://docs.python.org/3/library/functions.html#int ""(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)"") *| Iterable\[ShapeInput]]*) – The new desired shape. **Returns** A new bit array. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the size corresponding to your new shape is not equal to either [`size`](#qiskit.primitives.BitArray.size ""qiskit.primitives.BitArray.size""), or the product of [`size`](#qiskit.primitives.BitArray.size ""qiskit.primitives.BitArray.size"") and [`num_shots`](#qiskit.primitives.BitArray.num_shots ""qiskit.primitives.BitArray.num_shots""). **Return type** [*BitArray*](#qiskit.primitives.BitArray ""qiskit.primitives.containers.bit_array.BitArray"") ",repo/docs/api/qiskit/1.0\qiskit.primitives.BitArray.mdx "--- title: DataBin description: API reference for qiskit.primitives.DataBin in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.DataBin --- # DataBin Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Base class for data bin containers. Subclasses are typically made via `make_data_bin`, which is a specialization of `make_dataclass`. ",repo/docs/api/qiskit/1.0\qiskit.primitives.DataBin.mdx "--- title: Estimator description: API reference for qiskit.primitives.Estimator in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.Estimator --- # Estimator Bases: [`BaseEstimatorV1`](qiskit.primitives.BaseEstimatorV1 ""qiskit.primitives.base.base_estimator.BaseEstimatorV1"")\[[`PrimitiveJob`](qiskit.primitives.PrimitiveJob ""qiskit.primitives.primitive_job.PrimitiveJob"")\[[`EstimatorResult`](qiskit.primitives.EstimatorResult ""qiskit.primitives.base.estimator_result.EstimatorResult"")]] Reference implementation of [`BaseEstimator`](qiskit.primitives.BaseEstimator ""qiskit.primitives.BaseEstimator""). **Run Options** * **shots** (None or int) – The number of shots. If None, it calculates the exact expectation values. Otherwise, it samples from normal distributions with standard errors as standard deviations using normal distribution approximation. * **seed** (np.random.Generator or int) – Set a fixed seed or generator for the normal distribution. If shots is None, this option is ignored. **Parameters** **options** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *| None*) – Default options. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if some classical bits are not used for measurements. ## Attributes ### options Return options values for the estimator. **Returns** options ## Methods ### run Run the job of the estimation of expectation value(s). `circuits`, `observables`, and `parameter_values` should have the same length. The i-th element of the result is the expectation of observable ```python obs = observables[i] ``` for the state prepared by ```python circ = circuits[i] ``` with bound parameters ```python values = parameter_values[i]. ``` **Parameters** * **circuits** (*Sequence\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] |* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – one or more circuit objects. * **observables** (*Sequence\[BaseOperator |* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*] | BaseOperator |* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – one or more observable objects. Several formats are allowed; importantly, `str` should follow the string representation format for [`Pauli`](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") objects. * **parameter\_values** (*Sequence\[Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]] | Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] |* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – concrete parameters to be bound. * **run\_options** – runtime options used for circuit execution. **Returns** The job object of EstimatorResult. **Raises** * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – Invalid argument type given. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – Invalid argument values given. **Return type** T ### set\_options Set options values for the estimator. **Parameters** **\*\*fields** – The fields to update the options ",repo/docs/api/qiskit/1.0\qiskit.primitives.Estimator.mdx "--- title: EstimatorResult description: API reference for qiskit.primitives.EstimatorResult in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.EstimatorResult --- # EstimatorResult Bases: `_BasePrimitiveResult` Result of Estimator. ```python result = estimator.run(circuits, observables, params).result() ``` where the i-th elements of `result` correspond to the circuit and observable given by `circuits[i]`, `observables[i]`, and the parameter values bounds by `params[i]`. For example, `results.values[i]` gives the expectation value, and `result.metadata[i]` is a metadata dictionary for this circuit and parameters. **Parameters** * **values** (*np.ndarray*) – The array of the expectation values. * **metadata** ([*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 the metadata. ## Attributes ### values ### metadata ",repo/docs/api/qiskit/1.0\qiskit.primitives.EstimatorResult.mdx "--- title: PrimitiveJob description: API reference for qiskit.primitives.PrimitiveJob in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.PrimitiveJob --- # PrimitiveJob Bases: [`BasePrimitiveJob`](qiskit.primitives.BasePrimitiveJob ""qiskit.primitives.base.base_primitive_job.BasePrimitiveJob"")\[`ResultT`, [`JobStatus`](qiskit.providers.JobStatus ""qiskit.providers.jobstatus.JobStatus"")] Primitive job class for the reference implementations of Primitives. **Parameters** **function** – A callable function to execute the job. ## Methods ### cancel Attempt to cancel the job. ### cancelled Return whether the job has been cancelled. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### done Return whether the job has successfully run. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### in\_final\_state Return whether the job is in a final job state such as `DONE` or `ERROR`. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### job\_id Return a unique id identifying the job. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### result Return the results of the job. **Return type** *ResultT* ### running Return whether the job is actively running. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### status Return the status of the job. **Return type** [*JobStatus*](qiskit.providers.JobStatus ""qiskit.providers.jobstatus.JobStatus"") ",repo/docs/api/qiskit/1.0\qiskit.primitives.PrimitiveJob.mdx "--- title: PrimitiveResult description: API reference for qiskit.primitives.PrimitiveResult in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.PrimitiveResult --- # PrimitiveResult Bases: [`Generic`](https://docs.python.org/3/library/typing.html#typing.Generic ""(in Python v3.12)"")\[`T`] A container for multiple pub results and global metadata. **Parameters** * **pub\_results** (*Iterable\[T]*) – Pub results. * **metadata** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any] | None*) – Metadata that is common to all pub results; metadata specific to particular pubs should be placed in their metadata fields. Keys are expected to be strings. ## Attributes ### metadata The metadata of this primitive result. ",repo/docs/api/qiskit/1.0\qiskit.primitives.PrimitiveResult.mdx "--- title: PubResult description: API reference for qiskit.primitives.PubResult in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.PubResult --- # PubResult Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Result of Primitive Unified Bloc. Initialize a pub result. **Parameters** * **data** ([*DataBin*](qiskit.primitives.DataBin ""qiskit.primitives.DataBin"")) – Result data. * **metadata** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any] | None*) – Metadata specific to this pub. Keys are expected to be strings. ## Attributes ### data Result data for the pub. ### metadata Metadata for the pub. ",repo/docs/api/qiskit/1.0\qiskit.primitives.PubResult.mdx "--- title: Sampler description: API reference for qiskit.primitives.Sampler in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.Sampler --- # Sampler Bases: [`BaseSamplerV1`](qiskit.primitives.BaseSamplerV1 ""qiskit.primitives.base.base_sampler.BaseSamplerV1"")\[[`PrimitiveJob`](qiskit.primitives.PrimitiveJob ""qiskit.primitives.primitive_job.PrimitiveJob"")\[[`SamplerResult`](qiskit.primitives.SamplerResult ""qiskit.primitives.base.sampler_result.SamplerResult"")]] Sampler class. [`Sampler`](#qiskit.primitives.Sampler ""qiskit.primitives.Sampler"") is a reference implementation of [`BaseSampler`](qiskit.primitives.BaseSampler ""qiskit.primitives.BaseSampler""). **Run Options** * **shots** (None or int) – The number of shots. If None, it calculates the probabilities. Otherwise, it samples from multinomial distributions. * **seed** (np.random.Generator or int) – Set a fixed seed or generator for the multinomial distribution. If shots is None, this option is ignored. **Parameters** **options** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *| None*) – Default options. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if some classical bits are not used for measurements. ## Attributes ### options Return options values for the estimator. **Returns** options ## Methods ### run Run the job of the sampling of bitstrings. **Parameters** * **circuits** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *| Sequence\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]*) – One of more circuit objects. * **parameter\_values** (*Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | Sequence\[Sequence\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]] | None*) – Parameters to be bound to the circuit. * **run\_options** – Backend runtime options used for circuit execution. **Returns** The job object of the result of the sampler. The i-th result corresponds to `circuits[i]` evaluated with parameters bound as `parameter_values[i]`. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – Invalid arguments are given. **Return type** T ### set\_options Set options values for the estimator. **Parameters** **\*\*fields** – The fields to update the options ",repo/docs/api/qiskit/1.0\qiskit.primitives.Sampler.mdx "--- title: SamplerResult description: API reference for qiskit.primitives.SamplerResult in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.SamplerResult --- # SamplerResult Bases: `_BasePrimitiveResult` Result of Sampler. ```python result = sampler.run(circuits, params).result() ``` where the i-th elements of `result` correspond to the circuit given by `circuits[i]`, and the parameter values bounds by `params[i]`. For example, `results.quasi_dists[i]` gives the quasi-probabilities of bitstrings, and `result.metadata[i]` is a metadata dictionary for this circuit and parameters. **Parameters** * **quasi\_dists** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*QuasiDistribution*](qiskit.result.QuasiDistribution ""qiskit.result.QuasiDistribution"")*]*) – List of the quasi-probabilities. * **metadata** ([*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 the metadata. ## Attributes ### quasi\_dists ### metadata ",repo/docs/api/qiskit/1.0\qiskit.primitives.SamplerResult.mdx "--- title: StatevectorEstimator description: API reference for qiskit.primitives.StatevectorEstimator in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.StatevectorEstimator --- # StatevectorEstimator Bases: [`BaseEstimatorV2`](qiskit.primitives.BaseEstimatorV2 ""qiskit.primitives.base.base_estimator.BaseEstimatorV2"") Simple implementation of [`BaseEstimatorV2`](qiskit.primitives.BaseEstimatorV2 ""qiskit.primitives.BaseEstimatorV2"") with full state vector simulation. This class is implemented via [`Statevector`](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") which turns provided circuits into pure state vectors. These states are subsequently acted on by :class:\~.SparsePauliOp\`, which implies that, at present, this implementation is only compatible with Pauli-based observables. Each tuple of `(circuit, observables, parameter values, precision)`, called an estimator primitive unified bloc (PUB), produces its own array-based result. The `run()` method can be given a sequence of pubs to run in one call. ```python from qiskit.circuit import Parameter, QuantumCircuit from qiskit.primitives import StatevectorEstimator from qiskit.quantum_info import Pauli, SparsePauliOp import matplotlib.pyplot as plt import numpy as np # Define a circuit with two parameters. circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.ry(Parameter(""a""), 0) circuit.rz(Parameter(""b""), 0) circuit.cx(0, 1) circuit.h(0) # Define a sweep over parameter values, where the second axis is over # the two parameters in the circuit. params = np.vstack([ np.linspace(-np.pi, np.pi, 100), np.linspace(-4 * np.pi, 4 * np.pi, 100) ]).T # Define three observables. Many formats are supported here including # classes such as qiskit.quantum_info.SparsePauliOp. The inner length-1 # lists cause this array of observables to have shape (3, 1), rather # than shape (3,) if they were omitted. observables = [ [SparsePauliOp([""XX"", ""IY""], [0.5, 0.5])], [Pauli(""XX"")], [Pauli(""IY"")] ] # Instantiate a new statevector simulation based estimator object. estimator = StatevectorEstimator() # Estimate the expectation value for all 300 combinations of # observables and parameter values, where the pub result will have # shape (3, 100). This shape is due to our array of parameter # bindings having shape (100,), combined with our array of observables # having shape (3, 1) pub = (circuit, observables, params) job = estimator.run([pub]) # Extract the result for the 0th pub (this example only has one pub). result = job.result()[0] # Error-bar information is also available, but the error is 0 # for this StatevectorEstimator. result.data.stds # Pull out the array-based expectation value estimate data from the # result and plot a trace for each observable. for idx, pauli in enumerate(observables): plt.plot(result.data.evs[idx], label=pauli) plt.legend() ``` ![../\_images/qiskit-primitives-StatevectorEstimator-1.png](/images/api/qiskit/1.0/qiskit-primitives-StatevectorEstimator-1.png) **Parameters** * **default\_precision** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The default precision for the estimator if not specified during run. * **seed** (*np.random.Generator |* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The seed or Generator object for random number generation. If None, a random seeded default RNG will be used. ## Attributes ### default\_precision Return the default precision ### seed Return the seed or Generator object for random number generation. ## Methods ### run Estimate expectation values for each provided pub (Primitive Unified Bloc). **Parameters** * **pubs** (*Iterable\[EstimatorPubLike]*) – An iterable of pub-like objects, such as tuples `(circuit, observables)` or `(circuit, observables, parameter_values)`. * **precision** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – The target precision for expectation value estimates of each run Estimator Pub that does not specify its own precision. If None the estimator’s default precision value will be used. **Returns** A job object that contains results. **Return type** [PrimitiveJob](qiskit.primitives.PrimitiveJob ""qiskit.primitives.PrimitiveJob"")\[[PrimitiveResult](qiskit.primitives.PrimitiveResult ""qiskit.primitives.PrimitiveResult"")\[[PubResult](qiskit.primitives.PubResult ""qiskit.primitives.PubResult"")]] ",repo/docs/api/qiskit/1.0\qiskit.primitives.StatevectorEstimator.mdx "--- title: StatevectorSampler description: API reference for qiskit.primitives.StatevectorSampler in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.primitives.StatevectorSampler --- # StatevectorSampler Bases: [`BaseSamplerV2`](qiskit.primitives.BaseSamplerV2 ""qiskit.primitives.base.base_sampler.BaseSamplerV2"") Simple implementation of [`BaseSamplerV2`](qiskit.primitives.BaseSamplerV2 ""qiskit.primitives.BaseSamplerV2"") using full state vector simulation. This class is implemented via [`Statevector`](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") which turns provided circuits into pure state vectors, and is therefore incompatible with mid-circuit measurements (although other implementations may be). As seen in the example below, this sampler supports providing arrays of parameter value sets to bind against a single circuit. Each tuple of `(circuit, parameter values, shots)`, called a sampler primitive unified bloc (PUB), produces its own array-valued result. The [`run()`](#qiskit.primitives.StatevectorSampler.run ""qiskit.primitives.StatevectorSampler.run"") method can be given many pubs at once. ```python from qiskit.circuit import ( Parameter, QuantumCircuit, ClassicalRegister, QuantumRegister ) from qiskit.primitives import StatevectorSampler import matplotlib.pyplot as plt import numpy as np # Define our circuit registers, including classical registers # called 'alpha' and 'beta'. qreg = QuantumRegister(3) alpha = ClassicalRegister(2, ""alpha"") beta = ClassicalRegister(1, ""beta"") # Define a quantum circuit with two parameters. circuit = QuantumCircuit(qreg, alpha, beta) circuit.h(0) circuit.cx(0, 1) circuit.cx(1, 2) circuit.ry(Parameter(""a""), 0) circuit.rz(Parameter(""b""), 0) circuit.cx(1, 2) circuit.cx(0, 1) circuit.h(0) circuit.measure([0, 1], alpha) circuit.measure([2], beta) # Define a sweep over parameter values, where the second axis is over. # the two parameters in the circuit. params = np.vstack([ np.linspace(-np.pi, np.pi, 100), np.linspace(-4 * np.pi, 4 * np.pi, 100) ]).T # Instantiate a new statevector simulation based sampler object. sampler = StatevectorSampler() # Start a job that will return shots for all 100 parameter value sets. pub = (circuit, params) job = sampler.run([pub], shots=256) # Extract the result for the 0th pub (this example only has one pub). result = job.result()[0] # There is one BitArray object for each ClassicalRegister in the # circuit. Here, we can see that the BitArray for alpha contains data # for all 100 sweep points, and that it is indeed storing data for 2 # bits over 256 shots. assert result.data.alpha.shape == (100,) assert result.data.alpha.num_bits == 2 assert result.data.alpha.num_shots == 256 # We can work directly with a binary array in performant applications. raw = result.data.alpha.array # For small registers where it is anticipated to have many counts # associated with the same bitstrings, we can turn the data from, # for example, the 22nd sweep index into a dictionary of counts. counts = result.data.alpha.get_counts(22) # Or, convert into a list of bitstrings that preserve shot order. bitstrings = result.data.alpha.get_bitstrings(22) print(bitstrings) ``` **Parameters** * **default\_shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The default shots for the sampler if not specified during run. * **seed** (*np.random.Generator |* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The seed or Generator object for random number generation. If None, a random seeded default RNG will be used. ## Attributes ### default\_shots Return the default shots ### seed Return the seed or Generator object for random number generation. ## Methods ### run Run and collect samples from each pub. **Parameters** * **pubs** (*Iterable\[SamplerPubLike]*) – An iterable of pub-like objects. For example, a list of circuits or tuples `(circuit, parameter_values)`. * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The total number of shots to sample for each sampler pub that does not specify its own shots. If `None`, the primitive’s default shots value will be used, which can vary by implementation. **Returns** The job object of Sampler’s result. **Return type** [PrimitiveJob](qiskit.primitives.PrimitiveJob ""qiskit.primitives.PrimitiveJob"")\[[PrimitiveResult](qiskit.primitives.PrimitiveResult ""qiskit.primitives.PrimitiveResult"")\[[PubResult](qiskit.primitives.PubResult ""qiskit.primitives.PubResult"")]] ",repo/docs/api/qiskit/1.0\qiskit.primitives.StatevectorSampler.mdx "--- title: Backend description: API reference for qiskit.providers.Backend in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.Backend --- # Backend Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Base common type for all versioned Backend abstract classes. Note this class should not be inherited from directly, it is intended to be used for type checking. When implementing a provider you should use the versioned abstract classes as the parent class and not this class directly. ## Attributes ### version ",repo/docs/api/qiskit/1.0\qiskit.providers.Backend.mdx "--- title: BackendV1 description: API reference for qiskit.providers.BackendV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.BackendV1 --- # BackendV1 Bases: [`Backend`](qiskit.providers.Backend ""qiskit.providers.backend.Backend""), [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Abstract class for Backends This abstract class is to be used for all Backend objects created by a provider. There are several classes of information contained in a Backend. The first are the attributes of the class itself. These should be used to defined the immutable characteristics of the backend. The `options` attribute of the backend is used to contain the dynamic user configurable options of the backend. It should be used more for runtime options that configure how the backend is used. For example, something like a `shots` field for a backend that runs experiments which would contain an int for how many shots to execute. The `properties` attribute is optionally defined [`BackendProperties`](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"") object and is used to return measured properties, or properties of a backend that may change over time. The simplest example of this would be a version string, which will change as a backend is updated, but also could be something like noise parameters for backends that run experiments. This first version of the Backend abstract class is written to be mostly backwards compatible with the legacy providers interface. This includes reusing the model objects [`BackendProperties`](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"") and [`BackendConfiguration`](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration""). This was done to ease the transition for users and provider maintainers to the new versioned providers. Expect, future versions of this abstract class to change the data model and interface. Subclasses of this should override the public method [`run()`](#qiskit.providers.BackendV1.run ""qiskit.providers.BackendV1.run"") and the internal [`_default_options()`](#qiskit.providers.BackendV1._default_options ""qiskit.providers.BackendV1._default_options""): ### \_default\_options Return the default options This method will return a [`qiskit.providers.Options`](qiskit.providers.Options ""qiskit.providers.Options"") subclass object that will be used for the default options. These should be the default parameters to use for the options of the backend. **Returns** **A options object with** default values set **Return type** [qiskit.providers.Options](qiskit.providers.Options ""qiskit.providers.Options"") Initialize a backend class **Parameters** * **configuration** ([*BackendConfiguration*](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"")) – A backend configuration object for the backend object. * **provider** ([*qiskit.providers.Provider*](qiskit.providers.Provider ""qiskit.providers.Provider"")) – Optionally, the provider object that this Backend comes from. * **fields** – kwargs for the values to use to override the default options. **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – if input field not a valid options ## Attributes ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.BackendV1.run ""qiskit.providers.BackendV1.run"") method. ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** [BackendConfiguration](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"") ### name Return the backend name. **Returns** the name of the backend. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### properties Return the backend properties. **Returns** the configuration for the backend. If the backend does not support properties, it returns `None`. **Return type** [BackendProperties](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"") ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### run Run on the backend. This method returns a [`Job`](qiskit.providers.Job ""qiskit.providers.Job"") object that runs circuits. Depending on the backend this may be either an async or sync call. It is at the discretion of the provider to decide whether running should block until the execution is finished or not: the Job class can handle either situation. **Parameters** * **run\_input** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – An individual or a list of [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") or [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") objects to run on the backend. For legacy providers migrating to the new versioned providers, provider interface a [`QasmQobj`](qiskit.qobj.QasmQobj ""qiskit.qobj.QasmQobj"") or [`PulseQobj`](qiskit.qobj.PulseQobj ""qiskit.qobj.PulseQobj"") objects should probably be supported too (but deprecated) for backwards compatibility. Be sure to update the docstrings of subclasses implementing this method to document that. New provider implementations should not do this though as [`qiskit.qobj`](qobj#module-qiskit.qobj ""qiskit.qobj"") will be deprecated and removed along with the legacy providers interface. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** [Job](qiskit.providers.Job ""qiskit.providers.Job"") ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** [BackendStatus](qiskit.providers.models.BackendStatus ""qiskit.providers.models.BackendStatus"") ",repo/docs/api/qiskit/1.0\qiskit.providers.BackendV1.mdx "--- title: BackendV2 description: API reference for qiskit.providers.BackendV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.BackendV2 --- # BackendV2 Bases: [`Backend`](qiskit.providers.Backend ""qiskit.providers.backend.Backend""), [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Abstract class for Backends This abstract class is to be used for all Backend objects created by a provider. This version differs from earlier abstract Backend classes in that the configuration attribute no longer exists. Instead, attributes exposing equivalent required immutable properties of the backend device are added. For example `backend.configuration().n_qubits` is accessible from `backend.num_qubits` now. The `options` attribute of the backend is used to contain the dynamic user configurable options of the backend. It should be used more for runtime options that configure how the backend is used. For example, something like a `shots` field for a backend that runs experiments which would contain an int for how many shots to execute. If migrating a provider from [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") one thing to keep in mind is for backwards compatibility you might need to add a configuration method that will build a [`BackendConfiguration`](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"") object and [`BackendProperties`](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"") from the attributes defined in this class for backwards compatibility. A backend object can optionally contain methods named `get_translation_stage_plugin` and `get_scheduling_stage_plugin`. If these methods are present on a backend object and this object is used for [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") or [`generate_preset_pass_manager()`](transpiler_preset#qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager ""qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager"") the transpilation process will default to using the output from those methods as the scheduling stage and the translation compilation stage. This enables a backend which has custom requirements for compilation to specify a stage plugin for these stages to enable custom transformation of the circuit to ensure it is runnable on the backend. These hooks are enabled by default and should only be used to enable extra compilation steps if they are **required** to ensure a circuit is executable on the backend or have the expected level of performance. These methods are passed no input arguments and are expected to return a `str` representing the method name which should be a stage plugin (see: [`qiskit.transpiler.preset_passmanagers.plugin`](transpiler_plugins#module-qiskit.transpiler.preset_passmanagers.plugin ""qiskit.transpiler.preset_passmanagers.plugin"") for more details on plugins). The typical expected use case is for a backend provider to implement a stage plugin for `translation` or `scheduling` that contains the custom compilation passes and then for the hook methods on the backend object to return the plugin name so that [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") will use it by default when targetting the backend. Subclasses of this should override the public method [`run()`](#qiskit.providers.BackendV2.run ""qiskit.providers.BackendV2.run"") and the internal [`_default_options()`](#qiskit.providers.BackendV2._default_options ""qiskit.providers.BackendV2._default_options""): ### \_default\_options Return the default options This method will return a [`qiskit.providers.Options`](qiskit.providers.Options ""qiskit.providers.Options"") subclass object that will be used for the default options. These should be the default parameters to use for the options of the backend. **Returns** **A options object with** default values set **Return type** [qiskit.providers.Options](qiskit.providers.Options ""qiskit.providers.Options"") Initialize a BackendV2 based backend **Parameters** * **provider** ([*Provider*](qiskit.providers.Provider ""qiskit.providers.provider.Provider"")) – An optional backwards reference to the [`Provider`](qiskit.providers.Provider ""qiskit.providers.Provider"") object that the backend is from * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – An optional name for the backend * **description** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – An optional description of the backend * **online\_date** ([*datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime ""(in Python v3.12)"")) – An optional datetime the backend was brought online * **backend\_version** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – An optional backend version string. This differs from the [`version`](#qiskit.providers.BackendV2.version ""qiskit.providers.BackendV2.version"") attribute as [`version`](#qiskit.providers.BackendV2.version ""qiskit.providers.BackendV2.version"") is for the abstract [`Backend`](qiskit.providers.Backend ""qiskit.providers.Backend"") abstract interface version of the object while `backend_version` is for versioning the backend itself. * **fields** – kwargs for the values to use to override the default options. **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If a field is specified that’s outside the backend’s options ## Attributes ### coupling\_map Return the [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") object ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Returns** The output signal timestep in seconds. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the output signal timestep ### instruction\_durations Return the [`InstructionDurations`](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"") object. ### instruction\_schedule\_map Return the [`InstructionScheduleMap`](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"") for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` ### max\_circuits The maximum number of circuits (or Pulse schedules) that can be run in a single job. If there is no limit this will return None ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Returns** The grouping of measurements which are multiplexed **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### num\_qubits Return the number of qubits the backend has. ### operation\_names A list of instruction names that the backend supports. ### operations A list of [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") instances that the backend supports. ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.BackendV2.run ""qiskit.providers.BackendV2.run"") method. ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### target A [`qiskit.transpiler.Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object for the backend. **Return type** [Target](qiskit.transpiler.Target ""qiskit.transpiler.Target"") ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as [`BackendV2.version`](#qiskit.providers.BackendV2.version ""qiskit.providers.BackendV2.version""), which is the version of the [`Backend`](qiskit.providers.Backend ""qiskit.providers.Backend"") abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** [AcquireChannel](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** ([*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)"")*]*) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[[ControlChannel](qiskit.pulse.channels.ControlChannel ""qiskit.pulse.channels.ControlChannel"")] **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** [DriveChannel](qiskit.pulse.channels.DriveChannel ""qiskit.pulse.channels.DriveChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** [MeasureChannel](qiskit.pulse.channels.MeasureChannel ""qiskit.pulse.channels.MeasureChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(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)"")*]*) – The qubit to get the [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") object for. This can be a single integer for 1 qubit or a list of qubits and a list of [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") objects will be returned in the same order **Returns** The [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the qubit properties **Return type** [*QubitProperties*](qiskit.providers.QubitProperties ""qiskit.providers.backend.QubitProperties"") | [*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")\[[*QubitProperties*](qiskit.providers.QubitProperties ""qiskit.providers.backend.QubitProperties"")] ### run Run on the backend. This method returns a [`Job`](qiskit.providers.Job ""qiskit.providers.Job"") object that runs circuits. Depending on the backend this may be either an async or sync call. It is at the discretion of the provider to decide whether running should block until the execution is finished or not: the Job class can handle either situation. **Parameters** * **run\_input** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *or*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – An individual or a list of [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""), [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock""), or [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** [Job](qiskit.providers.Job ""qiskit.providers.Job"") ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ",repo/docs/api/qiskit/1.0\qiskit.providers.BackendV2.mdx "--- title: BackendV2Converter description: API reference for qiskit.providers.BackendV2Converter in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.BackendV2Converter --- # BackendV2Converter Bases: [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.backend.BackendV2"") 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. This class implements the [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") interface and is used to enable common access patterns between [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") and [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2""). This class should only be used if you need a [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") and still need compatibility with [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1""). When using custom calibrations (or other custom workflows) it is **not** recommended to mutate the `BackendV1` object before applying this converter. For example, in order to convert a `BackendV1` object with a customized `defaults().instruction_schedule_map`, which has a custom calibration for an operation, the operation name must be in `configuration().basis_gates` and `name_mapping` must be supplied for the operation. Otherwise, the operation will be dropped in the resulting `BackendV2` object. Instead it is typically better to add custom calibrations **after** applying this converter instead of updating `BackendV1.defaults()` in advance. For example: ```python backend_v2 = BackendV2Converter(backend_v1) backend_v2.target.add_instruction( custom_gate, {(0, 1): InstructionProperties(calibration=custom_sched)} ) ``` Initialize a BackendV2 converter instance based on a BackendV1 instance. **Parameters** * **backend** ([*BackendV1*](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"")) – The input [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") based backend to wrap in a [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") interface * **name\_mapping** (*Optional\[Dict\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any]]*) – An optional dictionary that maps custom gate/operation names in `backend` to an [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation"") object representing that gate/operation. By default most standard gates names are mapped to the standard gate object from [`qiskit.circuit.library`](circuit_library#module-qiskit.circuit.library ""qiskit.circuit.library"") this only needs to be specified if the input `backend` defines gates in names outside that set. * **add\_delay** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to true a [`Delay`](qiskit.circuit.Delay ""qiskit.circuit.Delay"") operation will be added to the target as a supported operation for all qubits * **filter\_faulty** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If the [`BackendProperties`](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"") object (if present) for `backend` has any qubits or gates flagged as non-operational filter those from the output target. ## Attributes ### coupling\_map Return the [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") object ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm ### instruction\_durations Return the [`InstructionDurations`](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"") object. ### instruction\_schedule\_map Return the [`InstructionScheduleMap`](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"") for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` ### max\_circuits ### meas\_map ### num\_qubits Return the number of qubits the backend has. ### operation\_names A list of instruction names that the backend supports. ### operations A list of [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") instances that the backend supports. ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.BackendV2Converter.run ""qiskit.providers.BackendV2Converter.run"") method. ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### target A [`qiskit.transpiler.Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object for the backend. **Return type** [Target](qiskit.transpiler.Target ""qiskit.transpiler.Target"") ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as [`BackendV2.version`](qiskit.providers.BackendV2#version ""qiskit.providers.BackendV2.version""), which is the version of the [`Backend`](qiskit.providers.Backend ""qiskit.providers.Backend"") abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** [AcquireChannel](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** ([*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)"")*]*) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[[ControlChannel](qiskit.pulse.channels.ControlChannel ""qiskit.pulse.channels.ControlChannel"")] **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** [DriveChannel](qiskit.pulse.channels.DriveChannel ""qiskit.pulse.channels.DriveChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** [MeasureChannel](qiskit.pulse.channels.MeasureChannel ""qiskit.pulse.channels.MeasureChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(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)"")*]*) – The qubit to get the [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") object for. This can be a single integer for 1 qubit or a list of qubits and a list of [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") objects will be returned in the same order **Returns** The [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the qubit properties **Return type** [*QubitProperties*](qiskit.providers.QubitProperties ""qiskit.providers.backend.QubitProperties"") | [*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")\[[*QubitProperties*](qiskit.providers.QubitProperties ""qiskit.providers.backend.QubitProperties"")] ### run Run on the backend. This method returns a [`Job`](qiskit.providers.Job ""qiskit.providers.Job"") object that runs circuits. Depending on the backend this may be either an async or sync call. It is at the discretion of the provider to decide whether running should block until the execution is finished or not: the Job class can handle either situation. **Parameters** * **run\_input** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *or*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – An individual or a list of [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""), [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock""), or [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** [Job](qiskit.providers.Job ""qiskit.providers.Job"") ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ",repo/docs/api/qiskit/1.0\qiskit.providers.BackendV2Converter.mdx "--- title: BasicProvider description: API reference for qiskit.providers.basic_provider.BasicProvider in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.basic_provider.BasicProvider --- # BasicProvider Bases: [`ProviderV1`](qiskit.providers.ProviderV1 ""qiskit.providers.provider.ProviderV1"") Provider for test simulators. ## Attributes ### version ## Methods ### backends Return a list of backends matching the specified filtering. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – name of the backend. * **\*\*kwargs** – dict used for filtering. **Returns** **a list of Backends that match the filtering** criteria. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[Backend](qiskit.providers.Backend ""qiskit.providers.Backend"")] ### get\_backend Return a single backend matching the specified filtering. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – name of the backend. * **\*\*kwargs** – dict used for filtering. **Returns** a backend matching the filtering. **Return type** [Backend](qiskit.providers.Backend ""qiskit.providers.Backend"") **Raises** [**QiskitBackendNotFoundError**](providers#qiskit.providers.QiskitBackendNotFoundError ""qiskit.providers.QiskitBackendNotFoundError"") – if no backend could be found or more than one backend matches the filtering criteria. ",repo/docs/api/qiskit/1.0\qiskit.providers.basic_provider.BasicProvider.mdx "--- title: BasicProviderError description: API reference for qiskit.providers.basic_provider.BasicProviderError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit.providers.basic_provider.BasicProviderError --- # qiskit.providers.basic\_provider.BasicProviderError Base class for errors raised by the Basic Provider. Set the error message. ",repo/docs/api/qiskit/1.0\qiskit.providers.basic_provider.BasicProviderError.mdx "--- title: BasicProviderJob description: API reference for qiskit.providers.basic_provider.BasicProviderJob in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.basic_provider.BasicProviderJob --- # BasicProviderJob Bases: [`JobV1`](qiskit.providers.JobV1 ""qiskit.providers.job.JobV1"") BasicProviderJob class. Initializes the asynchronous job. **Parameters** * **backend** – the backend used to run the job. * **job\_id** – a unique id in the context of the backend used to run the job. * **kwargs** – Any key value metadata to associate with this job. ## Attributes ### version ## Methods ### backend Return the instance of the backend used for this job. ### cancel Attempt to cancel the job. ### cancelled Return whether the job has been cancelled. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### done Return whether the job has successfully run. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### in\_final\_state Return whether the job is in a final job state such as `DONE` or `ERROR`. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### job\_id Return a unique id identifying the job. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### result Get job result . **Returns** Result object **Return type** [qiskit.result.Result](qiskit.result.Result ""qiskit.result.Result"") ### running Return whether the job is actively running. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### status Gets the status of the job by querying the Python’s future **Returns** The current JobStatus **Return type** [qiskit.providers.JobStatus](qiskit.providers.JobStatus ""qiskit.providers.JobStatus"") ### submit Submit the job to the backend for execution. **Raises** [**JobError**](providers#qiskit.providers.JobError ""qiskit.providers.JobError"") – if trying to re-submit the job. ### wait\_for\_final\_state Poll the job status until it progresses to a final state such as `DONE` or `ERROR`. **Parameters** * **timeout** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – Seconds to wait for the job. If `None`, wait indefinitely. * **wait** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Seconds between queries. * **callback** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"") *| None*) – Callback function invoked after each query. The following positional arguments are provided to the callback function: * job\_id: Job ID * job\_status: Status of the job from the last query * job: This BaseJob instance Note: different subclass might provide different arguments to the callback function. **Raises** [**JobTimeoutError**](providers#qiskit.providers.JobTimeoutError ""qiskit.providers.JobTimeoutError"") – If the job does not reach a final state before the specified timeout. ",repo/docs/api/qiskit/1.0\qiskit.providers.basic_provider.BasicProviderJob.mdx "--- title: BasicSimulator description: API reference for qiskit.providers.basic_provider.BasicSimulator in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.basic_provider.BasicSimulator --- # BasicSimulator Bases: [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.backend.BackendV2"") Python implementation of a basic (non-efficient) quantum simulator. **Parameters** * **provider** ([*Provider*](qiskit.providers.Provider ""qiskit.providers.Provider"") *| None*) – An optional backwards reference to the [`Provider`](qiskit.providers.Provider ""qiskit.providers.Provider"") object that the backend is from. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"") *| None*) – An optional target to configure the simulator. * **fields** – kwargs for the values to use to override the default options. **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If a field is specified that’s outside the backend’s options. ## Attributes ### MAX\_QUBITS\_MEMORY ### coupling\_map Return the [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") object ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Returns** The output signal timestep in seconds. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the output signal timestep ### instruction\_durations Return the [`InstructionDurations`](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"") object. ### instruction\_schedule\_map Return the [`InstructionScheduleMap`](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"") for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` ### max\_circuits ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Returns** The grouping of measurements which are multiplexed **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### num\_qubits Return the number of qubits the backend has. ### operation\_names A list of instruction names that the backend supports. ### operations A list of [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") instances that the backend supports. ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.basic_provider.BasicSimulator.run ""qiskit.providers.basic_provider.BasicSimulator.run"") method. ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as [`BackendV2.version`](qiskit.providers.BackendV2#version ""qiskit.providers.BackendV2.version""), which is the version of the [`Backend`](qiskit.providers.Backend ""qiskit.providers.Backend"") abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** [AcquireChannel](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### configuration Return the simulator backend configuration. **Returns** The configuration for the backend. **Return type** [*BackendConfiguration*](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.backendconfiguration.BackendConfiguration"") ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** ([*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)"")*]*) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[[ControlChannel](qiskit.pulse.channels.ControlChannel ""qiskit.pulse.channels.ControlChannel"")] **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** [DriveChannel](qiskit.pulse.channels.DriveChannel ""qiskit.pulse.channels.DriveChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** [MeasureChannel](qiskit.pulse.channels.MeasureChannel ""qiskit.pulse.channels.MeasureChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(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)"")*]*) – The qubit to get the [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") object for. This can be a single integer for 1 qubit or a list of qubits and a list of [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") objects will be returned in the same order **Returns** The [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the qubit properties **Return type** [*QubitProperties*](qiskit.providers.QubitProperties ""qiskit.providers.backend.QubitProperties"") | [*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")\[[*QubitProperties*](qiskit.providers.QubitProperties ""qiskit.providers.backend.QubitProperties"")] ### run Run on the backend. **Parameters** * **run\_input** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]*) – payload of the experiment * **backend\_options** – backend options **Returns** derived from BaseJob **Return type** [BasicProviderJob](qiskit.providers.basic_provider.BasicProviderJob ""qiskit.providers.basic_provider.BasicProviderJob"") **Additional Information:** **backend\_options: Is a dict of options for the backend. It may contain** * “initial\_statevector”: vector\_like The “initial\_statevector” option specifies a custom initial initial statevector for the simulator to be used instead of the all zero state. This size of this vector must be correct for the number of qubits in `run_input` parameter. Example: ```python backend_options = { ""initial_statevector"": np.array([1, 0, 0, 1j]) / np.sqrt(2), } ``` ### run\_experiment Run an experiment (circuit) and return a single experiment result. **Parameters** **experiment** ([*QasmQobjExperiment*](qiskit.qobj.QasmQobjExperiment ""qiskit.qobj.qasm_qobj.QasmQobjExperiment"")) – experiment from qobj experiments list **Returns** A result dictionary which looks something like: ```python { ""name"": name of this experiment (obtained from qobj.experiment header) ""seed"": random seed used for simulation ""shots"": number of shots used in the simulation ""data"": { ""counts"": {'0x9: 5, ...}, ""memory"": ['0x9', '0xF', '0x1D', ..., '0x9'] }, ""status"": status string for the simulation ""success"": boolean ""time_taken"": simulation time of this single experiment } ``` **Raises** [**BasicProviderError**](qiskit.providers.basic_provider.BasicProviderError ""qiskit.providers.basic_provider.BasicProviderError"") – if an error occurred. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")\[[str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)""), …] ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ",repo/docs/api/qiskit/1.0\qiskit.providers.basic_provider.BasicSimulator.mdx "--- title: convert_to_target description: API reference for qiskit.providers.convert_to_target in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.providers.convert_to_target --- # qiskit.providers.convert\_to\_target Decode transpiler target from backend data set. This function generates `` Target` `` instance from intermediate legacy objects such as [`BackendProperties`](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"") and [`PulseDefaults`](qiskit.providers.models.PulseDefaults ""qiskit.providers.models.PulseDefaults""). These objects are usually components of the legacy [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") model. **Parameters** * **configuration** ([*BackendConfiguration*](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.backendconfiguration.BackendConfiguration"")) – Backend configuration as `BackendConfiguration` * **properties** ([*BackendProperties*](qiskit.providers.models.BackendProperties ""qiskit.providers.models.backendproperties.BackendProperties"") *| None*) – Backend property dictionary or `BackendProperties` * **defaults** ([*PulseDefaults*](qiskit.providers.models.PulseDefaults ""qiskit.providers.models.pulsedefaults.PulseDefaults"") *| None*) – Backend pulse defaults dictionary or `PulseDefaults` * **custom\_name\_mapping** ([*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)"")*,* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")*] | None*) – A name mapping must be supplied for the operation not included in Qiskit Standard Gate name mapping, otherwise the operation will be dropped in the resulting `Target` object. * **add\_delay** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, adds delay to the instruction set. * **filter\_faulty** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, this filters the non-operational qubits. **Returns** A `Target` instance. ",repo/docs/api/qiskit/1.0\qiskit.providers.convert_to_target.mdx "--- title: Fake127QPulseV1 description: API reference for qiskit.providers.fake_provider.Fake127QPulseV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.fake_provider.Fake127QPulseV1 --- # Fake127QPulseV1 Bases: [`FakePulseBackend`](providers_fake_provider#qiskit.providers.fake_provider.FakePulseBackend ""qiskit.providers.fake_provider.fake_pulse_backend.FakePulseBackend"") A fake **pulse** backend with the following characteristics: * num\_qubits: 127 * coupling\_map: heavy-hex based * basis\_gates: `[""id"", ""rz"", ""sx"", ""x"", ""cx"", ""reset""]` * **scheduled instructions:** \# `{'id', 'measure', 'u2', 'rz', 'x', 'u3', 'sx', 'u1'}` for all individual qubits # `{'cx'}` for all edges # `{'measure'}` for (0, …, 127) 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 ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.fake_provider.Fake127QPulseV1.run ""qiskit.providers.fake_provider.Fake127QPulseV1.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** [BackendConfiguration](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"") ### defaults Returns a snapshot of device defaults ### name Return the backend name. **Returns** the name of the backend. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### properties Returns a snapshot of device properties ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** [BackendStatus](qiskit.providers.models.BackendStatus ""qiskit.providers.models.BackendStatus"") ",repo/docs/api/qiskit/1.0\qiskit.providers.fake_provider.Fake127QPulseV1.mdx "--- title: Fake1Q description: API reference for qiskit.providers.fake_provider.Fake1Q in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.fake_provider.Fake1Q --- # Fake1Q Bases: [`FakeBackend`](providers_fake_provider#qiskit.providers.fake_provider.FakeBackend ""qiskit.providers.fake_provider.fake_backend.FakeBackend"") A fake 1Q backend. 0 ## Attributes ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.fake_provider.Fake1Q.run ""qiskit.providers.fake_provider.Fake1Q.run"") method. ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** [BackendConfiguration](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"") ### name Return the backend name. **Returns** the name of the backend. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### properties Return backend properties ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** [BackendStatus](qiskit.providers.models.BackendStatus ""qiskit.providers.models.BackendStatus"") ",repo/docs/api/qiskit/1.0\qiskit.providers.fake_provider.Fake1Q.mdx "--- title: Fake20QV1 description: API reference for qiskit.providers.fake_provider.Fake20QV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.fake_provider.Fake20QV1 --- # Fake20QV1 Bases: [`FakeQasmBackend`](providers_fake_provider#qiskit.providers.fake_provider.FakeQasmBackend ""qiskit.providers.fake_provider.fake_qasm_backend.FakeQasmBackend"") A fake backend with the following characteristics: * num\_qubits: 20 * coupling\_map: > ```python > 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 > ↕ ↕ > 05 ↔ 06 ↔ 07 ↔ 08 ↔ 09 > ↕ ↕ ↕ > 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 > ↕ ↕ > 15 ↔ 16 ↔ 17 ↔ 18 ↔ 19 > ``` * basis\_gates: `[""id"", ""u1"", ""u2"", ""u3"", ""cx""]` 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 ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.fake_provider.Fake20QV1.run ""qiskit.providers.fake_provider.Fake20QV1.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** [BackendConfiguration](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"") ### name Return the backend name. **Returns** the name of the backend. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### properties Returns a snapshot of device properties ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** [BackendStatus](qiskit.providers.models.BackendStatus ""qiskit.providers.models.BackendStatus"") ",repo/docs/api/qiskit/1.0\qiskit.providers.fake_provider.Fake20QV1.mdx "--- title: Fake27QPulseV1 description: API reference for qiskit.providers.fake_provider.Fake27QPulseV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.fake_provider.Fake27QPulseV1 --- # Fake27QPulseV1 Bases: [`FakePulseBackend`](providers_fake_provider#qiskit.providers.fake_provider.FakePulseBackend ""qiskit.providers.fake_provider.fake_pulse_backend.FakePulseBackend"") A fake **pulse** backend with the following characteristics: * num\_qubits: 27 * coupling\_map: > ```python > 06 17 > ↕ ↕ > 00 ↔ 01 ↔ 04 ↔ 07 ↔ 10 ↔ 12 ↔ 15 ↔ 18 ↔ 20 ↔ 23 > ↕ ↕ ↕ > 02 13 24 > ↕ ↕ ↕ > 03 ↔ 05 ↔ 08 ↔ 11 ↔ 14 ↔ 16 ↔ 19 ↔ 22 ↔ 25 ↔ 26 > ↕ ↕ > 09 20 > ``` * basis\_gates: `[""id"", ""rz"", ""sx"", ""x"", ""cx"", ""reset""]` * **scheduled instructions:** \# `{'id', 'rz', 'u2', 'x', 'u3', 'sx', 'measure', 'u1'}` for all individual qubits # `{'cx'}` for all edges # `{'measure'}` for (0, …, 26) 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 ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.fake_provider.Fake27QPulseV1.run ""qiskit.providers.fake_provider.Fake27QPulseV1.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** [BackendConfiguration](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"") ### defaults Returns a snapshot of device defaults ### name Return the backend name. **Returns** the name of the backend. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### properties Returns a snapshot of device properties ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** [BackendStatus](qiskit.providers.models.BackendStatus ""qiskit.providers.models.BackendStatus"") ",repo/docs/api/qiskit/1.0\qiskit.providers.fake_provider.Fake27QPulseV1.mdx "--- title: Fake5QV1 description: API reference for qiskit.providers.fake_provider.Fake5QV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.fake_provider.Fake5QV1 --- # Fake5QV1 Bases: [`FakeQasmBackend`](providers_fake_provider#qiskit.providers.fake_provider.FakeQasmBackend ""qiskit.providers.fake_provider.fake_qasm_backend.FakeQasmBackend"") A fake backend with the following characteristics: * num\_qubits: 5 * coupling\_map: > ```python > 1 > / | > 0 - 2 - 3 > | / > 4 > ``` * basis\_gates: `[""id"", ""rz"", ""sx"", ""x"", ""cx"", ""reset""]` 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 ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.fake_provider.Fake5QV1.run ""qiskit.providers.fake_provider.Fake5QV1.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** [BackendConfiguration](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"") ### name Return the backend name. **Returns** the name of the backend. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### properties Returns a snapshot of device properties ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** [BackendStatus](qiskit.providers.models.BackendStatus ""qiskit.providers.models.BackendStatus"") ",repo/docs/api/qiskit/1.0\qiskit.providers.fake_provider.Fake5QV1.mdx "--- title: Fake7QPulseV1 description: API reference for qiskit.providers.fake_provider.Fake7QPulseV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.fake_provider.Fake7QPulseV1 --- # Fake7QPulseV1 Bases: [`FakePulseBackend`](providers_fake_provider#qiskit.providers.fake_provider.FakePulseBackend ""qiskit.providers.fake_provider.fake_pulse_backend.FakePulseBackend"") A fake **pulse** backend with the following characteristics: * num\_qubits: 7 * coupling\_map: > ```python > 0 ↔ 1 ↔ 3 ↔ 5 ↔ 6 > ↕ ↕ > 2 4 > ``` * basis\_gates: `[""id"", ""rz"", ""sx"", ""x"", ""cx"", ""reset""]` * **scheduled instructions:** \# `{'u3', 'id', 'measure', 'u2', 'x', 'u1', 'sx', 'rz'}` for all individual qubits # `{'cx'}` for all edges # `{'measure'}` for (0, 1, 2, 3, 4, 5, 6) 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 ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.fake_provider.Fake7QPulseV1.run ""qiskit.providers.fake_provider.Fake7QPulseV1.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** [BackendConfiguration](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"") ### defaults Returns a snapshot of device defaults ### name Return the backend name. **Returns** the name of the backend. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### properties Returns a snapshot of device properties ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** [BackendStatus](qiskit.providers.models.BackendStatus ""qiskit.providers.models.BackendStatus"") ",repo/docs/api/qiskit/1.0\qiskit.providers.fake_provider.Fake7QPulseV1.mdx "--- title: FakeOpenPulse2Q description: API reference for qiskit.providers.fake_provider.FakeOpenPulse2Q in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.fake_provider.FakeOpenPulse2Q --- # FakeOpenPulse2Q Bases: [`FakeBackend`](providers_fake_provider#qiskit.providers.fake_provider.FakeBackend ""qiskit.providers.fake_provider.fake_backend.FakeBackend"") A fake 2 qubit backend for pulse test. 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 ## Attributes ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.fake_provider.FakeOpenPulse2Q.run ""qiskit.providers.fake_provider.FakeOpenPulse2Q.run"") method. ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** [BackendConfiguration](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"") ### defaults Return the default pulse-related settings provided by the backend (such as gate to Schedule mappings). ### name Return the backend name. **Returns** the name of the backend. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### properties Return the measured characteristics of the backend. ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** [BackendStatus](qiskit.providers.models.BackendStatus ""qiskit.providers.models.BackendStatus"") ",repo/docs/api/qiskit/1.0\qiskit.providers.fake_provider.FakeOpenPulse2Q.mdx "--- title: FakeOpenPulse3Q description: API reference for qiskit.providers.fake_provider.FakeOpenPulse3Q in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.fake_provider.FakeOpenPulse3Q --- # FakeOpenPulse3Q Bases: [`FakeBackend`](providers_fake_provider#qiskit.providers.fake_provider.FakeBackend ""qiskit.providers.fake_provider.fake_backend.FakeBackend"") Trivial extension of the FakeOpenPulse2Q. 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 ## Attributes ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.fake_provider.FakeOpenPulse3Q.run ""qiskit.providers.fake_provider.FakeOpenPulse3Q.run"") method. ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** [BackendConfiguration](qiskit.providers.models.BackendConfiguration ""qiskit.providers.models.BackendConfiguration"") ### defaults ### name Return the backend name. **Returns** the name of the backend. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### properties Return backend properties ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** [BackendStatus](qiskit.providers.models.BackendStatus ""qiskit.providers.models.BackendStatus"") ",repo/docs/api/qiskit/1.0\qiskit.providers.fake_provider.FakeOpenPulse3Q.mdx "--- title: GenericBackendV2 description: API reference for qiskit.providers.fake_provider.GenericBackendV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.fake_provider.GenericBackendV2 --- # GenericBackendV2 Bases: [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.backend.BackendV2"") Generic [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") implementation with a configurable constructor. This class will return a [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") instance that runs on a local simulator (in the spirit of fake backends) and contains all the necessary information to test backend-interfacing components, such as the transpiler. A [`GenericBackendV2`](#qiskit.providers.fake_provider.GenericBackendV2 ""qiskit.providers.fake_provider.GenericBackendV2"") instance can be constructed from as little as a specified `num_qubits`, but users can additionally configure the basis gates, coupling map, ability to run dynamic circuits (control flow instructions), instruction calibrations and dtm. The remainder of the backend properties are generated by randomly sampling from default ranges extracted from historical IBM backend data. The seed for this random generation can be fixed to ensure the reproducibility of the backend output. This backend only supports gates in the standard library, if you need a more flexible backend, there is always the option to directly instantiate a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object to use for transpilation. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of qubits that will be used to construct the backend’s target. Note that, while there is no limit in the size of the target that can be constructed, this backend runs on local noisy simulators, and these might present limitations in the number of qubits that can be simulated. * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*] | None*) – List of basis gate names to be supported by the target. These must be part of the standard qiskit circuit library. The default set of basis gates is `[""id"", ""rz"", ""sx"", ""x"", ""cx""]` The `""reset""`, `""delay""`, and `""measure""` instructions are always supported by default, even if not specified via `basis_gates`. * **coupling\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]] |* [*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") *| None*) – Optional coupling map for the backend. Multiple formats are supported: 1. [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") instance 2. List, must be given as an edge list representing the two qubit interactions supported by the backend, for example: `[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]` If `coupling_map` is specified, it must match the number of qubits specified in `num_qubits`. If `coupling_map` is not specified, a fully connected coupling map will be generated with `num_qubits` qubits. * **control\_flow** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Flag to enable control flow directives on the target (defaults to False). * **calibrate\_instructions** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *|*[*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"") *| None*) – Instruction calibration settings, this argument supports both boolean and [`InstructionScheduleMap`](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"") as input types, and is `None` by default: 1. If `calibrate_instructions==None`, no calibrations will be added to the target. 2. **If `calibrate_instructions==True`, all gates will be calibrated for all** qubits using the default pulse schedules generated internally. 3. **If `calibrate_instructions==False`, all gates will be “calibrated” for** all qubits with an empty pulse schedule. 4. **If an [`InstructionScheduleMap`](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"") instance is given, the calibrations** in this instruction schedule map will be appended to the target instead of the default pulse schedules (this allows for custom calibrations). * **dtm** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – System time resolution of output signals in nanoseconds. None by default. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Optional seed for generation of default values. ## Attributes ### coupling\_map Return the [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") object ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals ### instruction\_durations Return the [`InstructionDurations`](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"") object. ### instruction\_schedule\_map Return the [`InstructionScheduleMap`](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"") for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` ### max\_circuits ### meas\_map ### num\_qubits Return the number of qubits the backend has. ### operation\_names A list of instruction names that the backend supports. ### operations A list of [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") instances that the backend supports. ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit.providers.fake_provider.GenericBackendV2.run ""qiskit.providers.fake_provider.GenericBackendV2.run"") method. ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** [Provider](qiskit.providers.Provider ""qiskit.providers.Provider"") ### target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as [`BackendV2.version`](qiskit.providers.BackendV2#version ""qiskit.providers.BackendV2.version""), which is the version of the [`Backend`](qiskit.providers.Backend ""qiskit.providers.Backend"") abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** [AcquireChannel](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** ([*Iterable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[[ControlChannel](qiskit.pulse.channels.ControlChannel ""qiskit.pulse.channels.ControlChannel"")] **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** [DriveChannel](qiskit.pulse.channels.DriveChannel ""qiskit.pulse.channels.DriveChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** [MeasureChannel](qiskit.pulse.channels.MeasureChannel ""qiskit.pulse.channels.MeasureChannel"") **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the measurement mapping ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(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)"")*]*) – The qubit to get the [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") object for. This can be a single integer for 1 qubit or a list of qubits and a list of [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") objects will be returned in the same order **Returns** The [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – if the backend doesn’t support querying the qubit properties **Return type** [*QubitProperties*](qiskit.providers.QubitProperties ""qiskit.providers.backend.QubitProperties"") | [*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")\[[*QubitProperties*](qiskit.providers.QubitProperties ""qiskit.providers.backend.QubitProperties"")] ### run Run on the backend using a simulator. This method runs circuit jobs (an individual or a list of [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ) and pulse jobs (an individual or a list of [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") or [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"")) using [`BasicSimulator`](qiskit.providers.basic_provider.BasicSimulator ""qiskit.providers.basic_provider.BasicSimulator"") or Aer simulator and returns a [`Job`](qiskit.providers.Job ""qiskit.providers.Job"") object. If qiskit-aer is installed, jobs will be run using the `AerSimulator` with noise model of the backend. Otherwise, jobs will be run using the `BasicSimulator` simulator without noise. Noisy simulations of pulse jobs are not yet supported in [`GenericBackendV2`](#qiskit.providers.fake_provider.GenericBackendV2 ""qiskit.providers.fake_provider.GenericBackendV2""). **Parameters** * **run\_input** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *or*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – An individual or a list of [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""), [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock""), or [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object, then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** [Job](qiskit.providers.Job ""qiskit.providers.Job"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If a pulse job is supplied and qiskit\_aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the field passed in is not part of the options ",repo/docs/api/qiskit/1.0\qiskit.providers.fake_provider.GenericBackendV2.mdx "--- title: Job description: API reference for qiskit.providers.Job in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.Job --- # Job Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Base common type for all versioned Job abstract classes. Note this class should not be inherited from directly, it is intended to be used for type checking. When implementing a provider you should use the versioned abstract classes as the parent class and not this class directly. ## Attributes ### version ",repo/docs/api/qiskit/1.0\qiskit.providers.Job.mdx "--- title: JobStatus description: API reference for qiskit.providers.JobStatus in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.JobStatus --- # JobStatus Bases: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum ""(in Python v3.12)"") Class for job status enumerated type. ## Attributes ### INITIALIZING ### QUEUED ### VALIDATING ### RUNNING ### CANCELLED ### DONE ### ERROR ",repo/docs/api/qiskit/1.0\qiskit.providers.JobStatus.mdx "--- title: JobV1 description: API reference for qiskit.providers.JobV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.JobV1 --- # JobV1 Bases: [`Job`](qiskit.providers.Job ""qiskit.providers.job.Job""), [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Class to handle jobs This first version of the Backend abstract class is written to be mostly backwards compatible with the legacy providers interface. This was done to ease the transition for users and provider maintainers to the new versioned providers. Expect, future versions of this abstract class to change the data model and interface. Initializes the asynchronous job. **Parameters** * **backend** (*Optional\[*[*Backend*](qiskit.providers.Backend ""qiskit.providers.Backend"")*]*) – the backend used to run the job. * **job\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – a unique id in the context of the backend used to run the job. * **kwargs** – Any key value metadata to associate with this job. ## Attributes ### version ## Methods ### backend Return the backend where this job was executed. **Return type** [*Backend*](qiskit.providers.Backend ""qiskit.providers.backend.Backend"") ### cancel Attempt to cancel the job. ### cancelled Return whether the job has been cancelled. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### done Return whether the job has successfully run. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### in\_final\_state Return whether the job is in a final job state such as `DONE` or `ERROR`. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### job\_id Return a unique id identifying the job. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### result Return the results of the job. **Return type** [Result](qiskit.result.Result ""qiskit.result.Result"") ### running Return whether the job is actively running. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### status Return the status of the job, among the values of `JobStatus`. **Return type** [*JobStatus*](qiskit.providers.JobStatus ""qiskit.providers.jobstatus.JobStatus"") ### submit Submit the job to the backend for execution. ### wait\_for\_final\_state Poll the job status until it progresses to a final state such as `DONE` or `ERROR`. **Parameters** * **timeout** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – Seconds to wait for the job. If `None`, wait indefinitely. * **wait** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Seconds between queries. * **callback** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"") *| None*) – Callback function invoked after each query. The following positional arguments are provided to the callback function: * job\_id: Job ID * job\_status: Status of the job from the last query * job: This BaseJob instance Note: different subclass might provide different arguments to the callback function. **Raises** [**JobTimeoutError**](providers#qiskit.providers.JobTimeoutError ""qiskit.providers.JobTimeoutError"") – If the job does not reach a final state before the specified timeout. ",repo/docs/api/qiskit/1.0\qiskit.providers.JobV1.mdx "--- title: BackendConfiguration description: API reference for qiskit.providers.models.BackendConfiguration in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.BackendConfiguration --- # BackendConfiguration Bases: [`QasmBackendConfiguration`](qiskit.providers.models.QasmBackendConfiguration ""qiskit.providers.models.backendconfiguration.QasmBackendConfiguration"") Backwards compat shim representing an abstract backend configuration. Initialize a QasmBackendConfiguration Object **Parameters** * **backend\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The backend name * **backend\_version** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The backend version in the form X.Y.Z * **n\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of qubits for the backend * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The list of strings for the basis gates of the backends * **gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The list of GateConfig objects for the basis gates of the backend * **local** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend is local or False if remote * **simulator** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend is a simulator * **conditional** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend supports conditional operations * **open\_pulse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend supports OpenPulse * **memory** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend supports memory * **max\_shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of shots allowed on the backend * **coupling\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The coupling map for the device * **supported\_instructions** (*List\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – Instructions supported by the backend. * **dynamic\_reprate\_enabled** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – whether delay between programs can be set dynamically (ie via `rep_delay`). Defaults to False. * **rep\_delay\_range** (*List\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – 2d list defining supported range of repetition delays for backend in μs. First entry is lower end of the range, second entry is higher end of the range. Optional, but will be specified when `dynamic_reprate_enabled=True`. * **default\_rep\_delay** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Value of `rep_delay` if not specified by user and `dynamic_reprate_enabled=True`. * **max\_experiments** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of experiments per job * **sample\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Sample name for the backend * **n\_registers** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of register slots available for feedback (if conditional is True) * **register\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – An array of dimension n\_qubits X n\_registers that specifies whether a qubit can store a measurement in a certain register slot. * **configurable** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend is configurable, if the backend is a simulator * **credits\_required** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if backend requires credits to run a job. * **online\_date** ([*datetime.datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime ""(in Python v3.12)"")) – The date that the device went online * **display\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Alternate name field for the backend * **description** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A description for the backend * **tags** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of string tags to describe the backend * **dt** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Qubit drive channel timestep in nanoseconds. * **dtm** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Measurement drive channel timestep in nanoseconds. * **processor\_type** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Processor type for this backend. A dictionary of the form `{""family"": , ""revision"": , segment: }` such as `{""family"": ""Canary"", ""revision"": ""1.0"", segment: ""A""}`. * family: Processor family of this backend. * revision: Revision version of this processor. * segment: Segment this processor belongs to within a larger chip. * **parametric\_pulses** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of pulse shapes which are supported on the backend. For example: `['gaussian', 'constant']` * **\*\*kwargs** – optional fields ## Attributes ### num\_qubits Returns the number of qubits. In future, n\_qubits should be replaced in favor of num\_qubits for consistent use throughout Qiskit. Until this is properly refactored, this property serves as intermediate solution. ## Methods ### from\_dict Create a new GateConfig object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the GateConfig to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.BackendConfiguration.to_dict ""qiskit.providers.models.BackendConfiguration.to_dict""). **Returns** The GateConfig from the input dictionary. **Return type** [GateConfig](qiskit.providers.models.GateConfig ""qiskit.providers.models.GateConfig"") ### to\_dict Return a dictionary format representation of the GateConfig. **Returns** The dictionary form of the GateConfig. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.providers.models.BackendConfiguration.mdx "--- title: BackendProperties description: API reference for qiskit.providers.models.BackendProperties in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.BackendProperties --- # BackendProperties Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Class representing backend properties This holds backend properties measured by the provider. All properties which are provided optionally. These properties may describe qubits, gates, or other general properties of the backend. Initialize a BackendProperties instance. **Parameters** * **backend\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Backend name. * **backend\_version** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Backend version in the form X.Y.Z. * **last\_update\_date** ([*datetime.datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime ""(in Python v3.12)"") *or*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Last date/time that a property was updated. If specified as a `str`, it must be in ISO format. * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – System qubit parameters as a list of lists of [`Nduv`](qiskit.providers.models.Nduv ""qiskit.providers.models.Nduv"") objects * **gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – System gate parameters as a list of [`GateProperties`](qiskit.providers.models.GateProperties ""qiskit.providers.models.GateProperties"") objects * **general** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – General parameters as a list of [`Nduv`](qiskit.providers.models.Nduv ""qiskit.providers.models.Nduv"") objects * **kwargs** – optional additional fields ## Methods ### faulty\_gates Return a list of faulty gates. ### faulty\_qubits Return a list of faulty qubits. ### frequency Return the frequency of the given qubit. **Parameters** **qubit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Qubit for which to return frequency of. **Returns** Frequency of the given qubit. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### from\_dict Create a new BackendProperties object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the BackendProperties to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.BackendProperties.to_dict ""qiskit.providers.models.BackendProperties.to_dict""). **Returns** The BackendProperties from the input dictionary. **Return type** [BackendProperties](#qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"") ### gate\_error Return gate error estimates from backend properties. **Parameters** * **gate** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The gate for which to get the error. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(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)"")*]*) – The specific qubits for the gate. **Returns** Gate error of the given gate and qubit(s). **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### gate\_length Return the duration of the gate in units of seconds. **Parameters** * **gate** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The gate for which to get the duration. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(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)"")*]*) – The specific qubits for the gate. **Returns** Gate length of the given gate and qubit(s). **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### gate\_property Return the property of the given gate. **Parameters** * **gate** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of the gate. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(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*) – The qubit to find the property for. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Optionally used to specify which gate property to return. **Returns** Gate property as a tuple of the value and the time it was measured. **Raises** [**BackendPropertyError**](providers#qiskit.providers.BackendPropertyError ""qiskit.providers.BackendPropertyError"") – If the property is not found or name is specified but qubit is not. **Return type** [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict ""(in Python v3.12)"")\[[*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")\[[int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)""), …], [*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)""), [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime ""(in Python v3.12)"")]]] | [*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)""), [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime ""(in Python v3.12)"")]] | [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime ""(in Python v3.12)"")] ### is\_gate\_operational Return the operational status of the given gate. **Parameters** * **gate** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of the gate. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(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*) – The qubit to find the operational status for. **Returns** Operational status of the given gate. True if the gate is operational, False otherwise. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_qubit\_operational Return the operational status of the given qubit. **Parameters** **qubit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Qubit for which to return operational status of. **Returns** Operational status of the given qubit. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### qubit\_property Return the property of the given qubit. **Parameters** * **qubit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The property to look for. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Optionally used to specify within the hierarchy which property to return. **Returns** Qubit property as a tuple of the value and the time it was measured. **Raises** [**BackendPropertyError**](providers#qiskit.providers.BackendPropertyError ""qiskit.providers.BackendPropertyError"") – If the property is not found. **Return type** [*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)""), [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime ""(in Python v3.12)"")]] | [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime ""(in Python v3.12)"")] ### readout\_error Return the readout error of the given qubit. **Parameters** **qubit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Qubit for which to return the readout error of. **Returns** Readout error of the given qubit. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### readout\_length Return the readout length \[sec] of the given qubit. **Parameters** **qubit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Qubit for which to return the readout length of. **Returns** Readout length of the given qubit. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### t1 Return the T1 time of the given qubit. **Parameters** **qubit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Qubit for which to return the T1 time of. **Returns** T1 time of the given qubit. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### t2 Return the T2 time of the given qubit. **Parameters** **qubit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Qubit for which to return the T2 time of. **Returns** T2 time of the given qubit. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### to\_dict Return a dictionary format representation of the BackendProperties. **Returns** The dictionary form of the BackendProperties. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.providers.models.BackendProperties.mdx "--- title: BackendStatus description: API reference for qiskit.providers.models.BackendStatus in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.BackendStatus --- # BackendStatus Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Class representing Backend Status. Initialize a BackendStatus object **Parameters** * **backend\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The backend’s name * **backend\_version** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The backend’s version of the form X.Y.Z * **operational** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend is operational * **pending\_jobs** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of pending jobs on the backend * **status\_msg** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The status msg for the backend **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If the backend version is in an invalid format ## Methods ### from\_dict Create a new BackendStatus object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the BaseBakend to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.BackendStatus.to_dict ""qiskit.providers.models.BackendStatus.to_dict""). **Returns** The BackendStatus from the input dictionary. **Return type** [BackendStatus](#qiskit.providers.models.BackendStatus ""qiskit.providers.models.BackendStatus"") ### to\_dict Return a dictionary format representation of the BackendStatus. **Returns** The dictionary form of the QobjHeader. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.providers.models.BackendStatus.mdx "--- title: Command description: API reference for qiskit.providers.models.Command in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.Command --- # Command Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Class representing a Command. ### name Pulse command name. Initialize a Command object **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the command * **qubits** – The qubits for the command * **sequence** ([*PulseQobjInstruction*](qiskit.qobj.PulseQobjInstruction ""qiskit.qobj.PulseQobjInstruction"")) – The sequence for the Command * **kwargs** – Optional additional fields ## Methods ### from\_dict Create a new Command object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the `Command` to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.Command.to_dict ""qiskit.providers.models.Command.to_dict""). **Returns** The `Command` from the input dictionary. **Return type** [Command](#qiskit.providers.models.Command ""qiskit.providers.models.Command"") ### to\_dict Return a dictionary format representation of the Command. **Returns** The dictionary form of the Command. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.providers.models.Command.mdx "--- title: GateConfig description: API reference for qiskit.providers.models.GateConfig in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.GateConfig --- # GateConfig Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Class representing a Gate Configuration ### name the gate name as it will be referred to in OpenQASM. ### parameters variable names for the gate parameters (if any). ### qasm\_def definition of this gate in terms of OpenQASM 2 primitives U and CX. Initialize a GateConfig object **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – the gate name as it will be referred to in OpenQASM. * **parameters** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – variable names for the gate parameters (if any) as a list of strings. * **qasm\_def** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – definition of this gate in terms of OpenQASM 2 primitives U and CX. * **coupling\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – An optional coupling map for the gate. In the form of a list of lists of integers representing the qubit groupings which are coupled by this gate. * **latency\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – An optional map of latency for the gate. In the the form of a list of lists of integers of either 0 or 1 representing an array of dimension len(coupling\_map) X n\_registers that specifies the register latency (1: fast, 0: slow) conditional operations on the gate * **conditional** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Optionally specify whether this gate supports conditional operations (true/false). If this is not specified, then the gate inherits the conditional property of the backend. * **description** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Description of the gate operation ## Methods ### from\_dict Create a new GateConfig object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the GateConfig to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.GateConfig.to_dict ""qiskit.providers.models.GateConfig.to_dict""). **Returns** The GateConfig from the input dictionary. **Return type** [GateConfig](#qiskit.providers.models.GateConfig ""qiskit.providers.models.GateConfig"") ### to\_dict Return a dictionary format representation of the GateConfig. **Returns** The dictionary form of the GateConfig. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.providers.models.GateConfig.mdx "--- title: GateProperties description: API reference for qiskit.providers.models.GateProperties in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.GateProperties --- # GateProperties Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Class representing a gate’s properties ### qubits qubits. ### gate gate. ### parameters parameters. Initialize a new [`GateProperties`](#qiskit.providers.models.GateProperties ""qiskit.providers.models.GateProperties"") object **Parameters** * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of integers representing qubits * **gate** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The gates name * **parameters** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of [`Nduv`](qiskit.providers.models.Nduv ""qiskit.providers.models.Nduv"") objects for the name-date-unit-value for the gate * **kwargs** – Optional additional fields ## Methods ### from\_dict Create a new Gate object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the Gate to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.GateProperties.to_dict ""qiskit.providers.models.GateProperties.to_dict""). **Returns** The Nduv from the input dictionary. **Return type** [GateProperties](#qiskit.providers.models.GateProperties ""qiskit.providers.models.GateProperties"") ### to\_dict Return a dictionary format representation of the BackendStatus. **Returns** The dictionary form of the Gate. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.providers.models.GateProperties.mdx "--- title: JobStatus description: API reference for qiskit.providers.models.JobStatus in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.JobStatus --- # JobStatus Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Model for JobStatus. ### job\_id backend job\_id. **Type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### status status of the job. **Type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### status\_msg status message. **Type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ## Methods ### from\_dict Create a new JobStatus object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the JobStatus to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.JobStatus.to_dict ""qiskit.providers.models.JobStatus.to_dict""). **Returns** The `JobStatus` from the input dictionary. **Return type** [JobStatus](#qiskit.providers.models.JobStatus ""qiskit.providers.models.JobStatus"") ### to\_dict Return a dictionary format representation of the JobStatus. **Returns** The dictionary form of the JobStatus. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.providers.models.JobStatus.mdx "--- title: Nduv description: API reference for qiskit.providers.models.Nduv in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.Nduv --- # Nduv Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Class representing name-date-unit-value ### date date. ### name name. ### unit unit. ### value value. Initialize a new name-date-unit-value object **Parameters** * **date** ([*datetime.datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime ""(in Python v3.12)"")) – Date field * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name field * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Nduv unit * **value** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The value of the Nduv ## Methods ### from\_dict Create a new Nduv object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the Nduv to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.Nduv.to_dict ""qiskit.providers.models.Nduv.to_dict""). **Returns** The Nduv from the input dictionary. **Return type** [Nduv](#qiskit.providers.models.Nduv ""qiskit.providers.models.Nduv"") ### to\_dict Return a dictionary format representation of the object. **Returns** The dictionary form of the Nduv. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.providers.models.Nduv.mdx "--- title: PulseBackendConfiguration description: API reference for qiskit.providers.models.PulseBackendConfiguration in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.PulseBackendConfiguration --- # PulseBackendConfiguration Bases: [`QasmBackendConfiguration`](qiskit.providers.models.QasmBackendConfiguration ""qiskit.providers.models.backendconfiguration.QasmBackendConfiguration"") Static configuration state for an OpenPulse enabled backend. This contains information about the set up of the device which can be useful for building Pulse programs. Initialize a backend configuration that contains all the extra configuration that is made available for OpenPulse backends. **Parameters** * **backend\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – backend name. * **backend\_version** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – backend version in the form X.Y.Z. * **n\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubits. * **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)"")*]*) – list of basis gates names on the backend. * **gates** ([*GateConfig*](qiskit.providers.models.GateConfig ""qiskit.providers.models.backendconfiguration.GateConfig"")) – list of basis gates on the backend. * **local** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – backend is local or remote. * **simulator** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – backend is a simulator. * **conditional** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – backend supports conditional operations. * **open\_pulse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – backend supports open pulse. * **memory** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – backend supports memory. * **max\_shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – maximum number of shots supported. * **coupling\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The coupling map for the device * **n\_uchannels** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of u-channels. * **u\_channel\_lo** ([*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)"")*\[*[*UchannelLO*](qiskit.providers.models.UchannelLO ""qiskit.providers.models.backendconfiguration.UchannelLO"")*]]*) – U-channel relationship on device los. * **meas\_levels** ([*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)"")*]*) – Supported measurement levels. * **qubit\_lo\_range** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]]*) – Qubit lo ranges for each qubit with form (min, max) in GHz. * **meas\_lo\_range** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]]*) – Measurement lo ranges for each qubit with form (min, max) in GHz. * **dt** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Qubit drive channel timestep in nanoseconds. * **dtm** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Measurement drive channel timestep in nanoseconds. * **rep\_times** ([*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)"")*]*) – Supported repetition times (program execution time) for backend in μs. * **meas\_kernels** ([*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)"")*]*) – Supported measurement kernels. * **discriminators** ([*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)"")*]*) – Supported discriminators. * **hamiltonian** ([*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)"")*,* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")*]*) – An optional dictionary with fields characterizing the system hamiltonian. * **channel\_bandwidth** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – Bandwidth of all channels (qubit, measurement, and U) * **acquisition\_latency** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – Array of dimension n\_qubits x n\_registers. Latency (in units of dt) to write a measurement result from qubit n into register slot m. * **conditional\_latency** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – Array of dimension n\_channels \[d->u->m] x n\_registers. Latency (in units of dt) to do a conditional operation on channel n from register slot m * **meas\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – Grouping of measurement which are multiplexed * **max\_experiments** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of experiments per job * **sample\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Sample name for the backend * **n\_registers** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of register slots available for feedback (if conditional is True) * **register\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – An array of dimension n\_qubits X n\_registers that specifies whether a qubit can store a measurement in a certain register slot. * **configurable** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend is configurable, if the backend is a simulator * **credits\_required** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if backend requires credits to run a job. * **online\_date** ([*datetime.datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime ""(in Python v3.12)"")) – The date that the device went online * **display\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Alternate name field for the backend * **description** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A description for the backend * **tags** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of string tags to describe the backend * **channels** ([*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)"")*,* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")*]*) – An optional dictionary containing information of each channel – their purpose, type, and qubits operated on. * **\*\*kwargs** – Optional fields. ## Attributes ### control\_channels Return the control channels ### num\_qubits Returns the number of qubits. In future, n\_qubits should be replaced in favor of num\_qubits for consistent use throughout Qiskit. Until this is properly refactored, this property serves as intermediate solution. ### sample\_rate Sample rate of the signal channels in Hz (1/dt). ## Methods ### acquire Return the acquisition channel for the given qubit. **Raises** [**BackendConfigurationError**](providers#qiskit.providers.BackendConfigurationError ""qiskit.providers.BackendConfigurationError"") – If the qubit is not a part of the system. **Returns** Qubit measurement acquisition line. **Return type** [*AcquireChannel*](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"") ### control Return the secondary drive channel for the given qubit – typically utilized for controlling multiqubit interactions. This channel is derived from other channels. **Parameters** **qubits** ([*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*) – Tuple or list of qubits of the form (control\_qubit, target\_qubit). **Raises** [**BackendConfigurationError**](providers#qiskit.providers.BackendConfigurationError ""qiskit.providers.BackendConfigurationError"") – If the `qubits` is not a part of the system or if the backend does not provide channels information in its configuration. **Returns** List of control channels. **Return type** [*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")\[[*ControlChannel*](qiskit.pulse.channels.ControlChannel ""qiskit.pulse.channels.ControlChannel"")] ### describe Return a basic description of the channel dependency. Derived channels are given weights which describe how their frames are linked to other frames. For instance, the backend could be configured with this setting: ```python u_channel_lo = [ [UchannelLO(q=0, scale=1. + 0.j)], [UchannelLO(q=0, scale=-1. + 0.j), UchannelLO(q=1, scale=1. + 0.j)] ] ``` Then, this method can be used as follows: ```python backend.configuration().describe(ControlChannel(1)) >>> {DriveChannel(0): -1, DriveChannel(1): 1} ``` **Parameters** **channel** ([*ControlChannel*](qiskit.pulse.channels.ControlChannel ""qiskit.pulse.channels.ControlChannel"")) – The derived channel to describe. **Raises** [**BackendConfigurationError**](providers#qiskit.providers.BackendConfigurationError ""qiskit.providers.BackendConfigurationError"") – If channel is not a ControlChannel. **Returns** Control channel derivations. **Return type** [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict ""(in Python v3.12)"")\[[*DriveChannel*](qiskit.pulse.channels.DriveChannel ""qiskit.pulse.channels.DriveChannel""), [complex](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")] ### drive Return the drive channel for the given qubit. **Raises** [**BackendConfigurationError**](providers#qiskit.providers.BackendConfigurationError ""qiskit.providers.BackendConfigurationError"") – If the qubit is not a part of the system. **Returns** Qubit drive channel. **Return type** [*DriveChannel*](qiskit.pulse.channels.DriveChannel ""qiskit.pulse.channels.DriveChannel"") ### from\_dict Create a new GateConfig object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the GateConfig to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.PulseBackendConfiguration.to_dict ""qiskit.providers.models.PulseBackendConfiguration.to_dict""). **Returns** The GateConfig from the input dictionary. **Return type** [GateConfig](qiskit.providers.models.GateConfig ""qiskit.providers.models.GateConfig"") ### get\_channel\_qubits Return a list of indices for qubits which are operated on directly by the given `channel`. **Raises** [**BackendConfigurationError**](providers#qiskit.providers.BackendConfigurationError ""qiskit.providers.BackendConfigurationError"") – If `channel` is not a found or if the backend does not provide channels information in its configuration. **Returns** List of qubits operated on my the given `channel`. **Return type** [*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)"")] ### get\_qubit\_channels Return a list of channels which operate on the given `qubit`. **Raises** [**BackendConfigurationError**](providers#qiskit.providers.BackendConfigurationError ""qiskit.providers.BackendConfigurationError"") – If `qubit` is not a found or if the backend does not provide channels information in its configuration. **Returns** List of `Channel`s operated on my the given `qubit`. **Return type** [*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")\[[*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")] ### measure Return the measure stimulus channel for the given qubit. **Raises** [**BackendConfigurationError**](providers#qiskit.providers.BackendConfigurationError ""qiskit.providers.BackendConfigurationError"") – If the qubit is not a part of the system. **Returns** Qubit measurement stimulus line. **Return type** [*MeasureChannel*](qiskit.pulse.channels.MeasureChannel ""qiskit.pulse.channels.MeasureChannel"") ### to\_dict Return a dictionary format representation of the GateConfig. **Returns** The dictionary form of the GateConfig. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.providers.models.PulseBackendConfiguration.mdx "--- title: PulseDefaults description: API reference for qiskit.providers.models.PulseDefaults in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.PulseDefaults --- # PulseDefaults Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Description of default settings for Pulse systems. These are instructions or settings that may be good starting points for the Pulse user. The user may modify these defaults for custom scheduling. Validate and reformat transport layer inputs to initialize. :param qubit\_freq\_est: Estimated qubit frequencies in GHz. :param meas\_freq\_est: Estimated measurement cavity frequencies in GHz. :param buffer: Default buffer time (in units of dt) between pulses. :param pulse\_library: Pulse name and sample definitions. :param cmd\_def: Operation name and definition in terms of Commands. :param meas\_kernel: The measurement kernels :param discriminator: The discriminators :param \*\*kwargs: Other attributes for the super class. ## Attributes ### qubit\_freq\_est Qubit frequencies in Hertz. ### meas\_freq\_est Measurement frequencies in Hertz. ## Methods ### from\_dict Create a new PulseDefaults object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the PulseDefaults to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.PulseDefaults.to_dict ""qiskit.providers.models.PulseDefaults.to_dict""). **Returns** The PulseDefaults from the input dictionary. **Return type** [PulseDefaults](#qiskit.providers.models.PulseDefaults ""qiskit.providers.models.PulseDefaults"") ### to\_dict Return a dictionary format representation of the PulseDefaults. :returns: The dictionary form of the PulseDefaults. :rtype: dict ",repo/docs/api/qiskit/1.0\qiskit.providers.models.PulseDefaults.mdx "--- title: QasmBackendConfiguration description: API reference for qiskit.providers.models.QasmBackendConfiguration in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.QasmBackendConfiguration --- # QasmBackendConfiguration Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Class representing an OpenQASM 2.0 Backend Configuration. ### backend\_name backend name. ### backend\_version backend version in the form X.Y.Z. ### n\_qubits number of qubits. ### basis\_gates list of basis gates names on the backend. ### gates list of basis gates on the backend. ### local backend is local or remote. ### simulator backend is a simulator. ### conditional backend supports conditional operations. ### open\_pulse backend supports open pulse. ### memory backend supports memory. ### max\_shots maximum number of shots supported. Initialize a QasmBackendConfiguration Object **Parameters** * **backend\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The backend name * **backend\_version** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The backend version in the form X.Y.Z * **n\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of qubits for the backend * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The list of strings for the basis gates of the backends * **gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The list of GateConfig objects for the basis gates of the backend * **local** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend is local or False if remote * **simulator** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend is a simulator * **conditional** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend supports conditional operations * **open\_pulse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend supports OpenPulse * **memory** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend supports memory * **max\_shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of shots allowed on the backend * **coupling\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The coupling map for the device * **supported\_instructions** (*List\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – Instructions supported by the backend. * **dynamic\_reprate\_enabled** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – whether delay between programs can be set dynamically (ie via `rep_delay`). Defaults to False. * **rep\_delay\_range** (*List\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – 2d list defining supported range of repetition delays for backend in μs. First entry is lower end of the range, second entry is higher end of the range. Optional, but will be specified when `dynamic_reprate_enabled=True`. * **default\_rep\_delay** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Value of `rep_delay` if not specified by user and `dynamic_reprate_enabled=True`. * **max\_experiments** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of experiments per job * **sample\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Sample name for the backend * **n\_registers** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of register slots available for feedback (if conditional is True) * **register\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – An array of dimension n\_qubits X n\_registers that specifies whether a qubit can store a measurement in a certain register slot. * **configurable** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if the backend is configurable, if the backend is a simulator * **credits\_required** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – True if backend requires credits to run a job. * **online\_date** ([*datetime.datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime ""(in Python v3.12)"")) – The date that the device went online * **display\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Alternate name field for the backend * **description** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A description for the backend * **tags** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of string tags to describe the backend * **dt** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Qubit drive channel timestep in nanoseconds. * **dtm** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Measurement drive channel timestep in nanoseconds. * **processor\_type** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Processor type for this backend. A dictionary of the form `{""family"": , ""revision"": , segment: }` such as `{""family"": ""Canary"", ""revision"": ""1.0"", segment: ""A""}`. * family: Processor family of this backend. * revision: Revision version of this processor. * segment: Segment this processor belongs to within a larger chip. * **parametric\_pulses** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of pulse shapes which are supported on the backend. For example: `['gaussian', 'constant']` * **\*\*kwargs** – optional fields ## Attributes ### num\_qubits Returns the number of qubits. In future, n\_qubits should be replaced in favor of num\_qubits for consistent use throughout Qiskit. Until this is properly refactored, this property serves as intermediate solution. ## Methods ### from\_dict Create a new GateConfig object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the GateConfig to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.QasmBackendConfiguration.to_dict ""qiskit.providers.models.QasmBackendConfiguration.to_dict""). **Returns** The GateConfig from the input dictionary. **Return type** [GateConfig](qiskit.providers.models.GateConfig ""qiskit.providers.models.GateConfig"") ### to\_dict Return a dictionary format representation of the GateConfig. **Returns** The dictionary form of the GateConfig. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.providers.models.QasmBackendConfiguration.mdx "--- title: UchannelLO description: API reference for qiskit.providers.models.UchannelLO in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.models.UchannelLO --- # UchannelLO Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Class representing a U Channel LO ### q Qubit that scale corresponds too. ### scale Scale factor for qubit frequency. Initialize a UchannelLOSchema object **Parameters** * **q** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Qubit that scale corresponds too. Must be >= 0. * **scale** ([*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")) – Scale factor for qubit frequency. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If q is \< 0 ## Methods ### from\_dict Create a new UchannelLO object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the UChannelLO to create. It will be in the same format as output by [`to_dict()`](#qiskit.providers.models.UchannelLO.to_dict ""qiskit.providers.models.UchannelLO.to_dict""). **Returns** The UchannelLO from the input dictionary. **Return type** [UchannelLO](#qiskit.providers.models.UchannelLO ""qiskit.providers.models.UchannelLO"") ### to\_dict Return a dictionary format representation of the UChannelLO. **Returns** The dictionary form of the UChannelLO. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.providers.models.UchannelLO.mdx "--- title: Options description: API reference for qiskit.providers.Options in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.Options --- # Options Bases: [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping ""(in Python v3.12)"") Base options object This class is what all backend options are based on. The properties of the class are intended to be all dynamically adjustable so that a user can reconfigure the backend on demand. If a property is immutable to the user (eg something like number of qubits) that should be a configuration of the backend class itself instead of the options. Instances of this class behave like dictionaries. Accessing an option with a default value can be done with the get() method: ```python >>> options = Options(opt1=1, opt2=2) >>> options.get(""opt1"") 1 >>> options.get(""opt3"", default=""hello"") 'hello' ``` Key-value pairs for all options can be retrieved using the items() method: ```python >>> list(options.items()) [('opt1', 1), ('opt2', 2)] ``` Options can be updated by name: ```python >>> options[""opt1""] = 3 >>> options.get(""opt1"") 3 ``` Runtime validators can be registered. See set\_validator. Updates through update\_options and indexing (\_\_setitem\_\_) validate the new value before performing the update and raise ValueError if the new value is invalid. ```python >>> options.set_validator(""opt1"", (1, 5)) >>> options[""opt1""] = 4 >>> options[""opt1""] 4 >>> options[""opt1""] = 10 Traceback (most recent call last): ... ValueError: ... ``` ## Attributes ### validator ## Methods ### get ### items ### keys ### set\_validator Set an optional validator for a field in the options Setting a validator enables changes to an options values to be validated for correctness when [`update_options()`](#qiskit.providers.Options.update_options ""qiskit.providers.Options.update_options"") is called. For example if you have a numeric field like `shots` you can specify a bounds tuple that set an upper and lower bound on the value such as: ```python options.set_validator(""shots"", (1, 4096)) ``` In this case whenever the `""shots""` option is updated by the user it will enforce that the value is >=1 and \<=4096. A `ValueError` will be raised if it’s outside those bounds. If a validator is already present for the specified field it will be silently overridden. **Parameters** * **field** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The field name to set the validator on * **validator\_value** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") *or*[*type*](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"")) – The value to use for the validator depending on the type indicates on how the value for a field is enforced. If a tuple is passed in it must have a length of two and will enforce the min and max value (inclusive) for an integer or float value option. If it’s a list it will list the valid values for a field. If it’s a `type` the validator will just enforce the value is of a certain type. **Raises** * [**KeyError**](https://docs.python.org/3/library/exceptions.html#KeyError ""(in Python v3.12)"") – If field is not present in the options object * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the `validator_value` has an invalid value for a given type * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – If `validator_value` is not a valid type ### update\_options Update options with kwargs ### values ",repo/docs/api/qiskit/1.0\qiskit.providers.Options.mdx "--- title: Provider description: API reference for qiskit.providers.Provider in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.Provider --- # Provider Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Base common type for all versioned Provider abstract classes. Note this class should not be inherited from directly, it is intended to be used for type checking. When implementing a provider you should use the versioned abstract classes as the parent class and not this class directly. ## Attributes ### version ",repo/docs/api/qiskit/1.0\qiskit.providers.Provider.mdx "--- title: ProviderV1 description: API reference for qiskit.providers.ProviderV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.ProviderV1 --- # ProviderV1 Bases: [`Provider`](qiskit.providers.Provider ""qiskit.providers.provider.Provider""), [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Base class for a Backend Provider. ## Attributes ### version ## Methods ### backends Return a list of backends matching the specified filtering. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – name of the backend. * **\*\*kwargs** – dict used for filtering. **Returns** **a list of Backends that match the filtering** criteria. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[Backend](qiskit.providers.Backend ""qiskit.providers.Backend"")] ### get\_backend Return a single backend matching the specified filtering. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – name of the backend. * **\*\*kwargs** – dict used for filtering. **Returns** a backend matching the filtering. **Return type** [Backend](qiskit.providers.Backend ""qiskit.providers.Backend"") **Raises** [**QiskitBackendNotFoundError**](providers#qiskit.providers.QiskitBackendNotFoundError ""qiskit.providers.QiskitBackendNotFoundError"") – if no backend could be found or more than one backend matches the filtering criteria. ",repo/docs/api/qiskit/1.0\qiskit.providers.ProviderV1.mdx "--- title: QubitProperties description: API reference for qiskit.providers.QubitProperties in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.providers.QubitProperties --- # QubitProperties Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A representation of the properties of a qubit on a backend. This class provides the optional properties that a backend can provide for a qubit. These represent the set of qubit properties that Qiskit can currently work with if present. However if your backend provides additional properties of qubits you should subclass this to add additional custom attributes for those custom/additional properties provided by the backend. Create a new [`QubitProperties`](#qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") object. **Parameters** * **t1** – The T1 time for a qubit in seconds * **t2** – The T2 time for a qubit in seconds * **frequency** – The frequency of a qubit in Hz ## Attributes ### t1 ### t2 ### frequency ",repo/docs/api/qiskit/1.0\qiskit.providers.QubitProperties.mdx "--- title: AcquireChannel description: API reference for qiskit.pulse.channels.AcquireChannel in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.channels.AcquireChannel --- # AcquireChannel Bases: [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") Acquire channels are used to collect data. Channel class. **Parameters** **index** – Index of channel. ## Attributes ### index Return the index of this channel. The index is a label for a control signal line typically mapped trivially to a qubit index. For instance, `DriveChannel(0)` labels the signal line driving the qubit labeled with index 0. ### name Return the shorthand alias for this channel, which is based on its type and index. ### parameters Parameters which determine the channel index. ### prefix A shorthand string prefix for characterizing the channel type. ## Methods ### is\_parameterized Return True iff the channel is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.channels.AcquireChannel.mdx "--- title: ControlChannel description: API reference for qiskit.pulse.channels.ControlChannel in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.channels.ControlChannel --- # ControlChannel Bases: `PulseChannel` Control channels provide supplementary control over the qubit to the drive channel. These are often associated with multi-qubit gate operations. They may not map trivially to a particular qubit index. Channel class. **Parameters** **index** – Index of channel. ## Attributes ### index Return the index of this channel. The index is a label for a control signal line typically mapped trivially to a qubit index. For instance, `DriveChannel(0)` labels the signal line driving the qubit labeled with index 0. ### name Return the shorthand alias for this channel, which is based on its type and index. ### parameters Parameters which determine the channel index. ### prefix A shorthand string prefix for characterizing the channel type. ## Methods ### is\_parameterized Return True iff the channel is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.channels.ControlChannel.mdx "--- title: DriveChannel description: API reference for qiskit.pulse.channels.DriveChannel in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.channels.DriveChannel --- # DriveChannel Bases: `PulseChannel` Drive channels transmit signals to qubits which enact gate operations. Channel class. **Parameters** **index** – Index of channel. ## Attributes ### index Return the index of this channel. The index is a label for a control signal line typically mapped trivially to a qubit index. For instance, `DriveChannel(0)` labels the signal line driving the qubit labeled with index 0. ### name Return the shorthand alias for this channel, which is based on its type and index. ### parameters Parameters which determine the channel index. ### prefix A shorthand string prefix for characterizing the channel type. ## Methods ### is\_parameterized Return True iff the channel is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.channels.DriveChannel.mdx "--- title: MeasureChannel description: API reference for qiskit.pulse.channels.MeasureChannel in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.channels.MeasureChannel --- # MeasureChannel Bases: `PulseChannel` Measure channels transmit measurement stimulus pulses for readout. Channel class. **Parameters** **index** – Index of channel. ## Attributes ### index Return the index of this channel. The index is a label for a control signal line typically mapped trivially to a qubit index. For instance, `DriveChannel(0)` labels the signal line driving the qubit labeled with index 0. ### name Return the shorthand alias for this channel, which is based on its type and index. ### parameters Parameters which determine the channel index. ### prefix A shorthand string prefix for characterizing the channel type. ## Methods ### is\_parameterized Return True iff the channel is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.channels.MeasureChannel.mdx "--- title: MemorySlot description: API reference for qiskit.pulse.channels.MemorySlot in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.channels.MemorySlot --- # MemorySlot Bases: `ClassicalIOChannel` Memory slot channels represent classical memory storage. Channel class. **Parameters** **index** – Index of channel. ## Attributes ### index Return the index of this channel. The index is a label for a control signal line typically mapped trivially to a qubit index. For instance, `DriveChannel(0)` labels the signal line driving the qubit labeled with index 0. ### name Return the shorthand alias for this channel, which is based on its type and index. ### parameters Parameters which determine the channel index. ### prefix A shorthand string prefix for characterizing the channel type. ## Methods ### is\_parameterized Return True iff the channel is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.channels.MemorySlot.mdx "--- title: RegisterSlot description: API reference for qiskit.pulse.channels.RegisterSlot in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.channels.RegisterSlot --- # RegisterSlot Bases: `ClassicalIOChannel` Classical resister slot channels represent classical registers (low-latency classical memory). Channel class. **Parameters** **index** – Index of channel. ## Attributes ### index Return the index of this channel. The index is a label for a control signal line typically mapped trivially to a qubit index. For instance, `DriveChannel(0)` labels the signal line driving the qubit labeled with index 0. ### name Return the shorthand alias for this channel, which is based on its type and index. ### parameters Parameters which determine the channel index. ### prefix A shorthand string prefix for characterizing the channel type. ## Methods ### is\_parameterized Return True iff the channel is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.channels.RegisterSlot.mdx "--- title: SnapshotChannel description: API reference for qiskit.pulse.channels.SnapshotChannel in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.channels.SnapshotChannel --- # SnapshotChannel Bases: `ClassicalIOChannel` Snapshot channels are used to specify instructions for simulators. Create new snapshot channel. ## Attributes ### index Return the index of this channel. The index is a label for a control signal line typically mapped trivially to a qubit index. For instance, `DriveChannel(0)` labels the signal line driving the qubit labeled with index 0. ### name Return the shorthand alias for this channel, which is based on its type and index. ### parameters Parameters which determine the channel index. ### prefix A shorthand string prefix for characterizing the channel type. ## Methods ### is\_parameterized Return True iff the channel is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.channels.SnapshotChannel.mdx "--- title: Acquire description: API reference for qiskit.pulse.instructions.Acquire in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.instructions.Acquire --- # Acquire Bases: [`Instruction`](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"") The Acquire instruction is used to trigger the ADC associated with a particular qubit; e.g. instantiated with AcquireChannel(0), the Acquire command will trigger data collection for the channel associated with qubit 0 readout. This instruction also provides acquisition metadata: > * the number of cycles during which to acquire (in terms of dt), > * the register slot to store classified, intermediary readout results, > * the memory slot to return classified results, > * the kernel to integrate raw data for each shot, and > * the discriminator to classify kerneled IQ points. Create a new Acquire instruction. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Length of time to acquire data in terms of dt. * **channel** ([*AcquireChannel*](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"")) – The channel that will acquire data. * **mem\_slot** ([*MemorySlot*](qiskit.pulse.channels.MemorySlot ""qiskit.pulse.channels.MemorySlot"") *| None*) – The classical memory slot in which to store the classified readout result. * **reg\_slot** ([*RegisterSlot*](qiskit.pulse.channels.RegisterSlot ""qiskit.pulse.channels.RegisterSlot"") *| None*) – The fast-access register slot in which to store the classified readout result for fast feedback. * **kernel** (*Kernel | None*) – A `Kernel` for integrating raw data. * **discriminator** (*Discriminator | None*) – A `Discriminator` for discriminating kerneled IQ data into 0/1 results. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the instruction for display purposes. ## Attributes ### acquire Acquire channel to acquire data. The `AcquireChannel` index maps trivially to qubit index. ### channel Return the [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") that this instruction is scheduled on. ### channels Returns the channels that this schedule uses. ### discriminator Return discrimination settings. ### duration Duration of this instruction. ### id Unique identifier for this instruction. ### instructions Iterable for getting instructions from Schedule tree. ### kernel Return kernel settings. ### mem\_slot The classical memory slot which will store the classified readout result. ### name Name of this instruction. ### operands Return instruction operands. ### parameters Parameters which determine the instruction behavior. ### reg\_slot The fast-access register slot which will store the classified readout result for fast-feedback computation. ### start\_time Relative begin time of this instruction. ### stop\_time Relative end time of this instruction. ## Methods ### append Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. **Parameters** * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to be appended * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` a this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### ch\_duration Return duration of the supplied channels in this Instruction. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return minimum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### insert Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted within `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule schedule * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to insert * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` inserted with this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### shift Return a new schedule shifted forward by time. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** The shifted schedule. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.instructions.Acquire.mdx "--- title: Delay description: API reference for qiskit.pulse.instructions.Delay in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.instructions.Delay --- # Delay Bases: [`Instruction`](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"") A blocking instruction with no other effect. The delay is used for aligning and scheduling other instructions. **Example** To schedule an instruction at time = 10, on a channel assigned to the variable `channel`, the following could be used: ```python sched = Schedule(name=""Delay instruction example"") sched += Delay(10, channel) sched += Gaussian(duration, amp, sigma, channel) ``` The `channel` will output no signal from time=0 up until time=10. Create a new delay instruction. No other instruction may be scheduled within a `Delay`. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Length of time of the delay in terms of dt. * **channel** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – The channel that will have the delay. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the delay for display purposes. ## Attributes ### channel Return the [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") that this instruction is scheduled on. ### channels Returns the channels that this schedule uses. ### duration Duration of this instruction. ### id Unique identifier for this instruction. ### instructions Iterable for getting instructions from Schedule tree. ### name Name of this instruction. ### operands Return instruction operands. ### parameters Parameters which determine the instruction behavior. ### start\_time Relative begin time of this instruction. ### stop\_time Relative end time of this instruction. ## Methods ### append Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. **Parameters** * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to be appended * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` a this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### ch\_duration Return duration of the supplied channels in this Instruction. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return minimum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### insert Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted within `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule schedule * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to insert * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` inserted with this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### shift Return a new schedule shifted forward by time. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** The shifted schedule. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.instructions.Delay.mdx "--- title: Play description: API reference for qiskit.pulse.instructions.Play in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.instructions.Play --- # Play Bases: [`Instruction`](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"") This instruction is responsible for applying a pulse on a channel. The pulse specifies the exact time dynamics of the output signal envelope for a limited time. The output is modulated by a phase and frequency which are controlled by separate instructions. The pulse duration must be fixed, and is implicitly given in terms of the cycle time, dt, of the backend. Create a new pulse instruction. **Parameters** * **pulse** (*Pulse*) – A pulse waveform description, such as [`Waveform`](qiskit.pulse.library.Waveform ""qiskit.pulse.library.Waveform""). * **channel** (*PulseChannel*) – The channel to which the pulse is applied. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the instruction for display purposes. Defaults to `pulse.name`. ## Attributes ### channel Return the [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") that this instruction is scheduled on. ### channels Returns the channels that this schedule uses. ### duration Duration of this instruction. ### id Unique identifier for this instruction. ### instructions Iterable for getting instructions from Schedule tree. ### name Name of this instruction. ### operands Return instruction operands. ### parameters Parameters which determine the instruction behavior. ### pulse A description of the samples that will be played. ### start\_time Relative begin time of this instruction. ### stop\_time Relative end time of this instruction. ## Methods ### append Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. **Parameters** * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to be appended * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` a this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### ch\_duration Return duration of the supplied channels in this Instruction. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return minimum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### insert Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted within `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule schedule * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to insert * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` inserted with this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### shift Return a new schedule shifted forward by time. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** The shifted schedule. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.instructions.Play.mdx "--- title: Reference description: API reference for qiskit.pulse.instructions.Reference in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.instructions.Reference --- # Reference Bases: [`Instruction`](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"") Pulse compiler directive that refers to a subroutine. If a pulse program uses the same subset of instructions multiple times, then using the [`Reference`](#qiskit.pulse.instructions.Reference ""qiskit.pulse.instructions.Reference"") class may significantly reduce the memory footprint of the program. This instruction only stores the set of strings to identify the subroutine. The actual pulse program can be stored in the `ScheduleBlock.references` of the [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") that this reference instruction belongs to. You can later assign schedules with the `ScheduleBlock.assign_references()` method. This allows you to build the main program without knowing the actual subroutine, that is supplied at a later time. Create new reference. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of subroutine. * **extra\_keys** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Optional. A set of string keys that may be necessary to refer to a particular subroutine. For example, when we use “sx” as a name to refer to the subroutine of an sx pulse, this name might be used among schedules for different qubits. In this example, you may specify “q0” in the extra keys to distinguish the sx schedule for qubit 0 from others. The user can use an arbitrary number of extra string keys to uniquely determine the subroutine. ## Attributes ### channels Returns the channels that this schedule uses. ### duration Duration of this instruction. ### id Unique identifier for this instruction. ### instructions Iterable for getting instructions from Schedule tree. ### key\_delimiter ### name Name of this instruction. ### operands Return instruction operands. ### parameters Parameters which determine the instruction behavior. ### ref\_keys Returns unique key of the subroutine. ### scope\_delimiter ### start\_time Relative begin time of this instruction. ### stop\_time Relative end time of this instruction. ## Methods ### append Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. **Parameters** * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to be appended * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` a this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### ch\_duration Return duration of the supplied channels in this Instruction. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return minimum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### insert Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted within `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule schedule * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to insert * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` inserted with this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### shift Return a new schedule shifted forward by time. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** The shifted schedule. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.instructions.Reference.mdx "--- title: RelativeBarrier description: API reference for qiskit.pulse.instructions.RelativeBarrier in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.instructions.RelativeBarrier --- # RelativeBarrier Bases: `Directive` Pulse `RelativeBarrier` directive. Create a relative barrier directive. The barrier directive blocks instructions within the same schedule as the barrier on channels contained within this barrier from moving through the barrier in time. **Parameters** * **channels** (*chans.Channel*) – The channel that the barrier applies to. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the directive for display purposes. ## Attributes ### channels Returns the channels that this schedule uses. ### duration Duration of this instruction. ### id Unique identifier for this instruction. ### instructions Iterable for getting instructions from Schedule tree. ### name Name of this instruction. ### operands Return instruction operands. ### parameters Parameters which determine the instruction behavior. ### start\_time Relative begin time of this instruction. ### stop\_time Relative end time of this instruction. ## Methods ### append Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. **Parameters** * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to be appended * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` a this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### ch\_duration Return duration of the supplied channels in this Instruction. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return minimum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### insert Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted within `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule schedule * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to insert * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` inserted with this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### shift Return a new schedule shifted forward by time. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** The shifted schedule. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.instructions.RelativeBarrier.mdx "--- title: SetFrequency description: API reference for qiskit.pulse.instructions.SetFrequency in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.instructions.SetFrequency --- # SetFrequency Bases: [`Instruction`](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"") Set the channel frequency. This instruction operates on `PulseChannel` s. A `PulseChannel` creates pulses of the form $$ Re[\exp(i 2\pi f jdt + \phi) d_j]. $$ Here, $f$ is the frequency of the channel. The instruction `SetFrequency` allows the user to set the value of $f$. All pulses that are played on a channel after SetFrequency has been called will have the corresponding frequency. The duration of SetFrequency is 0. Creates a new set channel frequency instruction. **Parameters** * **frequency** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"")) – New frequency of the channel in Hz. * **channel** (*PulseChannel*) – The channel this instruction operates on. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of this set channel frequency instruction. ## Attributes ### channel Return the [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") that this instruction is scheduled on. ### channels Returns the channels that this schedule uses. ### duration Duration of this instruction. ### frequency New frequency. ### id Unique identifier for this instruction. ### instructions Iterable for getting instructions from Schedule tree. ### name Name of this instruction. ### operands Return instruction operands. ### parameters Parameters which determine the instruction behavior. ### start\_time Relative begin time of this instruction. ### stop\_time Relative end time of this instruction. ## Methods ### append Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. **Parameters** * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to be appended * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` a this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### ch\_duration Return duration of the supplied channels in this Instruction. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return minimum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### insert Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted within `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule schedule * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to insert * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` inserted with this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### shift Return a new schedule shifted forward by time. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** The shifted schedule. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.instructions.SetFrequency.mdx "--- title: SetPhase description: API reference for qiskit.pulse.instructions.SetPhase in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.instructions.SetPhase --- # SetPhase Bases: [`Instruction`](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"") The set phase instruction sets the phase of the proceeding pulses on that channel to `phase` radians. In particular, a PulseChannel creates pulses of the form $$ Re[\exp(i 2\pi f jdt + \phi) d_j] $$ The `SetPhase` instruction sets $\phi$ to the instruction’s `phase` operand. Instantiate a set phase instruction, setting the output signal phase on `channel` to `phase` \[radians]. **Parameters** * **phase** ([*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"")) – The rotation angle in radians. * **channel** (*PulseChannel*) – The channel this instruction operates on. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this instruction. ## Attributes ### channel Return the [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") that this instruction is scheduled on. ### channels Returns the channels that this schedule uses. ### duration Duration of this instruction. ### id Unique identifier for this instruction. ### instructions Iterable for getting instructions from Schedule tree. ### name Name of this instruction. ### operands Return instruction operands. ### parameters Parameters which determine the instruction behavior. ### phase Return the rotation angle enacted by this instruction in radians. ### start\_time Relative begin time of this instruction. ### stop\_time Relative end time of this instruction. ## Methods ### append Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. **Parameters** * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to be appended * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` a this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### ch\_duration Return duration of the supplied channels in this Instruction. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return minimum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### insert Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted within `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule schedule * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to insert * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` inserted with this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### shift Return a new schedule shifted forward by time. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** The shifted schedule. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.instructions.SetPhase.mdx "--- title: ShiftFrequency description: API reference for qiskit.pulse.instructions.ShiftFrequency in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.instructions.ShiftFrequency --- # ShiftFrequency Bases: [`Instruction`](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"") Shift the channel frequency away from the current frequency. Creates a new shift frequency instruction. **Parameters** * **frequency** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"")) – Frequency shift of the channel in Hz. * **channel** (*PulseChannel*) – The channel this instruction operates on. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of this set channel frequency instruction. ## Attributes ### channel Return the [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") that this instruction is scheduled on. ### channels Returns the channels that this schedule uses. ### duration Duration of this instruction. ### frequency Frequency shift from the set frequency. ### id Unique identifier for this instruction. ### instructions Iterable for getting instructions from Schedule tree. ### name Name of this instruction. ### operands Return instruction operands. ### parameters Parameters which determine the instruction behavior. ### start\_time Relative begin time of this instruction. ### stop\_time Relative end time of this instruction. ## Methods ### append Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. **Parameters** * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to be appended * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` a this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### ch\_duration Return duration of the supplied channels in this Instruction. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return minimum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### insert Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted within `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule schedule * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to insert * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` inserted with this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### shift Return a new schedule shifted forward by time. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** The shifted schedule. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.instructions.ShiftFrequency.mdx "--- title: ShiftPhase description: API reference for qiskit.pulse.instructions.ShiftPhase in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.instructions.ShiftPhase --- # ShiftPhase Bases: [`Instruction`](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"") The shift phase instruction updates the modulation phase of proceeding pulses played on the same [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel""). It is a relative increase in phase determined by the `phase` operand. In particular, a PulseChannel creates pulses of the form $$ Re[\exp(i 2\pi f jdt + \phi) d_j]. $$ The `ShiftPhase` instruction causes $\phi$ to be increased by the instruction’s `phase` operand. This will affect all pulses following on the same channel. The qubit phase is tracked in software, enabling instantaneous, nearly error-free Z-rotations by using a ShiftPhase to update the frame tracking the qubit state. Instantiate a shift phase instruction, increasing the output signal phase on `channel` by `phase` \[radians]. **Parameters** * **phase** ([*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"")) – The rotation angle in radians. * **channel** (*PulseChannel*) – The channel this instruction operates on. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this instruction. ## Attributes ### channel Return the [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") that this instruction is scheduled on. ### channels Returns the channels that this schedule uses. ### duration Duration of this instruction. ### id Unique identifier for this instruction. ### instructions Iterable for getting instructions from Schedule tree. ### name Name of this instruction. ### operands Return instruction operands. ### parameters Parameters which determine the instruction behavior. ### phase Return the rotation angle enacted by this instruction in radians. ### start\_time Relative begin time of this instruction. ### stop\_time Relative end time of this instruction. ## Methods ### append Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. **Parameters** * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to be appended * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` a this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### ch\_duration Return duration of the supplied channels in this Instruction. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return minimum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### insert Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted within `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule schedule * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to insert * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` inserted with this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### shift Return a new schedule shifted forward by time. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** The shifted schedule. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.instructions.ShiftPhase.mdx "--- title: Snapshot description: API reference for qiskit.pulse.instructions.Snapshot in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.instructions.Snapshot --- # Snapshot Bases: [`Instruction`](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"") An instruction targeted for simulators, to capture a moment in the simulation. Create new snapshot. **Parameters** * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Snapshot label which is used to identify the snapshot in the output. * **snapshot\_type** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Type of snapshot, e.g., “state” (take a snapshot of the quantum state). The types of snapshots offered are defined by the simulator used. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Snapshot name which defaults to `label`. This parameter is only for display purposes and is not taken into account during comparison. ## Attributes ### channel Return the [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") that this instruction is scheduled on; trivially, a `SnapshotChannel`. ### channels Returns the channels that this schedule uses. ### duration Duration of this instruction. ### id Unique identifier for this instruction. ### instructions Iterable for getting instructions from Schedule tree. ### label Label of snapshot. ### name Name of this instruction. ### operands Return instruction operands. ### parameters Parameters which determine the instruction behavior. ### start\_time Relative begin time of this instruction. ### stop\_time Relative end time of this instruction. ### type Type of snapshot. ## Methods ### append Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. **Parameters** * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to be appended * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` a this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### ch\_duration Return duration of the supplied channels in this Instruction. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return minimum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### insert Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted within `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule schedule * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to insert * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` inserted with this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### shift Return a new schedule shifted forward by time. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** The shifted schedule. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.instructions.Snapshot.mdx "--- title: TimeBlockade description: API reference for qiskit.pulse.instructions.TimeBlockade in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.instructions.TimeBlockade --- # TimeBlockade Bases: `Directive` Pulse `TimeBlockade` directive. This instruction is intended to be used internally within the pulse builder, to convert [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") into [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock""). Because [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") cannot take an absolute instruction time interval, this directive helps the block representation to find the starting time of an instruction. **Example** This schedule plays constant pulse at t0 = 120. ```python schedule = Schedule() schedule.insert(120, Play(Constant(10, 0.1), DriveChannel(0))) ``` This schedule block is expected to be identical to above at a time of execution. ```python block = ScheduleBlock() block.append(TimeBlockade(120, DriveChannel(0))) block.append(Play(Constant(10, 0.1), DriveChannel(0))) ``` Such conversion may be done by ```python from qiskit.pulse.transforms import block_to_schedule, remove_directives schedule = remove_directives(block_to_schedule(block)) ``` The TimeBlockade instruction behaves almost identically to [`Delay`](qiskit.pulse.instructions.Delay ""qiskit.pulse.instructions.Delay"") instruction. However, the TimeBlockade is just a compiler directive and must be removed before execution. This may be done by [`remove_directives()`](pulse#qiskit.pulse.transforms.remove_directives ""qiskit.pulse.transforms.remove_directives"") transform. Once these directives are removed, occupied timeslots are released and user can insert another instruction without timing overlap. Create a time blockade directive. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Length of time of the occupation in terms of dt. * **channel** (*chans.Channel*) – The channel that will be the occupied. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the time blockade for display purposes. ## Attributes ### channel Return the [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") that this instruction is scheduled on. ### channels Returns the channels that this schedule uses. ### duration Duration of this instruction. ### id Unique identifier for this instruction. ### instructions Iterable for getting instructions from Schedule tree. ### name Name of this instruction. ### operands Return instruction operands. ### parameters Parameters which determine the instruction behavior. ### start\_time Relative begin time of this instruction. ### stop\_time Relative end time of this instruction. ## Methods ### append Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. **Parameters** * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to be appended * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` a this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### ch\_duration Return duration of the supplied channels in this Instruction. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return minimum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time for supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Supplied channels **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### insert Return a new [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") with `schedule` inserted within `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule schedule * **schedule** (*Union\['Schedule', 'Instruction']*) – Schedule or instruction to insert * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** A new schedule with `schedule` inserted with this instruction at t=0. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### shift Return a new schedule shifted forward by time. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to name of self **Returns** The shifted schedule. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.instructions.TimeBlockade.mdx "--- title: InstructionScheduleMap description: API reference for qiskit.pulse.InstructionScheduleMap in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.InstructionScheduleMap --- # InstructionScheduleMap Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Mapping from [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") [`qiskit.circuit.Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") names and qubits to [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") s. In particular, the mapping is formatted as type: ```python Dict[str, Dict[Tuple[int], Schedule]] ``` where the first key is the name of a circuit instruction (e.g. `'u1'`, `'measure'`), the second key is a tuple of qubit indices, and the final value is a Schedule implementing the requested instruction. These can usually be seen as gate calibrations. Initialize a circuit instruction to schedule mapper instance. ## Attributes ### instructions Return all instructions which have definitions. By default, these are typically the basis gates along with other instructions such as measure and reset. **Returns** The names of all the circuit instructions which have Schedule definitions in this. ## Methods ### add Add a new known instruction for the given qubits and its mapping to a pulse schedule. **Parameters** * **instruction** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*circuit.instruction.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – The name of the instruction to add. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubits which the instruction applies to. * **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *|*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") *| Callable\[...,*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *|*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"")*]*) – The Schedule that implements the given instruction. * **arguments** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*] | None*) – List of parameter names to create a parameter-bound schedule from the associated gate instruction. If [`get()`](#qiskit.pulse.InstructionScheduleMap.get ""qiskit.pulse.InstructionScheduleMap.get"") is called with arguments rather than keyword arguments, this parameter list is used to map the input arguments to parameter objects stored in the target schedule. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – If the qubits are provided as an empty iterable. ### assert\_has Error if the given instruction is not defined. **Parameters** * **instruction** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*circuit.instruction.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – The instruction for which to look. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The specific qubits for the instruction. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – If the instruction is not defined on the qubits. ### get Return the defined [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") or [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") for the given instruction on the given qubits. If all keys are not specified this method returns schedule with unbound parameters. **Parameters** * **instruction** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*circuit.instruction.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – Name of the instruction or the instruction itself. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubits for the instruction. * **\*params** ([*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Command parameters for generating the output schedule. * **\*\*kwparams** ([*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Keyworded command parameters for generating the schedule. **Returns** The Schedule defined for the input. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") | [ScheduleBlock](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") ### get\_parameters Return the list of parameters taken by the given instruction on the given qubits. **Parameters** * **instruction** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*circuit.instruction.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – Name of the instruction. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubits for the instruction. **Returns** The names of the parameters required by the instruction. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)""), …] ### has Is the instruction defined for the given qubits? **Parameters** * **instruction** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*circuit.instruction.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – The instruction for which to look. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The specific qubits for the instruction. **Returns** True iff the instruction is defined. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### has\_custom\_gate Return `True` if the map has user provided instruction. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### pop Remove and return the defined schedule for the given instruction on the given qubits. **Parameters** * **instruction** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*circuit.instruction.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – Name of the instruction. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubits for the instruction. * **\*params** ([*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Command parameters for generating the output schedule. * **\*\*kwparams** ([*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Keyworded command parameters for generating the schedule. **Returns** The Schedule defined for the input. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") | [ScheduleBlock](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") ### qubit\_instructions Return a list of the instruction names that are defined by the backend for the given qubit or qubits. **Parameters** **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – A qubit index, or a list or tuple of indices. **Returns** All the instructions which are defined on the qubits. For 1 qubit, all the 1Q instructions defined. For multiple qubits, all the instructions which apply to that whole set of qubits (e.g. `qubits=[0, 1]` may return `['cx']`). **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")] ### qubits\_with\_instruction Return a list of the qubits for which the given instruction is defined. Single qubit instructions return a flat list, and multiqubit instructions return a list of ordered tuples. **Parameters** **instruction** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*circuit.instruction.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – The name of the circuit instruction. **Returns** Qubit indices which have the given instruction defined. This is a list of tuples if the instruction has an arity greater than 1, or a flat list of ints otherwise. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – If the instruction is not found. **Return type** [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)"") | [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)""), …]] ### remove Remove the given instruction from the listing of instructions defined in self. **Parameters** * **instruction** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*circuit.instruction.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – The name of the instruction to add. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The qubits which the instruction applies to. ",repo/docs/api/qiskit/1.0\qiskit.pulse.InstructionScheduleMap.mdx "--- title: Constant description: API reference for qiskit.pulse.library.Constant in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.library.Constant --- # Constant Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A simple constant pulse, with an amplitude value and a duration: $$ f(x) = \text{amp}\times\exp\left(i\text{angle}\right) , 0 <= x < duration f(x) = 0 , elsewhere $$ Create new pulse instance. **Parameters** * **duration** – Pulse length in terms of the sampling period dt. * **amp** – The magnitude of the amplitude of the square envelope. * **angle** – The angle of the complex amplitude of the square envelope. Default value 0. * **name** – Display name for this pulse envelope. * **limit\_amplitude** – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. ## Attributes ### alias ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.Constant_class.rst.mdx "--- title: Cos description: API reference for qiskit.pulse.library.Cos in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.pulse.library.Cos --- # qiskit.pulse.library.Cos A cosine pulse. The envelope of the pulse is given by: $$ f(x) = \text{A}\cos\left(2\pi\text{freq}x+\text{phase}\right) , 0 <= x < duration $$ where $\text{A} = \text{amp} \times\exp\left(i\times\text{angle}\right)$. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Pulse length in terms of the sampling period dt. * **amp** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The magnitude of the amplitude of the cosine wave. Wave range is \[-amp,\`amp\`]. * **phase** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The phase of the cosine wave (note that this is not equivalent to the angle of the complex amplitude). * **freq** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The frequency of the cosine wave, in terms of 1 over sampling period. If not provided defaults to a single cycle (i.e :math:’frac\{1}\{text\{duration}}’). The frequency is limited to the range $\left(0,0.5\right]$ (the Nyquist frequency). * **angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The angle in radians of the complex phase factor uniformly scaling the pulse. Default value 0. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this pulse envelope. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. **Return type** ScalableSymbolicPulse ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.Cos_class.rst.mdx "--- title: Drag description: API reference for qiskit.pulse.library.Drag in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.library.Drag --- # Drag Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") The Derivative Removal by Adiabatic Gate (DRAG) pulse is a standard Gaussian pulse with an additional Gaussian derivative component and lifting applied. It can be calibrated either to reduce the phase error due to virtual population of the $|2\rangle$ state during the pulse or to reduce the frequency spectrum of a standard Gaussian pulse near the $|1\rangle\leftrightarrow|2\rangle$ transition, reducing the chance of leakage to the $|2\rangle$ state. $$ \begin{aligned} g(x) &= \exp\Bigl(-\frac12 \frac{(x - \text{duration}/2)^2}{\text{sigma}^2}\Bigr)\\ g'(x) &= \text{A}\times\frac{g(x)-g(-1)}{1-g(-1)}\\ f(x) &= g'(x) \times \Bigl(1 + 1j \times \text{beta} \times \Bigl(-\frac{x - \text{duration}/2}{\text{sigma}^2}\Bigr) \Bigr), \quad 0 \le x < \text{duration} \end{aligned} $$ where $g(x)$ is a standard unlifted Gaussian waveform, $g'(x)$ is the lifted [`Gaussian`](qiskit.pulse.library.Gaussian_class.rst#qiskit.pulse.library.Gaussian ""qiskit.pulse.library.Gaussian"") waveform, and $\text{A} = \text{amp} \times \exp\left(i\times\text{angle}\right)$. **References** 1. [*Gambetta, J. M., Motzoi, F., Merkel, S. T. & Wilhelm, F. K. Analytic control methods for high-fidelity unitary operations in a weakly nonlinear oscillator. Phys. Rev. A 83, 012308 (2011).*](https://link.aps.org/doi/10.1103/PhysRevA.83.012308) 2. [*F. Motzoi, J. M. Gambetta, P. Rebentrost, and F. K. Wilhelm Phys. Rev. Lett. 103, 110501 – Published 8 September 2009.*](https://link.aps.org/doi/10.1103/PhysRevLett.103.110501) Create new pulse instance. **Parameters** * **duration** – Pulse length in terms of the sampling period dt. * **amp** – The magnitude of the amplitude of the DRAG envelope. * **sigma** – A measure of how wide or narrow the Gaussian peak is; described mathematically in the class docstring. * **beta** – The correction amplitude. * **angle** – The angle of the complex amplitude of the DRAG envelope. Default value 0. * **name** – Display name for this pulse envelope. * **limit\_amplitude** – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. ## Attributes ### alias ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.Drag_class.rst.mdx "--- title: GaussianDeriv description: API reference for qiskit.pulse.library.GaussianDeriv in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.pulse.library.GaussianDeriv --- # qiskit.pulse.library.GaussianDeriv An unnormalized Gaussian derivative pulse. The Gaussian function is centered around the halfway point of the pulse, and the envelope of the pulse is given by: $$ f(x) = -\text{A}\frac{x-\mu}{\text{sigma}^{2}}\exp \left[-\left(\frac{x-\mu}{2\text{sigma}}\right)^{2}\right] , 0 <= x < duration $$ where $\text{A} = \text{amp} \times\exp\left(i\times\text{angle}\right)$, and $\mu=\text{duration}/2$. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| ParameterValueType*) – Pulse length in terms of the sampling period dt. * **amp** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The magnitude of the amplitude of the pulse (the value of the corresponding Gaussian at the midpoint duration/2). * **sigma** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – A measure of how wide or narrow the corresponding Gaussian peak is in terms of dt; described mathematically in the class docstring. * **angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The angle in radians of the complex phase factor uniformly scaling the pulse. Default value 0. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this pulse envelope. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. **Return type** ScalableSymbolicPulse ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.GaussianDeriv.mdx "--- title: GaussianSquare description: API reference for qiskit.pulse.library.GaussianSquare in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.library.GaussianSquare --- # GaussianSquare Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A square pulse with a Gaussian shaped risefall on both sides lifted such that its first sample is zero. Exactly one of the `risefall_sigma_ratio` and `width` parameters has to be specified. If `risefall_sigma_ratio` is not None and `width` is None: $$ \begin{aligned} \text{risefall} &= \text{risefall\_sigma\_ratio} \times \text{sigma}\\ \text{width} &= \text{duration} - 2 \times \text{risefall} \end{aligned} $$ If `width` is not None and `risefall_sigma_ratio` is None: $$ \text{risefall} = \frac{\text{duration} - \text{width}}{2} $$ In both cases, the lifted gaussian square pulse $f'(x)$ is defined as: $$ \begin{aligned} f'(x) &= \begin{cases} \exp\biggl(-\frac12 \frac{(x - \text{risefall})^2}{\text{sigma}^2}\biggr) & x < \text{risefall}\\ 1 & \text{risefall} \le x < \text{risefall} + \text{width}\\ \exp\biggl(-\frac12 \frac{{\bigl(x - (\text{risefall} + \text{width})\bigr)}^2} {\text{sigma}^2} \biggr) & \text{risefall} + \text{width} \le x \end{cases}\\ f(x) &= \text{A} \times \frac{f'(x) - f'(-1)}{1-f'(-1)}, \quad 0 \le x < \text{duration} \end{aligned} $$ where $f'(x)$ is the gaussian square waveform without lifting or amplitude scaling, and $\text{A} = \text{amp} \times \exp\left(i\times\text{angle}\right)$. Create new pulse instance. **Parameters** * **duration** – Pulse length in terms of the sampling period dt. * **amp** – The magnitude of the amplitude of the Gaussian and square pulse. * **sigma** – A measure of how wide or narrow the Gaussian risefall is; see the class docstring for more details. * **width** – The duration of the embedded square pulse. * **angle** – The angle of the complex amplitude of the pulse. Default value 0. * **risefall\_sigma\_ratio** – The ratio of each risefall duration to sigma. * **name** – Display name for this pulse envelope. * **limit\_amplitude** – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When width and risefall\_sigma\_ratio are both empty or both non-empty. ## Attributes ### alias ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.GaussianSquare.mdx "--- title: GaussianSquareDrag description: API reference for qiskit.pulse.library.GaussianSquareDrag in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.pulse.library.GaussianSquareDrag --- # qiskit.pulse.library.GaussianSquareDrag A square pulse with a Drag shaped rise and fall This pulse shape is similar to [`GaussianSquare`](qiskit.pulse.library.GaussianSquare ""qiskit.pulse.library.GaussianSquare"") but uses [`Drag`](qiskit.pulse.library.Drag_class.rst#qiskit.pulse.library.Drag ""qiskit.pulse.library.Drag"") for its rise and fall instead of [`Gaussian`](qiskit.pulse.library.Gaussian_class.rst#qiskit.pulse.library.Gaussian ""qiskit.pulse.library.Gaussian""). The addition of the DRAG component of the rise and fall is sometimes helpful in suppressing the spectral content of the pulse at frequencies near to, but slightly offset from, the fundamental frequency of the drive. When there is a spectator qubit close in frequency to the fundamental frequency, suppressing the drive at the spectator’s frequency can help avoid unwanted excitation of the spectator. Exactly one of the `risefall_sigma_ratio` and `width` parameters has to be specified. If `risefall_sigma_ratio` is not `None` and `width` is `None`: $$ \begin{aligned} \text{risefall} &= \text{risefall\_sigma\_ratio} \times \text{sigma}\\ \text{width} &= \text{duration} - 2 \times \text{risefall} \end{aligned} $$ If `width` is not None and `risefall_sigma_ratio` is None: $$ \text{risefall} = \frac{\text{duration} - \text{width}}{2} $$ Gaussian $g(x, c, σ)$ and lifted gaussian $g'(x, c, σ)$ curves can be written as: $$ \begin{aligned} g(x, c, σ) &= \exp\Bigl(-\frac12 \frac{(x - c)^2}{σ^2}\Bigr)\\ g'(x, c, σ) &= \frac{g(x, c, σ)-g(-1, c, σ)}{1-g(-1, c, σ)} \end{aligned} $$ From these, the lifted DRAG curve $d'(x, c, σ, β)$ can be written as $$ d'(x, c, σ, β) = g'(x, c, σ) \times \Bigl(1 + 1j \times β \times \Bigl(-\frac{x - c}{σ^2}\Bigr)\Bigr) $$ The lifted gaussian square drag pulse $f'(x)$ is defined as: $$ \begin{aligned} f'(x) &= \begin{cases} \text{A} \times d'(x, \text{risefall}, \text{sigma}, \text{beta}) & x < \text{risefall}\\ \text{A} & \text{risefall} \le x < \text{risefall} + \text{width}\\ \text{A} \times \times d'( x - (\text{risefall} + \text{width}), \text{risefall}, \text{sigma}, \text{beta} ) & \text{risefall} + \text{width} \le x \end{cases}\\ \end{aligned} $$ where $\text{A} = \text{amp} \times \exp\left(i\times\text{angle}\right)$. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Pulse length in terms of the sampling period dt. * **amp** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The amplitude of the DRAG rise and fall and of the square pulse. * **sigma** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – A measure of how wide or narrow the DRAG risefall is; see the class docstring for more details. * **beta** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The DRAG correction amplitude. * **width** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The duration of the embedded square pulse. * **angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The angle in radians of the complex phase factor uniformly scaling the pulse. Default value 0. * **risefall\_sigma\_ratio** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The ratio of each risefall duration to sigma. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this pulse envelope. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When width and risefall\_sigma\_ratio are both empty or both non-empty. **Return type** ScalableSymbolicPulse ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.GaussianSquareDrag.mdx "--- title: Gaussian description: API reference for qiskit.pulse.library.Gaussian in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.library.Gaussian --- # Gaussian Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A lifted and truncated pulse envelope shaped according to the Gaussian function whose mean is centered at the center of the pulse (duration / 2): $$ \begin{aligned} f'(x) &= \exp\Bigl( -\frac12 \frac{{(x - \text{duration}/2)}^2}{\text{sigma}^2} \Bigr)\\ f(x) &= \text{A} \times \frac{f'(x) - f'(-1)}{1-f'(-1)}, \quad 0 \le x < \text{duration} \end{aligned} $$ where $f'(x)$ is the gaussian waveform without lifting or amplitude scaling, and $\text{A} = \text{amp} \times \exp\left(i\times\text{angle}\right)$. Create new pulse instance. **Parameters** * **duration** – Pulse length in terms of the sampling period dt. * **amp** – The magnitude of the amplitude of the Gaussian envelope. * **sigma** – A measure of how wide or narrow the Gaussian peak is; described mathematically in the class docstring. * **angle** – The angle of the complex amplitude of the Gaussian envelope. Default value 0. * **name** – Display name for this pulse envelope. * **limit\_amplitude** – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. ## Attributes ### alias ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.Gaussian_class.rst.mdx "--- title: gaussian_square_echo description: API reference for qiskit.pulse.library.gaussian_square_echo in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.pulse.library.gaussian_square_echo --- # qiskit.pulse.library.gaussian\_square\_echo An echoed Gaussian square pulse with an active tone overlaid on it. The Gaussian Square Echo pulse is composed of three pulses. First, a Gaussian Square pulse $f_{echo}(x)$ with amplitude `amp` and phase `angle` playing for half duration, followed by a second Gaussian Square pulse $-f_{echo}(x)$ with opposite amplitude and same phase playing for the rest of the duration. Third a Gaussian Square pulse $f_{active}(x)$ with amplitude `active_amp` and phase `active_angle` playing for the entire duration. The Gaussian Square Echo pulse $g_e()$ can be written as: $$ \begin{aligned} g_e(x) &= \begin{cases} f_{\text{active}} + f_{\text{echo}}(x) & x < \frac{\text{duration}}{2}\\ f_{\text{active}} - f_{\text{echo}}(x) & \frac{\text{duration}}{2} < x \end{cases}\\ \end{aligned} $$ One case where this pulse can be used is when implementing a direct CNOT gate with a cross-resonance superconducting qubit architecture. When applying this pulse to the target qubit, the active portion can be used to cancel IX terms from the cross-resonance drive while the echo portion can reduce the impact of a static ZZ coupling. Exactly one of the `risefall_sigma_ratio` and `width` parameters has to be specified. If `risefall_sigma_ratio` is not `None` and `width` is `None`: $$ \begin{aligned} \text{risefall} &= \text{risefall\_sigma\_ratio} \times \text{sigma}\\ \text{width} &= \text{duration} - 2 \times \text{risefall} \end{aligned} $$ If `width` is not None and `risefall_sigma_ratio` is None: $$ \text{risefall} = \frac{\text{duration} - \text{width}}{2} $$ **References** 1. [*Jurcevic, P., Javadi-Abhari, A., Bishop, L. S., Lauer, I., Bogorin, D. F., Brink, M., Capelluto, L., G\{“u}nl\{“u}k, O., Itoko, T., Kanazawa, N. & others Demonstration of quantum volume 64 on a superconducting quantum computing system. (Section V)*](https://iopscience.iop.org/article/10.1088/2058-9565/abe519) **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| ParameterValueType*) – Pulse length in terms of the sampling period dt. * **amp** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The amplitude of the rise and fall and of the echoed pulse. * **sigma** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – A measure of how wide or narrow the risefall is; see the class docstring for more details. * **width** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The duration of the embedded square pulse. * **angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The angle in radians of the complex phase factor uniformly scaling the echoed pulse. Default value 0. * **active\_amp** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The amplitude of the active pulse. * **active\_angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The angle in radian of the complex phase factor uniformly scaling the active pulse. Default value 0. * **risefall\_sigma\_ratio** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The ratio of each risefall duration to sigma. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this pulse envelope. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When width and risefall\_sigma\_ratio are both empty or both non-empty. **Return type** [SymbolicPulse](qiskit.pulse.library.SymbolicPulse ""qiskit.pulse.library.SymbolicPulse"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.gaussian_square_echo.mdx "--- title: Sawtooth description: API reference for qiskit.pulse.library.Sawtooth in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.pulse.library.Sawtooth --- # qiskit.pulse.library.Sawtooth A sawtooth pulse. The envelope of the pulse is given by: $$ f(x) = 2\text{A}\left[g\left(x\right)- \lfloor g\left(x\right)+\frac{1}{2}\rfloor\right] $$ where $\text{A} = \text{amp} \times\exp\left(i\times\text{angle}\right)$, $g\left(x\right)=x\times\text{freq}+\frac{\text{phase}}{2\pi}$, and $\lfloor ...\rfloor$ is the floor operation. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Pulse length in terms of the sampling period dt. * **amp** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The magnitude of the amplitude of the sawtooth wave. Wave range is \[-amp,\`amp\`]. * **phase** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The phase of the sawtooth wave (note that this is not equivalent to the angle of the complex amplitude) * **freq** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The frequency of the sawtooth wave, in terms of 1 over sampling period. If not provided defaults to a single cycle (i.e :math:’frac\{1}\{text\{duration}}’). The frequency is limited to the range $\left(0,0.5\right]$ (the Nyquist frequency). * **angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The angle in radians of the complex phase factor uniformly scaling the pulse. Default value 0. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this pulse envelope. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. **Return type** ScalableSymbolicPulse ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.Sawtooth_class.rst.mdx "--- title: SechDeriv description: API reference for qiskit.pulse.library.SechDeriv in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.pulse.library.SechDeriv --- # qiskit.pulse.library.SechDeriv An unnormalized sech derivative pulse. The sech function is centered around the halfway point of the pulse, and the envelope of the pulse is given by: $$ f(x) = \text{A}\frac{d}{dx}\left[\text{sech} \left(\frac{x-\mu}{\text{sigma}}\right)\right] , 0 <= x < duration $$ where $\text{A} = \text{amp} \times\exp\left(i\times\text{angle}\right)$, $\mu=\text{duration}/2$, and $d/dx$ is a derivative with respect to x. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| ParameterValueType*) – Pulse length in terms of the sampling period dt. * **amp** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The magnitude of the amplitude of the pulse (the value of the corresponding sech function at the midpoint duration/2). * **sigma** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – A measure of how wide or narrow the corresponding sech peak is, in terms of dt; described mathematically in the class docstring. * **angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The angle in radians of the complex phase factor uniformly scaling the pulse. Default value 0. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this pulse envelope. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. **Return type** ScalableSymbolicPulse ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.SechDeriv.mdx "--- title: Sech description: API reference for qiskit.pulse.library.Sech in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.pulse.library.Sech --- # qiskit.pulse.library.Sech An unnormalized sech pulse. The sech function is centered around the halfway point of the pulse, and the envelope of the pulse is given by: $$ f(x) = \text{A}\text{sech}\left( \frac{x-\mu}{\text{sigma}}\right) , 0 <= x < duration $$ where $\text{A} = \text{amp} \times\exp\left(i\times\text{angle}\right)$, and $\mu=\text{duration}/2$. If zero\_ends is set to True, the output y is modified: .. math: ```python y\left(x\right) \mapsto \text{A}\frac{y-y^{*}}{\text{A}-y^{*}}, ``` where $y^{*}$ is the value of $y$ at the endpoints (at $x=-1 and :math:`x=\text{duration}+1$). This shifts the endpoints value to zero, while also rescaling to preserve the amplitude at :math:text\{duration}/2\`\`. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| ParameterValueType*) – Pulse length in terms of the sampling period dt. * **amp** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The magnitude of the amplitude of the pulse (the value at the midpoint duration/2). * **sigma** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – A measure of how wide or narrow the sech peak is in terms of dt; described mathematically in the class docstring. * **angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The angle in radians of the complex phase factor uniformly scaling the pulse. Default value 0. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this pulse envelope. * **zero\_ends** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If True, zeros the ends at x = -1, x = duration + 1, but rescales to preserve amp. Default value True. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. **Return type** ScalableSymbolicPulse ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.Sech_fun.rst.mdx "--- title: Sin description: API reference for qiskit.pulse.library.Sin in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.pulse.library.Sin --- # qiskit.pulse.library.Sin A sinusoidal pulse. The envelope of the pulse is given by: $$ f(x) = \text{A}\sin\left(2\pi\text{freq}x+\text{phase}\right) , 0 <= x < duration $$ where $\text{A} = \text{amp} \times\exp\left(i\times\text{angle}\right)$. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Pulse length in terms of the sampling period dt. * **amp** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The magnitude of the amplitude of the sinusoidal wave. Wave range is \[-amp,\`amp\`]. * **phase** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The phase of the sinusoidal wave (note that this is not equivalent to the angle of the complex amplitude) * **freq** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The frequency of the sinusoidal wave, in terms of 1 over sampling period. If not provided defaults to a single cycle (i.e :math:’frac\{1}\{text\{duration}}’). The frequency is limited to the range $\left(0,0.5\right]$ (the Nyquist frequency). * **angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The angle in radians of the complex phase factor uniformly scaling the pulse. Default value 0. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this pulse envelope. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. **Return type** ScalableSymbolicPulse ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.Sin_class.rst.mdx "--- title: Square description: API reference for qiskit.pulse.library.Square in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.pulse.library.Square --- # qiskit.pulse.library.Square A square wave pulse. The envelope of the pulse is given by: $$ f(x) = \text{A}\text{sign}\left[\sin \left(2\pi x\times\text{freq}+\text{phase}\right)\right] , 0 <= x < duration $$ where $\text{A} = \text{amp} \times\exp\left(i\times\text{angle}\right)$, and $\text{sign}$ is the sign function with the convention $\text{sign}\left(0\right)=1$. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| ParameterValueType*) – Pulse length in terms of the sampling period dt. * **amp** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The magnitude of the amplitude of the square wave. Wave range is \[-amp,\`amp\`]. * **phase** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The phase of the square wave (note that this is not equivalent to the angle of the complex amplitude). * **freq** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The frequency of the square wave, in terms of 1 over sampling period. If not provided defaults to a single cycle (i.e :math:’frac\{1}\{text\{duration}}’). The frequency is limited to the range $\left(0,0.5\right]$ (the Nyquist frequency). * **angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The angle in radians of the complex phase factor uniformly scaling the pulse. Default value 0. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this pulse envelope. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. **Return type** ScalableSymbolicPulse ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.Square_fun.rst.mdx "--- title: SymbolicPulse description: API reference for qiskit.pulse.library.SymbolicPulse in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.library.SymbolicPulse --- # SymbolicPulse Bases: `Pulse` The pulse representation model with parameters and symbolic expressions. A symbolic pulse instance can be defined with an envelope and parameter constraints. Envelope and parameter constraints should be provided as symbolic expressions. Rather than creating a subclass, different pulse shapes can be distinguished by the instance attributes [`SymbolicPulse.envelope`](#qiskit.pulse.library.SymbolicPulse.envelope ""qiskit.pulse.library.SymbolicPulse.envelope"") and [`SymbolicPulse.pulse_type`](#qiskit.pulse.library.SymbolicPulse.pulse_type ""qiskit.pulse.library.SymbolicPulse.pulse_type""). The symbolic expressions must be defined either with [SymPy](https://www.sympy.org/en/index.html) or [Symengine](https://symengine.org). Usually Symengine-based expression is much more performant for instantiation of the [`SymbolicPulse`](#qiskit.pulse.library.SymbolicPulse ""qiskit.pulse.library.SymbolicPulse""), however, it doesn’t support every functions available in SymPy. You may need to choose proper library depending on how you define your pulses. Symengine works in the most envelopes and constraints, and thus it is recommended to use this library especially when your program contains a lot of pulses. Also note that Symengine has the limited platform support and may not be available for your local system. Symengine is a required dependency for Qiskit on platforms that support it will always be installed along with Qiskit on macOS `x86_64` and `arm64`, and Linux `x86_64`, `aarch64`, and `ppc64le`. For 64-bit Windows users they will need to manual install it. For 32-bit platforms such as `i686` and `armv7` Linux, and on Linux `s390x` there are no pre-compiled packages available and to use symengine you’ll need to compile it from source. If Symengine is not available in your environment SymPy will be used. **Envelope function** The waveform at time $t$ is generated by the [`get_waveform()`](#qiskit.pulse.library.SymbolicPulse.get_waveform ""qiskit.pulse.library.SymbolicPulse.get_waveform"") according to $$ F(t, \Theta) = \times F(t, {\rm duration}, \overline{\rm params}) $$ where $\Theta$ is the set of full pulse parameters in the [`SymbolicPulse.parameters`](#qiskit.pulse.library.SymbolicPulse.parameters ""qiskit.pulse.library.SymbolicPulse.parameters"") dictionary which must include the $\rm duration$. Note that the $F$ is an envelope of the waveform, and a programmer must provide this as a symbolic expression. $\overline{\rm params}$ can be arbitrary complex values as long as they pass [`validate_parameters()`](#qiskit.pulse.library.SymbolicPulse.validate_parameters ""qiskit.pulse.library.SymbolicPulse.validate_parameters"") and your quantum backend can accept. The time $t$ and $\rm duration$ are in units of dt, i.e. sample time resolution, and this function is sampled with a discrete time vector in $[0, {\rm duration}]$ sampling the pulse envelope at every 0.5 dt (middle sampling strategy) when the [`SymbolicPulse.get_waveform()`](#qiskit.pulse.library.SymbolicPulse.get_waveform ""qiskit.pulse.library.SymbolicPulse.get_waveform"") method is called. The sample data is not generated until this method is called thus a symbolic pulse instance only stores parameter values and waveform shape, which greatly reduces memory footprint during the program generation. **Pulse validation** When a symbolic pulse is instantiated, the method [`validate_parameters()`](#qiskit.pulse.library.SymbolicPulse.validate_parameters ""qiskit.pulse.library.SymbolicPulse.validate_parameters"") is called, and performs validation of the pulse. The validation process involves testing the constraint functions and the maximal amplitude of the pulse (see below). While the validation process will improve code stability, it will reduce performance and might create compatibility issues (particularly with JAX). Therefore, it is possible to disable the validation by setting the class attribute [`disable_validation`](#qiskit.pulse.library.SymbolicPulse.disable_validation ""qiskit.pulse.library.SymbolicPulse.disable_validation"") to `True`. **Constraint functions** Constraints on the parameters are defined with an instance attribute [`SymbolicPulse.constraints`](#qiskit.pulse.library.SymbolicPulse.constraints ""qiskit.pulse.library.SymbolicPulse.constraints"") which can be provided through the constructor. The constraints value must be a symbolic expression, which is a function of parameters to be validated and must return a boolean value being `True` when parameters are valid. If there are multiple conditions to be evaluated, these conditions can be concatenated with logical expressions such as `And` and `Or` in SymPy or Symengine. The symbolic pulse instance can be played only when the constraint function returns `True`. The constraint is evaluated when [`validate_parameters()`](#qiskit.pulse.library.SymbolicPulse.validate_parameters ""qiskit.pulse.library.SymbolicPulse.validate_parameters"") is called. **Maximum amplitude validation** When you play a pulse in a quantum backend, you might face the restriction on the power that your waveform generator can handle. Usually, the pulse amplitude is normalized by this maximum power, namely $\max |F| \leq 1$. This condition is evaluated along with above constraints when you set `limit_amplitude = True` in the constructor. To evaluate maximum amplitude of the waveform, we need to call [`get_waveform()`](#qiskit.pulse.library.SymbolicPulse.get_waveform ""qiskit.pulse.library.SymbolicPulse.get_waveform""). However, this introduces a significant overhead in the validation, and this cannot be ignored when you repeatedly instantiate symbolic pulse instances. [`SymbolicPulse.valid_amp_conditions`](#qiskit.pulse.library.SymbolicPulse.valid_amp_conditions ""qiskit.pulse.library.SymbolicPulse.valid_amp_conditions"") provides a condition to skip this waveform validation, and the waveform is not generated as long as this condition returns `True`, so that healthy symbolic pulses are created very quick. For example, for a simple pulse shape like `amp * cos(f * t)`, we know that pulse amplitude is valid as long as `amp` remains less than magnitude 1.0. So `abs(amp) <= 1` could be passed as [`SymbolicPulse.valid_amp_conditions`](#qiskit.pulse.library.SymbolicPulse.valid_amp_conditions ""qiskit.pulse.library.SymbolicPulse.valid_amp_conditions"") to skip doing a full waveform evaluation for amplitude validation. This expression is provided through the constructor. If this is not provided, the waveform is generated everytime when [`validate_parameters()`](#qiskit.pulse.library.SymbolicPulse.validate_parameters ""qiskit.pulse.library.SymbolicPulse.validate_parameters"") is called. **Examples** This is how a user can instantiate a symbolic pulse instance. In this example, we instantiate a custom Sawtooth envelope. ```python from qiskit.pulse.library import SymbolicPulse my_pulse = SymbolicPulse( pulse_type=""Sawtooth"", duration=100, parameters={""amp"": 0.1, ""freq"": 0.05}, name=""pulse1"", ) ``` Note that [`SymbolicPulse`](#qiskit.pulse.library.SymbolicPulse ""qiskit.pulse.library.SymbolicPulse"") can be instantiated without providing the envelope and constraints. However, this instance cannot generate waveforms without knowing the envelope definition. Now you need to provide the envelope. ```python import sympy from qiskit.pulse.library import SymbolicPulse t, amp, freq = sympy.symbols(""t, amp, freq"") envelope = 2 * amp * (freq * t - sympy.floor(1 / 2 + freq * t)) my_pulse = SymbolicPulse( pulse_type=""Sawtooth"", duration=100, parameters={""amp"": 0.1, ""freq"": 0.05}, envelope=envelope, name=""pulse1"", ) my_pulse.draw() ``` ![../\_images/qiskit-pulse-library-SymbolicPulse-1.png](/images/api/qiskit/1.0/qiskit-pulse-library-SymbolicPulse-1.png) Likewise, you can define [`SymbolicPulse.constraints`](#qiskit.pulse.library.SymbolicPulse.constraints ""qiskit.pulse.library.SymbolicPulse.constraints"") for `my_pulse`. After providing the envelope definition, you can generate the waveform data. Note that it would be convenient to define a factory function that automatically accomplishes this procedure. ```python def Sawtooth(duration, amp, freq, name): t, amp, freq = sympy.symbols(""t, amp, freq"") instance = SymbolicPulse( pulse_type=""Sawtooth"", duration=duration, parameters={""amp"": amp, ""freq"": freq}, envelope=2 * amp * (freq * t - sympy.floor(1 / 2 + freq * t)), name=name, ) return instance ``` You can also provide a `Parameter` object in the `parameters` dictionary, or define `duration` with a `Parameter` object when you instantiate the symbolic pulse instance. A waveform cannot be generated until you assign all unbounded parameters. Note that parameters will be assigned through the schedule playing the pulse. **Serialization** The [`SymbolicPulse`](#qiskit.pulse.library.SymbolicPulse ""qiskit.pulse.library.SymbolicPulse"") subclass can be serialized along with the symbolic expressions through [`qiskit.qpy`](qpy#module-qiskit.qpy ""qiskit.qpy""). A user can therefore create a custom pulse subclass with a novel envelope and constraints, and then one can instantiate the class with certain parameters to run on a backend. This pulse instance can be saved in the QPY binary, which can be loaded afterwards even within the environment not having original class definition loaded. This mechanism also allows us to easily share a pulse program including custom pulse instructions with collaborators. Create a parametric pulse. **Parameters** * **pulse\_type** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Display name of this pulse shape. * **duration** ([*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *|*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Duration of pulse. * **parameters** (*Mapping\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*,* [*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *|*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*] | None*) – Dictionary of pulse parameters that defines the pulse envelope. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this particular pulse envelope. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, then limit the absolute value of the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. * **envelope** (*sym.Expr | None*) – Pulse envelope expression. * **constraints** (*sym.Expr | None*) – Pulse parameter constraint expression. * **valid\_amp\_conditions** (*sym.Expr | None*) – Extra conditions to skip a full-waveform check for the amplitude limit. If this condition is not met, then the validation routine will investigate the full-waveform and raise an error when the amplitude norm of any data point exceeds 1.0. If not provided, the validation always creates a full-waveform. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When not all parameters are listed in the attribute `PARAM_DEF`. ## Attributes ### constraints Return symbolic expression for the pulse parameter constraints. ### disable\_validation ### duration ### envelope Return symbolic expression for the pulse envelope. ### id Unique identifier for this pulse. ### limit\_amplitude ### name ### parameters ### pulse\_type Return display name of the pulse shape. ### valid\_amp\_conditions Return symbolic expression for the pulse amplitude constraints. ## Methods ### draw Plot the interpolated envelope of pulse. **Parameters** * **style** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any] | None*) – Stylesheet options. This can be dictionary or preset stylesheet classes. See `IQXStandard`, `IQXSimple`, and `IQXDebugging` for details of preset stylesheets. * **backend** (*Optional\[BaseBackend]*) – Backend object to play the input pulse program. If provided, the plotter may use to make the visualization hardware aware. * **time\_range** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None*) – Set horizontal axis limit. Tuple `(tmin, tmax)`. * **time\_unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The unit of specified time range either `dt` or `ns`. The unit of `ns` is available only when `backend` object is provided. * **show\_waveform\_info** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Show waveform annotations, i.e. name, of waveforms. Set `True` to show additional information about waveforms. * **plotter** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of plotter API to generate an output image. One of following APIs should be specified: ```python mpl2d: Matplotlib API for 2D image generation. Matplotlib API to generate 2D image. Charts are placed along y axis with vertical offset. This API takes matplotlib.axes.Axes as `axis` input. ``` axis and style kwargs may depend on the plotter. * **axis** (*Any | None*) – Arbitrary object passed to the plotter. If this object is provided, the plotters use a given `axis` instead of internally initializing a figure object. This object format depends on the plotter. See plotter argument for details. **Returns** Visualization output data. The returned data type depends on the `plotter`. If matplotlib family is specified, this will be a `matplotlib.pyplot.Figure` data. ### get\_waveform Return a Waveform with samples filled according to the formula that the pulse represents and the parameter values it contains. Since the returned array is a discretized time series of the continuous function, this method uses a midpoint sampler. For `duration`, return: $$ \{f(t+0.5) \in \mathbb{C} | t \in \mathbb{Z} \wedge 0<=t<\texttt{duration}\} $$ **Returns** A waveform representation of this pulse. **Raises** * [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When parameters are not assigned. * [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When expression for pulse envelope is not assigned. **Return type** [*Waveform*](qiskit.pulse.library.Waveform ""qiskit.pulse.library.waveform.Waveform"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### validate\_parameters Validate parameters. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – If the parameters passed are not valid. ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.SymbolicPulse.mdx "--- title: Triangle description: API reference for qiskit.pulse.library.Triangle in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.pulse.library.Triangle --- # qiskit.pulse.library.Triangle A triangle wave pulse. The envelope of the pulse is given by: $$ f(x) = \text{A}\left[\text{sawtooth}\left(x\right)\right] , 0 <= x < duration $$ where $\text{A} = \text{amp} \times\exp\left(i\times\text{angle}\right)$, and $\text{sawtooth}\left(x\right)$ is a sawtooth wave with the same frequency as the triangle wave, but a phase shifted by $\frac{\pi}{2}$. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Pulse length in terms of the sampling period dt. * **amp** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The magnitude of the amplitude of the triangle wave. Wave range is \[-amp,\`amp\`]. * **phase** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The phase of the triangle wave (note that this is not equivalent to the angle of the complex amplitude) * **freq** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The frequency of the triangle wave, in terms of 1 over sampling period. If not provided defaults to a single cycle (i.e :math:’frac\{1}\{text\{duration}}’). The frequency is limited to the range $\left(0,0.5\right]$ (the Nyquist frequency). * **angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") *| None*) – The angle in radians of the complex phase factor uniformly scaling the pulse. Default value 0. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Display name for this pulse envelope. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, then limit the amplitude of the waveform to 1. The default is `True` and the amplitude is constrained to 1. **Returns** ScalableSymbolicPulse instance. **Return type** ScalableSymbolicPulse ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.Triangle_class.rst.mdx "--- title: Waveform description: API reference for qiskit.pulse.library.Waveform in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.library.Waveform --- # Waveform Bases: `Pulse` A pulse specified completely by complex-valued samples; each sample is played for the duration of the backend cycle-time, dt. Create new sample pulse command. **Parameters** * **samples** (*np.ndarray |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*]*) – Complex array of the samples in the pulse envelope. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Unique name to identify the pulse. * **epsilon** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Pulse sample norm tolerance for clipping. If any sample’s norm exceeds unity by less than or equal to epsilon it will be clipped to unit norm. If the sample norm is greater than 1+epsilon an error will be raised. * **limit\_amplitude** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – Passed to parent Pulse ## Attributes ### duration ### name ### id Unique identifier for this pulse. ### limit\_amplitude ### parameters Return a dictionary containing the pulse’s parameters. ### samples Return sample values. ## Methods ### draw Plot the interpolated envelope of pulse. **Parameters** * **style** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any] | None*) – Stylesheet options. This can be dictionary or preset stylesheet classes. See `IQXStandard`, `IQXSimple`, and `IQXDebugging` for details of preset stylesheets. * **backend** (*Optional\[BaseBackend]*) – Backend object to play the input pulse program. If provided, the plotter may use to make the visualization hardware aware. * **time\_range** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None*) – Set horizontal axis limit. Tuple `(tmin, tmax)`. * **time\_unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The unit of specified time range either `dt` or `ns`. The unit of `ns` is available only when `backend` object is provided. * **show\_waveform\_info** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Show waveform annotations, i.e. name, of waveforms. Set `True` to show additional information about waveforms. * **plotter** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of plotter API to generate an output image. One of following APIs should be specified: ```python mpl2d: Matplotlib API for 2D image generation. Matplotlib API to generate 2D image. Charts are placed along y axis with vertical offset. This API takes matplotlib.axes.Axes as `axis` input. ``` axis and style kwargs may depend on the plotter. * **axis** (*Any | None*) – Arbitrary object passed to the plotter. If this object is provided, the plotters use a given `axis` instead of internally initializing a figure object. This object format depends on the plotter. See plotter argument for details. **Returns** Visualization output data. The returned data type depends on the `plotter`. If matplotlib family is specified, this will be a `matplotlib.pyplot.Figure` data. ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.library.Waveform.mdx "--- title: Schedule description: API reference for qiskit.pulse.Schedule in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.Schedule --- # Schedule Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A quantum program *schedule* with exact time constraints for its instructions, operating over all input signal *channels* and supporting special syntaxes for building. Pulse program representation for the original Qiskit Pulse model \[1]. Instructions are not allowed to overlap in time on the same channel. This overlap constraint is immediately evaluated when a new instruction is added to the `Schedule` object. It is necessary to specify the absolute start time and duration for each instruction so as to deterministically fix its execution time. The `Schedule` program supports some syntax sugar for easier programming. * Appending an instruction to the end of a channel ```python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) ``` * Appending an instruction shifted in time by a given amount ```python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) << 30 ``` * Merge two schedules ```python sched1 = Schedule() sched1 += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) sched2 = Schedule() sched2 += Play(Gaussian(160, 0.1, 40), DriveChannel(1)) sched2 = sched1 | sched2 ``` A [`PulseError`](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") is immediately raised when the overlap constraint is violated. In the schedule representation, we cannot parametrize the duration of instructions. Thus, we need to create a new schedule object for each duration. To parametrize an instruction’s duration, the [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") representation may be used instead. **References** \[1]: [https://arxiv.org/abs/2004.06755](https://arxiv.org/abs/2004.06755) Create an empty schedule. **Parameters** * **\*schedules** (*'ScheduleComponent' |* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, 'ScheduleComponent']*) – Child Schedules of this parent Schedule. May either be passed as the list of schedules, or a list of `(start_time, schedule)` pairs. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of this schedule. Defaults to an autogenerated string if not provided. * **metadata** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *| None*) – Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the [`metadata`](#qiskit.pulse.Schedule.metadata ""qiskit.pulse.Schedule.metadata"") attribute. It will not be directly used in the schedule. **Raises** [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – if metadata is not a dict. ## Attributes ### channels Returns channels that this schedule uses. ### children Return the child schedule components of this `Schedule` in the order they were added to the schedule. **Notes** Nested schedules are returned as-is. If you want to collect only instructions, use py:meth:\~Schedule.instructions instead. **Returns** A tuple, where each element is a two-tuple containing the initial scheduled time of each `NamedValue` and the component itself. ### duration Duration of this schedule. ### instances\_counter ### instructions Get the time-ordered instructions from self. ### metadata The user provided metadata associated with the schedule. User provided `dict` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. ### name Name of this Schedule ### parameters Parameters which determine the schedule behavior. ### prefix ### start\_time Starting time of this schedule. ### stop\_time Stopping time of this schedule. ### timeslots Time keeping attribute. ## Methods ### append Return a new schedule with `schedule` inserted at the maximum time over all channels shared between `self` and `schedule`. $$ t = \textrm{max}(\texttt{x.stop_time} |\texttt{x} \in \texttt{self.channels} \cap \texttt{schedule.channels}) $$ **Parameters** * **schedule** (*ScheduleComponent*) – Schedule to be appended. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new `Schedule`. Defaults to name of `self`. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Perform operation inplace on this schedule. Otherwise return a new `Schedule`. **Return type** [Schedule](#qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### assign\_parameters Assign the parameters in this schedule according to the input. **Parameters** * **value\_dict** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*qiskit.circuit.parameterexpression.ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"")*,* [*Union*](https://docs.python.org/3/library/typing.html#typing.Union ""(in Python v3.12)"")*\[*[*qiskit.circuit.parameterexpression.ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"")*,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]]*) – A mapping from Parameters to either numeric values or another Parameter expression. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Set `True` to override this instance with new parameter. **Returns** Schedule with updated parameters. **Return type** [*Schedule*](#qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") ### ch\_duration Return the time of the end of the last instruction over the supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Channels within `self` to include. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_start\_time Return the time of the start of the first instruction over the supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Channels within `self` to include. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### ch\_stop\_time Return maximum start time over supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Channels within `self` to include. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### draw Plot the schedule. **Parameters** * **style** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any] | None*) – Stylesheet options. This can be dictionary or preset stylesheet classes. See `IQXStandard`, `IQXSimple`, and `IQXDebugging` for details of preset stylesheets. * **backend** (*Optional\[BaseBackend]*) – Backend object to play the input pulse program. If provided, the plotter may use to make the visualization hardware aware. * **time\_range** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None*) – Set horizontal axis limit. Tuple (tmin, tmax). * **time\_unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The unit of specified time range either dt or ns. The unit of ns is available only when backend object is provided. * **disable\_channels** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")*] | None*) – A control property to show specific pulse channel. Pulse channel instances provided as a list are not shown in the output image. * **show\_snapshot** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Show snapshot instructions. * **show\_framechange** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Show frame change instructions. The frame change represents instructions that modulate phase or frequency of pulse channels. * **show\_waveform\_info** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Show additional information about waveforms such as their name. * **show\_barrier** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Show barrier lines. * **plotter** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of plotter API to generate an output image. One of following APIs should be specified: ```python mpl2d: Matplotlib API for 2D image generation. Matplotlib API to generate 2D image. Charts are placed along y axis with vertical offset. This API takes matplotlib.axes.Axes as ``axis`` input. ``` `axis` and `style` kwargs may depend on the plotter. * **axis** (*Any | None*) – Arbitrary object passed to the plotter. If this object is provided, the plotters use a given `axis` instead of internally initializing a figure object. This object format depends on the plotter. See plotter argument for details. **Returns** Visualization output data. The returned data type depends on the `plotter`. If matplotlib family is specified, this will be a `matplotlib.pyplot.Figure` data. ### exclude Return a `Schedule` with only the instructions from this Schedule *failing* at least one of the provided filters. This method is the complement of py:meth:\~self.filter, so that: ```python self.filter(args) | self.exclude(args) == self ``` **Parameters** * **filter\_funcs** (*Callable*) – A list of Callables which take a (int, Union\[‘Schedule’, Instruction]) tuple and return a bool. * **channels** (*Iterable\[*[*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")*] | None*) – For example, `[DriveChannel(0), AcquireChannel(0)]`. * **instruction\_types** (*Iterable\[*[*abc.ABCMeta*](https://docs.python.org/3/library/abc.html#abc.ABCMeta ""(in Python v3.12)"")*] |* [*abc.ABCMeta*](https://docs.python.org/3/library/abc.html#abc.ABCMeta ""(in Python v3.12)"")) – For example, `[PulseInstruction, AcquireInstruction]`. * **time\_ranges** (*Iterable\[*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]] | None*) – For example, `[(0, 5), (6, 10)]`. * **intervals** (*Iterable\[Interval] | None*) – For example, `[(0, 5), (6, 10)]`. * **check\_subroutine** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Set True to individually filter instructions inside of a subroutine defined by the `Call` instruction. **Return type** [Schedule](#qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### filter Return a new `Schedule` with only the instructions from this `Schedule` which pass though the provided filters; i.e. an instruction will be retained iff every function in `filter_funcs` returns `True`, the instruction occurs on a channel type contained in `channels`, the instruction type is contained in `instruction_types`, and the period over which the instruction operates is *fully* contained in one specified in `time_ranges` or `intervals`. If no arguments are provided, `self` is returned. **Parameters** * **filter\_funcs** (*Callable*) – A list of Callables which take a (int, Union\[‘Schedule’, Instruction]) tuple and return a bool. * **channels** (*Iterable\[*[*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")*] | None*) – For example, `[DriveChannel(0), AcquireChannel(0)]`. * **instruction\_types** (*Iterable\[*[*abc.ABCMeta*](https://docs.python.org/3/library/abc.html#abc.ABCMeta ""(in Python v3.12)"")*] |* [*abc.ABCMeta*](https://docs.python.org/3/library/abc.html#abc.ABCMeta ""(in Python v3.12)"")) – For example, `[PulseInstruction, AcquireInstruction]`. * **time\_ranges** (*Iterable\[*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]] | None*) – For example, `[(0, 5), (6, 10)]`. * **intervals** (*Iterable\[Interval] | None*) – For example, `[(0, 5), (6, 10)]`. * **check\_subroutine** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Set True to individually filter instructions inside of a subroutine defined by the `Call` instruction. **Return type** [Schedule](#qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### get\_parameters Get parameter object bound to this schedule by string name. Because different `Parameter` objects can have the same name, this method returns a list of `Parameter` s for the provided name. **Parameters** **parameter\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of parameter. **Returns** Parameter objects that have corresponding name. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[qiskit.circuit.parameter.Parameter](qiskit.circuit.Parameter ""qiskit.circuit.parameter.Parameter"")] ### initialize\_from Create new schedule object with metadata of another schedule object. **Parameters** * **other\_program** (*Any*) – Qiskit program that provides metadata to new object. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of new schedule. Name of `schedule` is used by default. **Returns** New schedule object with name and metadata. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When other\_program does not provide necessary information. **Return type** [Schedule](#qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### insert Return a new schedule with `schedule` inserted into `self` at `start_time`. **Parameters** * **start\_time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to insert the schedule. * **schedule** (*ScheduleComponent*) – Schedule to insert. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to the name of self. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Perform operation inplace on this schedule. Otherwise return a new `Schedule`. **Return type** [Schedule](#qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### replace Return a `Schedule` with the `old` instruction replaced with a `new` instruction. The replacement matching is based on an instruction equality check. ```python from qiskit import pulse d0 = pulse.DriveChannel(0) sched = pulse.Schedule() old = pulse.Play(pulse.Constant(100, 1.0), d0) new = pulse.Play(pulse.Constant(100, 0.1), d0) sched += old sched = sched.replace(old, new) assert sched == pulse.Schedule(new) ``` Only matches at the top-level of the schedule tree. If you wish to perform this replacement over all instructions in the schedule tree. Flatten the schedule prior to running: ```python .. code-block:: ``` > sched = pulse.Schedule() > > sched += pulse.Schedule(old) > > sched = sched.flatten() > > sched = sched.replace(old, new) > > assert sched == pulse.Schedule(new) **Parameters** * **old** ([*Schedule*](#qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") *|*[*Instruction*](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"")) – Instruction to replace. * **new** ([*Schedule*](#qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") *|*[*Instruction*](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"")) – Instruction to replace with. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Replace instruction by mutably modifying this `Schedule`. **Returns** The modified schedule with `old` replaced by `new`. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – If the `Schedule` after replacements will has a timing overlap. **Return type** [*Schedule*](#qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") ### shift Return a schedule shifted forward by `time`. **Parameters** * **time** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Time to shift by. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new schedule. Defaults to the name of self. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Perform operation inplace on this schedule. Otherwise return a new `Schedule`. **Return type** [Schedule](#qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.Schedule.mdx "--- title: ScheduleBlock description: API reference for qiskit.pulse.ScheduleBlock in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.ScheduleBlock --- # ScheduleBlock Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Time-ordered sequence of instructions with alignment context. [`ScheduleBlock`](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") supports lazy scheduling of context instructions, i.e. their timeslots is always generated at runtime. This indicates we can parametrize instruction durations as well as other parameters. In contrast to [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") being somewhat static, [`ScheduleBlock`](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") is a dynamic representation of a pulse program. **Pulse Builder** The Qiskit pulse builder is a domain specific language that is developed on top of the schedule block. Use of the builder syntax will improve the workflow of pulse programming. See [Pulse Builder](pulse#pulse-builder) for a user guide. **Alignment contexts** A schedule block is always relatively scheduled. Instead of taking individual instructions with absolute execution time `t0`, the schedule block defines a context of scheduling and instructions under the same context are scheduled in the same manner (alignment). Several contexts are available in [Alignments](pulse#pulse-alignments). A schedule block is instantiated with one of these alignment contexts. The default context is `AlignLeft`, for which all instructions are left-justified, in other words, meaning they use as-soon-as-possible scheduling. If you need an absolute-time interval in between instructions, you can explicitly insert [`Delay`](qiskit.pulse.instructions.Delay ""qiskit.pulse.instructions.Delay"") instructions. **Nested blocks** A schedule block can contain other nested blocks with different alignment contexts. This enables advanced scheduling, where a subset of instructions is locally scheduled in a different manner. Note that a [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") instance cannot be directly added to a schedule block. To add a [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") instance, wrap it in a `Call` instruction. This is implicitly performed when a schedule is added through the [Pulse Builder](pulse#pulse-builder). **Unsupported operations** Because the schedule block representation lacks timeslots, it cannot perform particular [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") operations such as `insert()` or `shift()` that require instruction start time `t0`. In addition, [`exclude()`](#qiskit.pulse.ScheduleBlock.exclude ""qiskit.pulse.ScheduleBlock.exclude"") and [`filter()`](#qiskit.pulse.ScheduleBlock.filter ""qiskit.pulse.ScheduleBlock.filter"") methods are not supported because these operations may identify the target instruction with `t0`. Except for these operations, [`ScheduleBlock`](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") provides full compatibility with [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule""). **Subroutine** The timeslots-free representation offers much greater flexibility for writing pulse programs. Because [`ScheduleBlock`](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") only cares about the ordering of the child blocks we can add an undefined pulse sequence as a subroutine of the main program. If your program contains the same sequence multiple times, this representation may reduce the memory footprint required by the program construction. Such a subroutine is realized by the special compiler directive [`Reference`](qiskit.pulse.instructions.Reference ""qiskit.pulse.instructions.Reference"") that is defined by a unique set of reference key strings to the subroutine. The (executable) subroutine is separately stored in the main program. Appended reference directives are resolved when the main program is executed. Subroutines must be assigned through [`assign_references()`](#qiskit.pulse.ScheduleBlock.assign_references ""qiskit.pulse.ScheduleBlock.assign_references"") before execution. One way to reference a subroutine in a schedule is to use the pulse builder’s [`reference()`](pulse#qiskit.pulse.builder.reference ""qiskit.pulse.builder.reference"") function to declare an unassigned reference. In this example, the program is called with the reference key “grand\_child”. You can call a subroutine without specifying a substantial program. ```python from qiskit import pulse from qiskit.circuit.parameter import Parameter amp1 = Parameter(""amp1"") amp2 = Parameter(""amp2"") with pulse.build() as sched_inner: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as sched_outer: with pulse.align_right(): pulse.reference(""grand_child"") pulse.play(pulse.Constant(200, amp2), pulse.DriveChannel(0)) ``` Now you assign the inner pulse program to this reference. ```python sched_outer.assign_references({(""grand_child"", ): sched_inner}) print(sched_outer.parameters) ``` ```python {Parameter(amp1), Parameter(amp2)} ``` The outer program now has the parameter `amp2` from the inner program, indicating that the inner program’s data has been made available to the outer program. The program calling the “grand\_child” has a reference program description which is accessed through [`ScheduleBlock.references`](#qiskit.pulse.ScheduleBlock.references ""qiskit.pulse.ScheduleBlock.references""). ```python print(sched_outer.references) ``` ```python ReferenceManager: - ('grand_child',): ScheduleBlock(Play(Constant(duration=100, amp=amp1,... ``` Finally, you may want to call this program from another program. Here we try a different approach to define subroutine. Namely, we call a subroutine from the root program with the actual program `sched2`. ```python amp3 = Parameter(""amp3"") with pulse.build() as main: pulse.play(pulse.Constant(300, amp3), pulse.DriveChannel(0)) pulse.call(sched_outer, name=""child"") print(main.parameters) ``` ```python {Parameter(amp1), Parameter(amp2), Parameter(amp3} ``` This implicitly creates a reference named “child” within the root program and assigns `sched_outer` to it. Note that the root program is only aware of its direct references. ```python print(main.references) ``` ```python ReferenceManager: - ('child',): ScheduleBlock(ScheduleBlock(ScheduleBlock(Play(Con... ``` As you can see the main program cannot directly assign a subroutine to the “grand\_child” because this subroutine is not called within the root program, i.e. it is indirectly called by “child”. However, the returned `ReferenceManager` is a dict-like object, and you can still reach to “grand\_child” via the “child” program with the following chained dict access. ```python main.references[(""child"", )].references[(""grand_child"", )] ``` Note that [`ScheduleBlock.parameters`](#qiskit.pulse.ScheduleBlock.parameters ""qiskit.pulse.ScheduleBlock.parameters"") still collects all parameters also from the subroutine once it’s assigned. Create an empty schedule block. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of this schedule. Defaults to an autogenerated string if not provided. * **metadata** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *| None*) – Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the [`metadata`](#qiskit.pulse.ScheduleBlock.metadata ""qiskit.pulse.ScheduleBlock.metadata"") attribute. It will not be directly used in the schedule. * **alignment\_context** ([*AlignmentKind*](pulse#qiskit.pulse.transforms.AlignmentKind ""qiskit.pulse.transforms.AlignmentKind"")) – `AlignmentKind` instance that manages scheduling of instructions in this block. **Raises** [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – if metadata is not a dict. ## Attributes ### alignment\_context Return alignment instance that allocates block component to generate schedule. ### blocks Get the block elements added to self. The sequence of elements is returned in order of addition. Because the first element is schedule first, e.g. FIFO, the returned sequence is roughly time-ordered. However, in the parallel alignment context, especially in the as-late-as-possible scheduling, or [`AlignRight`](qiskit.pulse.transforms.AlignRight ""qiskit.pulse.transforms.AlignRight"") context, the actual timing of when the instructions are issued is unknown until the [`ScheduleBlock`](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") is scheduled and converted into a [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule""). ### channels Returns channels that this schedule block uses. ### duration Duration of this schedule block. ### instances\_counter ### instructions Get the time-ordered instructions from self. ### metadata The user provided metadata associated with the schedule. User provided `dict` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. ### name Return name of this schedule ### parameters Return unassigned parameters with raw names. ### prefix ### references Return a reference manager of the current scope. ## Methods ### append Return a new schedule block with `block` appended to the context block. The execution time is automatically assigned when the block is converted into schedule. **Parameters** * **block** (*BlockComponent*) – ScheduleBlock to be appended. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of the new `Schedule`. Defaults to name of `self`. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Perform operation inplace on this schedule. Otherwise, return a new `Schedule`. **Returns** Schedule block with appended schedule. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When invalid schedule type is specified. **Return type** [ScheduleBlock](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") ### assign\_parameters Assign the parameters in this schedule according to the input. **Parameters** * **value\_dict** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*qiskit.circuit.parameterexpression.ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"")*,* [*Union*](https://docs.python.org/3/library/typing.html#typing.Union ""(in Python v3.12)"")*\[*[*qiskit.circuit.parameterexpression.ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.parameterexpression.ParameterExpression"")*,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]]*) – A mapping from Parameters to either numeric values or another Parameter expression. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Set `True` to override this instance with new parameter. **Returns** Schedule with updated parameters. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When the block is nested into another block. **Return type** [*ScheduleBlock*](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"") ### assign\_references Assign schedules to references. It is only capable of assigning a schedule block to immediate references which are directly referred within the current scope. Let’s see following example: ```python from qiskit import pulse with pulse.build() as subroutine: pulse.delay(10, pulse.DriveChannel(0)) with pulse.build() as sub_prog: pulse.reference(""A"") with pulse.build() as main_prog: pulse.reference(""B"") ``` In above example, the `main_prog` can refer to the subroutine “root::B” and the reference of “B” to program “A”, i.e., “B::A”, is not defined in the root namespace. This prevents breaking the reference “root::B::A” by the assignment of “root::B”. For example, if a user could indirectly assign “root::B::A” from the root program, one can later assign another program to “root::B” that doesn’t contain “A” within it. In this situation, a reference “root::B::A” would still live in the reference manager of the root. However, the subroutine “root::B::A” would no longer be used in the actual pulse program. To assign subroutine “A” to `nested_prog` as a nested subprogram of `main_prog`, you must first assign “A” of the `sub_prog`, and then assign the `sub_prog` to the `main_prog`. ```python sub_prog.assign_references({(""A"", ): nested_prog}, inplace=True) main_prog.assign_references({(""B"", ): sub_prog}, inplace=True) ``` Alternatively, you can also write ```python main_prog.assign_references({(""B"", ): sub_prog}, inplace=True) main_prog.references[(""B"", )].assign_references({""A"": nested_prog}, inplace=True) ``` Here [`references`](#qiskit.pulse.ScheduleBlock.references ""qiskit.pulse.ScheduleBlock.references"") returns a dict-like object, and you can mutably update the nested reference of the particular subroutine. Assigned programs are deep-copied to prevent an unexpected update. **Parameters** * **subroutine\_dict** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, ...], 'ScheduleBlock']*) – A mapping from reference key to schedule block of the subroutine. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Set `True` to override this instance with new subroutine. **Returns** Schedule block with assigned subroutine. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When reference key is not defined in the current scope. **Return type** [ScheduleBlock](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") ### ch\_duration Return the time of the end of the last instruction over the supplied channels. **Parameters** **\*channels** ([*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")) – Channels within `self` to include. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### draw Plot the schedule. **Parameters** * **style** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any] | None*) – Stylesheet options. This can be dictionary or preset stylesheet classes. See `IQXStandard`, `IQXSimple`, and `IQXDebugging` for details of preset stylesheets. * **backend** (*Optional\[BaseBackend]*) – Backend object to play the input pulse program. If provided, the plotter may use to make the visualization hardware aware. * **time\_range** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None*) – Set horizontal axis limit. Tuple (tmin, tmax). * **time\_unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The unit of specified time range either dt or ns. The unit of ns is available only when backend object is provided. * **disable\_channels** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")*] | None*) – A control property to show specific pulse channel. Pulse channel instances provided as a list are not shown in the output image. * **show\_snapshot** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Show snapshot instructions. * **show\_framechange** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Show frame change instructions. The frame change represents instructions that modulate phase or frequency of pulse channels. * **show\_waveform\_info** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Show additional information about waveforms such as their name. * **show\_barrier** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Show barrier lines. * **plotter** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of plotter API to generate an output image. One of following APIs should be specified: ```python mpl2d: Matplotlib API for 2D image generation. Matplotlib API to generate 2D image. Charts are placed along y axis with vertical offset. This API takes matplotlib.axes.Axes as ``axis`` input. ``` `axis` and `style` kwargs may depend on the plotter. * **axis** (*Any | None*) – Arbitrary object passed to the plotter. If this object is provided, the plotters use a given `axis` instead of internally initializing a figure object. This object format depends on the plotter. See plotter argument for details. **Returns** Visualization output data. The returned data type depends on the `plotter`. If matplotlib family is specified, this will be a `matplotlib.pyplot.Figure` data. ### exclude Return a new `ScheduleBlock` with only the instructions from this `ScheduleBlock` *failing* at least one of the provided filters. This method is the complement of py:meth:\~self.filter, so that: ```python self.filter(args) + self.exclude(args) == self in terms of instructions included. ``` Because `ScheduleBlock` is not aware of the execution time of the context instructions, excluding some instructions may change the execution time of the remaining instructions. **Parameters** * **filter\_funcs** (*Callable\[...,* [*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*]*) – A list of Callables which take a `Instruction` and return a bool. * **channels** (*Iterable\[*[*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")*] | None*) – For example, `[DriveChannel(0), AcquireChannel(0)]`. * **instruction\_types** (*Iterable\[*[*abc.ABCMeta*](https://docs.python.org/3/library/abc.html#abc.ABCMeta ""(in Python v3.12)"")*] |* [*abc.ABCMeta*](https://docs.python.org/3/library/abc.html#abc.ABCMeta ""(in Python v3.12)"")) – For example, `[PulseInstruction, AcquireInstruction]`. * **check\_subroutine** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Set True to individually filter instructions inside of a subroutine defined by the `Call` instruction. **Returns** `ScheduleBlock` consisting of instructions that do not match with at least one of filtering conditions. ### filter Return a new `ScheduleBlock` with only the instructions from this `ScheduleBlock` which pass though the provided filters; i.e. an instruction will be retained if every function in `filter_funcs` returns `True`, the instruction occurs on a channel type contained in `channels`, and the instruction type is contained in `instruction_types`. Because `ScheduleBlock` is not aware of the execution time of the context instructions, filtering out some instructions may change the execution time of the remaining instructions. If no arguments are provided, `self` is returned. **Parameters** * **filter\_funcs** (*Callable\[...,* [*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*]*) – A list of Callables which take a `Instruction` and return a bool. * **channels** (*Iterable\[*[*Channel*](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"")*] | None*) – For example, `[DriveChannel(0), AcquireChannel(0)]`. * **instruction\_types** (*Iterable\[*[*abc.ABCMeta*](https://docs.python.org/3/library/abc.html#abc.ABCMeta ""(in Python v3.12)"")*] |* [*abc.ABCMeta*](https://docs.python.org/3/library/abc.html#abc.ABCMeta ""(in Python v3.12)"")) – For example, `[PulseInstruction, AcquireInstruction]`. * **check\_subroutine** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Set True to individually filter instructions inside a subroutine defined by the `Call` instruction. **Returns** `ScheduleBlock` consisting of instructions that matches with filtering condition. ### get\_parameters Get parameter object bound to this schedule by string name. Note that we can define different parameter objects with the same name, because these different objects are identified by their unique uuid. For example, ```python from qiskit import pulse, circuit amp1 = circuit.Parameter(""amp"") amp2 = circuit.Parameter(""amp"") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name=""sub"") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.get_parameters(""amp"") ``` This returns a list of two parameters `amp1` and `amp2`. **Parameters** **parameter\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of parameter. **Returns** Parameter objects that have corresponding name. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[qiskit.circuit.parameter.Parameter](qiskit.circuit.Parameter ""qiskit.circuit.parameter.Parameter"")] ### initialize\_from Create new schedule object with metadata of another schedule object. **Parameters** * **other\_program** (*Any*) – Qiskit program that provides metadata to new object. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of new schedule. Name of `block` is used by default. **Returns** New block object with name and metadata. **Raises** [**PulseError**](pulse#qiskit.pulse.PulseError ""qiskit.pulse.PulseError"") – When `other_program` does not provide necessary information. **Return type** [ScheduleBlock](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") ### is\_parameterized Return True iff the instruction is parameterized. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_referenced Return True iff the current schedule block contains reference to subroutine. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_schedulable Return `True` if all durations are assigned. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### replace Return a `ScheduleBlock` with the `old` component replaced with a `new` component. **Parameters** * **old** ([*ScheduleBlock*](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"") *|*[*Instruction*](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"")) – Schedule block component to replace. * **new** ([*ScheduleBlock*](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"") *|*[*Instruction*](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.instruction.Instruction"")) – Schedule block component to replace with. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Replace instruction by mutably modifying this `ScheduleBlock`. **Returns** The modified schedule block with `old` replaced by `new`. **Return type** [*ScheduleBlock*](#qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.ScheduleBlock.mdx "--- title: AlignEquispaced description: API reference for qiskit.pulse.transforms.AlignEquispaced in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.transforms.AlignEquispaced --- # AlignEquispaced Bases: [`AlignmentKind`](pulse#qiskit.pulse.transforms.AlignmentKind ""qiskit.pulse.transforms.alignments.AlignmentKind"") Align instructions with equispaced interval within a specified duration. Instructions played on different channels are also arranged in a sequence. This alignment is convenient to create dynamical decoupling sequences such as PDD. Create new equispaced context. **Parameters** **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Duration of this context. This should be larger than the schedule duration. If the specified duration is shorter than the schedule duration, no alignment is performed and the input schedule is just returned. This duration can be parametrized. ## Attributes ### duration Return context duration. ### is\_sequential ## Methods ### align Reallocate instructions according to the policy. Only top-level sub-schedules are aligned. If sub-schedules are nested, nested schedules are not recursively aligned. **Parameters** **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"")) – Schedule to align. **Returns** Schedule with reallocated instructions. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.transforms.AlignEquispaced.mdx "--- title: AlignFunc description: API reference for qiskit.pulse.transforms.AlignFunc in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.transforms.AlignFunc --- # AlignFunc Bases: [`AlignmentKind`](pulse#qiskit.pulse.transforms.AlignmentKind ""qiskit.pulse.transforms.alignments.AlignmentKind"") Allocate instructions at position specified by callback function. The position is specified for each instruction of index `j` as a fractional coordinate in \[0, 1] within the specified duration. Instructions played on different channels are also arranged in a sequence. This alignment is convenient to create dynamical decoupling sequences such as UDD. For example, UDD sequence with 10 pulses can be specified with following function. ```python def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 ``` This context cannot be QPY serialized because of the callable. If you use this context, your program cannot be saved in QPY format. Create new equispaced context. **Parameters** * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – Duration of this context. This should be larger than the schedule duration. If the specified duration is shorter than the schedule duration, no alignment is performed and the input schedule is just returned. This duration can be parametrized. * **func** (*Callable*) – A function that takes an index of sub-schedule and returns the fractional coordinate of of that sub-schedule. The returned value should be defined within \[0, 1]. The pulse index starts from 1. ## Attributes ### duration Return context duration. ### func Return context alignment function. ### is\_sequential ## Methods ### align Reallocate instructions according to the policy. Only top-level sub-schedules are aligned. If sub-schedules are nested, nested schedules are not recursively aligned. **Parameters** **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"")) – Schedule to align. **Returns** Schedule with reallocated instructions. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.transforms.AlignFunc.mdx "--- title: AlignLeft description: API reference for qiskit.pulse.transforms.AlignLeft in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.transforms.AlignLeft --- # AlignLeft Bases: [`AlignmentKind`](pulse#qiskit.pulse.transforms.AlignmentKind ""qiskit.pulse.transforms.alignments.AlignmentKind"") Align instructions in as-soon-as-possible manner. Instructions are placed at earliest available timeslots. Create new left-justified context. ## Attributes ### is\_sequential ## Methods ### align Reallocate instructions according to the policy. Only top-level sub-schedules are aligned. If sub-schedules are nested, nested schedules are not recursively aligned. **Parameters** **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"")) – Schedule to align. **Returns** Schedule with reallocated instructions. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.transforms.AlignLeft.mdx "--- title: AlignRight description: API reference for qiskit.pulse.transforms.AlignRight in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.transforms.AlignRight --- # AlignRight Bases: [`AlignmentKind`](pulse#qiskit.pulse.transforms.AlignmentKind ""qiskit.pulse.transforms.alignments.AlignmentKind"") Align instructions in as-late-as-possible manner. Instructions are placed at latest available timeslots. Create new right-justified context. ## Attributes ### is\_sequential ## Methods ### align Reallocate instructions according to the policy. Only top-level sub-schedules are aligned. If sub-schedules are nested, nested schedules are not recursively aligned. **Parameters** **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"")) – Schedule to align. **Returns** Schedule with reallocated instructions. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.transforms.AlignRight.mdx "--- title: AlignSequential description: API reference for qiskit.pulse.transforms.AlignSequential in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.pulse.transforms.AlignSequential --- # AlignSequential Bases: [`AlignmentKind`](pulse#qiskit.pulse.transforms.AlignmentKind ""qiskit.pulse.transforms.alignments.AlignmentKind"") Align instructions sequentially. Instructions played on different channels are also arranged in a sequence. No buffer time is inserted in between instructions. Create new sequential context. ## Attributes ### is\_sequential ## Methods ### align Reallocate instructions according to the policy. Only top-level sub-schedules are aligned. If sub-schedules are nested, nested schedules are not recursively aligned. **Parameters** **schedule** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"")) – Schedule to align. **Returns** Schedule with reallocated instructions. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") ",repo/docs/api/qiskit/1.0\qiskit.pulse.transforms.AlignSequential.mdx "--- title: GateCalibration description: API reference for qiskit.qobj.GateCalibration in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.GateCalibration --- # GateCalibration Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Each calibration specifies a unique gate by name, qubits and params, and contains the Pulse instructions to implement it. Initialize a single gate calibration. Instructions may reference waveforms which should be made available in the pulse\_library. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Gate name. * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*(*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*)*) – Qubits the gate applies to. * **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*(*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*)*) – Gate parameter values, if any. * **instructions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*(*[*PulseQobjInstruction*](qiskit.qobj.PulseQobjInstruction ""qiskit.qobj.PulseQobjInstruction"")*)*) – The gate implementation. ## Methods ### from\_dict Create a new GateCalibration object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the GateCalibration to create. It will be in the same format as output by [`to_dict()`](#qiskit.qobj.GateCalibration.to_dict ""qiskit.qobj.GateCalibration.to_dict""). **Returns** The GateCalibration from the input dictionary. **Return type** [GateCalibration](#qiskit.qobj.GateCalibration ""qiskit.qobj.GateCalibration"") ### to\_dict Return a dictionary format representation of the Gate Calibration. **Returns** The dictionary form of the GateCalibration. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.GateCalibration.mdx "--- title: PulseLibraryItem description: API reference for qiskit.qobj.PulseLibraryItem in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.PulseLibraryItem --- # PulseLibraryItem Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") An item in a pulse library. Instantiate a pulse library item. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A name for the pulse. * **samples** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*]*) – A list of complex values defining pulse shape. ## Methods ### from\_dict Create a new PulseLibraryItem object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary for the experiment config **Returns** The object from the input dictionary. **Return type** [PulseLibraryItem](#qiskit.qobj.PulseLibraryItem ""qiskit.qobj.PulseLibraryItem"") ### to\_dict Return a dictionary format representation of the pulse library item. **Returns** The dictionary form of the PulseLibraryItem. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.PulseLibraryItem.mdx "--- title: PulseQobj description: API reference for qiskit.qobj.PulseQobj in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.PulseQobj --- # PulseQobj Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A Pulse Qobj. Instantiate a new Pulse Qobj Object. Each Pulse Qobj object is used to represent a single payload that will be passed to a Qiskit provider. It mirrors the Qobj the published [Qobj specification](https://arxiv.org/abs/1809.03452) for Pulse experiments. **Parameters** * **qobj\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – An identifier for the qobj * **config** ([*PulseQobjConfig*](qiskit.qobj.PulseQobjConfig ""qiskit.qobj.PulseQobjConfig"")) – A config for the entire run * **header** ([*QobjHeader*](qiskit.qobj.QobjHeader ""qiskit.qobj.QobjHeader"")) – A header for the entire run * **experiments** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of lists of [`PulseQobjExperiment`](qiskit.qobj.PulseQobjExperiment ""qiskit.qobj.PulseQobjExperiment"") objects representing an experiment ## Methods ### from\_dict Create a new PulseQobj object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the PulseQobj to create. It will be in the same format as output by [`to_dict()`](#qiskit.qobj.PulseQobj.to_dict ""qiskit.qobj.PulseQobj.to_dict""). **Returns** The PulseQobj from the input dictionary. **Return type** [PulseQobj](#qiskit.qobj.PulseQobj ""qiskit.qobj.PulseQobj"") ### to\_dict Return a dictionary format representation of the Pulse Qobj. Note this dict is not in the json wire format expected by IBMQ and qobj specification because complex numbers are still of type complex. Also this may contain native numpy arrays. When serializing this output for use with IBMQ you can leverage a json encoder that converts these as expected. For example: ```python import json import numpy class QobjEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, numpy.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) json.dumps(qobj.to_dict(), cls=QobjEncoder) ``` **Returns** A dictionary representation of the PulseQobj object **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.PulseQobj.mdx "--- title: PulseQobjConfig description: API reference for qiskit.qobj.PulseQobjConfig in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.PulseQobjConfig --- # PulseQobjConfig Bases: `QobjDictField` A configuration for a Pulse Qobj. Instantiate a PulseQobjConfig object. **Parameters** * **meas\_level** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The measurement level to use. * **meas\_return** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The level of measurement information to return. * **pulse\_library** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of [`PulseLibraryItem`](qiskit.qobj.PulseLibraryItem ""qiskit.qobj.PulseLibraryItem"") objects which define the set of primitive pulses * **qubit\_lo\_freq** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of frequencies (as floats) for the qubit driver LO’s in GHz. * **meas\_lo\_freq** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of frequencies (as floats) for the’ measurement driver LO’s in GHz. * **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 sec. Must be from the list provided by the backend (`backend.configuration().rep_times`). Defaults to the first entry in `backend.configuration().rep_times`. * **rep\_delay** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Delay between programs in sec. Only supported on certain backends (`backend.configuration().dynamic_reprate_enabled` ). 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 `backend.configuration().default_rep_delay`. * **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\_slots** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The number of memory slots on the device * **kwargs** – Additional free form key value fields to add to the configuration ## Methods ### from\_dict Create a new PulseQobjConfig object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary for the config **Returns** The object from the input dictionary. **Return type** [PulseQobjConfig](#qiskit.qobj.PulseQobjConfig ""qiskit.qobj.PulseQobjConfig"") ### to\_dict Return a dictionary format representation of the Pulse Qobj config. **Returns** The dictionary form of the PulseQobjConfig. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.PulseQobjConfig.mdx "--- title: PulseQobjExperiment description: API reference for qiskit.qobj.PulseQobjExperiment in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.PulseQobjExperiment --- # PulseQobjExperiment Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A Pulse Qobj Experiment. Each instance of this class is used to represent an individual Pulse experiment as part of a larger Pulse Qobj. Instantiate a PulseQobjExperiment. **Parameters** * **config** ([*PulseQobjExperimentConfig*](qiskit.qobj.PulseQobjExperimentConfig ""qiskit.qobj.PulseQobjExperimentConfig"")) – A config object for the experiment * **header** (*PulseQobjExperimentHeader*) – A header object for the experiment * **instructions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of [`PulseQobjInstruction`](qiskit.qobj.PulseQobjInstruction ""qiskit.qobj.PulseQobjInstruction"") objects ## Methods ### from\_dict Create a new PulseQobjExperiment object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary for the experiment config **Returns** The object from the input dictionary. **Return type** [PulseQobjExperiment](#qiskit.qobj.PulseQobjExperiment ""qiskit.qobj.PulseQobjExperiment"") ### to\_dict Return a dictionary format representation of the Experiment. **Returns** The dictionary form of the PulseQobjExperiment. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.PulseQobjExperiment.mdx "--- title: PulseQobjExperimentConfig description: API reference for qiskit.qobj.PulseQobjExperimentConfig in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.PulseQobjExperimentConfig --- # PulseQobjExperimentConfig Bases: `QobjDictField` A config for a single Pulse experiment in the qobj. Instantiate a PulseQobjExperimentConfig object. **Parameters** * **qubit\_lo\_freq** (*List\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – List of qubit LO frequencies in GHz. * **meas\_lo\_freq** (*List\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – List of meas readout LO frequencies in GHz. * **kwargs** – Additional free form key value fields to add to the configuration ## Methods ### from\_dict Create a new QobjHeader object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the QobjHeader to create. It will be in the same format as output by [`to_dict()`](#qiskit.qobj.PulseQobjExperimentConfig.to_dict ""qiskit.qobj.PulseQobjExperimentConfig.to_dict""). **Returns** The QobjDictField from the input dictionary. **Return type** QobjDictFieldr ### to\_dict Return a dictionary format representation of the OpenQASM 2 Qobj. **Returns** The dictionary form of the QobjHeader. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.PulseQobjExperimentConfig.mdx "--- title: PulseQobjInstruction description: API reference for qiskit.qobj.PulseQobjInstruction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.PulseQobjInstruction --- # PulseQobjInstruction Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A class representing a single instruction in an PulseQobj Experiment. Instantiate a new PulseQobjInstruction object. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the instruction * **t0** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Pulse start time in integer **dt** units. * **ch** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The channel to apply the pulse instruction. * **conditional** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The register to use for a conditional for this instruction * **val** ([*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")) – Complex value to apply, bounded by an absolute value of 1. * **phase** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – if a `fc` instruction, the frame change phase in radians. * **frequency** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – if a `sf` instruction, the frequency in Hz. * **duration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The duration of the pulse in **dt** units. * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of `int` representing the qubits the instruction operates on * **memory\_slot** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – If a `measure` instruction this is a list of `int` containing the list of memory slots to store the measurement results in (must be the same length as qubits). If a `bfunc` instruction this is a single `int` of the memory slot to store the boolean function result in. * **register\_slot** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – If a `measure` instruction this is a list of `int` containing the list of register slots in which to store the measurement results (must be the same length as qubits). If a `bfunc` instruction this is a single `int` of the register slot in which to store the result. * **kernels** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of [`QobjMeasurementOption`](qiskit.qobj.QobjMeasurementOption ""qiskit.qobj.QobjMeasurementOption"") objects defining the measurement kernels and set of parameters if the measurement level is 1 or 2. Only used for `acquire` instructions. * **discriminators** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of [`QobjMeasurementOption`](qiskit.qobj.QobjMeasurementOption ""qiskit.qobj.QobjMeasurementOption"") used to set the discriminators to be used if the measurement level is 2. Only used for `acquire` instructions. * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Label of instruction * **type** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Type of instruction * **pulse\_shape** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The shape of the parametric pulse * **parameters** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – The parameters for a parametric pulse ## Methods ### from\_dict Create a new PulseQobjExperimentConfig object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary for the experiment config **Returns** The object from the input dictionary. **Return type** [PulseQobjInstruction](#qiskit.qobj.PulseQobjInstruction ""qiskit.qobj.PulseQobjInstruction"") ### to\_dict Return a dictionary format representation of the Instruction. **Returns** The dictionary form of the PulseQobjInstruction. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.PulseQobjInstruction.mdx "--- title: QasmExperimentCalibrations description: API reference for qiskit.qobj.QasmExperimentCalibrations in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.QasmExperimentCalibrations --- # QasmExperimentCalibrations Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A container for any calibrations data. The gates attribute contains a list of GateCalibrations. Initialize a container for calibrations. **Parameters** **gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*(*[*GateCalibration*](qiskit.qobj.GateCalibration ""qiskit.qobj.GateCalibration"")*)*) – ## Methods ### from\_dict Create a new GateCalibration object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the QasmExperimentCalibrations to create. It will be in the same format as output by [`to_dict()`](#qiskit.qobj.QasmExperimentCalibrations.to_dict ""qiskit.qobj.QasmExperimentCalibrations.to_dict""). **Returns** The QasmExperimentCalibrations from the input dictionary. **Return type** [QasmExperimentCalibrations](#qiskit.qobj.QasmExperimentCalibrations ""qiskit.qobj.QasmExperimentCalibrations"") ### to\_dict Return a dictionary format representation of the calibrations. **Returns** The dictionary form of the GateCalibration. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.QasmExperimentCalibrations.mdx "--- title: QasmQobj description: API reference for qiskit.qobj.QasmQobj in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.QasmQobj --- # QasmQobj Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") An OpenQASM 2 Qobj. Instantiate a new OpenQASM 2 Qobj Object. Each OpenQASM 2 Qobj object is used to represent a single payload that will be passed to a Qiskit provider. It mirrors the Qobj the published [Qobj specification](https://arxiv.org/abs/1809.03452) for OpenQASM experiments. **Parameters** * **qobj\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – An identifier for the qobj * **config** (*QasmQobjRunConfig*) – A config for the entire run * **header** ([*QobjHeader*](qiskit.qobj.QobjHeader ""qiskit.qobj.QobjHeader"")) – A header for the entire run * **experiments** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of lists of [`QasmQobjExperiment`](qiskit.qobj.QasmQobjExperiment ""qiskit.qobj.QasmQobjExperiment"") objects representing an experiment ## Methods ### from\_dict Create a new QASMQobj object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the QasmQobj to create. It will be in the same format as output by [`to_dict()`](#qiskit.qobj.QasmQobj.to_dict ""qiskit.qobj.QasmQobj.to_dict""). **Returns** The QasmQobj from the input dictionary. **Return type** [QasmQobj](#qiskit.qobj.QasmQobj ""qiskit.qobj.QasmQobj"") ### to\_dict Return a dictionary format representation of the OpenQASM 2 Qobj. Note this dict is not in the json wire format expected by IBM and Qobj specification because complex numbers are still of type complex. Also, this may contain native numpy arrays. When serializing this output for use with IBM systems, you can leverage a json encoder that converts these as expected. For example: ```python import json import numpy class QobjEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, numpy.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) json.dumps(qobj.to_dict(), cls=QobjEncoder) ``` **Returns** A dictionary representation of the QasmQobj object **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.QasmQobj.mdx "--- title: QasmQobjConfig description: API reference for qiskit.qobj.QasmQobjConfig in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.QasmQobjConfig --- # QasmQobjConfig Bases: [`SimpleNamespace`](https://docs.python.org/3/library/types.html#types.SimpleNamespace ""(in Python v3.12)"") A configuration for an OpenQASM 2 Qobj. Model for RunConfig. **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 * **meas\_level** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Measurement level 0, 1, or 2 * **meas\_return** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – For measurement level \< 2, whether single or avg shots are returned * **memory\_slots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of memory slots on the device * **n\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits on the device * **pulse\_library** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of [`PulseLibraryItem`](qiskit.qobj.PulseLibraryItem ""qiskit.qobj.PulseLibraryItem""). * **calibrations** ([*QasmExperimentCalibrations*](qiskit.qobj.QasmExperimentCalibrations ""qiskit.qobj.QasmExperimentCalibrations"")) – Information required for Pulse gates. * **rep\_delay** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Delay between programs in sec. Only supported on certain backends (`backend.configuration().dynamic_reprate_enabled` ). Must be from the range supplied by the backend (`backend.configuration().rep_delay_range`). Default is `backend.configuration().default_rep_delay`. * **qubit\_lo\_freq** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of frequencies (as floats) for the qubit driver LO’s in GHz. * **meas\_lo\_freq** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of frequencies (as floats) for the measurement driver LO’s in GHz. * **kwargs** – Additional free form key value fields to add to the configuration. ## Methods ### from\_dict Create a new QasmQobjConfig object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary for the config **Returns** The object from the input dictionary. **Return type** [QasmQobjConfig](#qiskit.qobj.QasmQobjConfig ""qiskit.qobj.QasmQobjConfig"") ### to\_dict Return a dictionary format representation of the OpenQASM 2 Qobj config. **Returns** The dictionary form of the QasmQobjConfig. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.QasmQobjConfig.mdx "--- title: QasmQobjExperiment description: API reference for qiskit.qobj.QasmQobjExperiment in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.QasmQobjExperiment --- # QasmQobjExperiment Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") An OpenQASM 2 Qobj Experiment. Each instance of this class is used to represent an OpenQASM 2 experiment as part of a larger OpenQASM 2 qobj. Instantiate a QasmQobjExperiment. **Parameters** * **config** ([*QasmQobjExperimentConfig*](qiskit.qobj.QasmQobjExperimentConfig ""qiskit.qobj.QasmQobjExperimentConfig"")) – A config object for the experiment * **header** (*QasmQobjExperimentHeader*) – A header object for the experiment * **instructions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of [`QasmQobjInstruction`](qiskit.qobj.QasmQobjInstruction ""qiskit.qobj.QasmQobjInstruction"") objects ## Methods ### from\_dict Create a new QasmQobjExperiment object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary for the experiment config **Returns** The object from the input dictionary. **Return type** [QasmQobjExperiment](#qiskit.qobj.QasmQobjExperiment ""qiskit.qobj.QasmQobjExperiment"") ### to\_dict Return a dictionary format representation of the Experiment. **Returns** The dictionary form of the QasmQObjExperiment. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.QasmQobjExperiment.mdx "--- title: QasmQobjExperimentConfig description: API reference for qiskit.qobj.QasmQobjExperimentConfig in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.QasmQobjExperimentConfig --- # QasmQobjExperimentConfig Bases: `QobjDictField` Configuration for a single OpenQASM 2 experiment in the qobj. **Parameters** * **calibrations** ([*QasmExperimentCalibrations*](qiskit.qobj.QasmExperimentCalibrations ""qiskit.qobj.QasmExperimentCalibrations"")) – Information required for Pulse gates. * **qubit\_lo\_freq** (*List\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – List of qubit LO frequencies in GHz. * **meas\_lo\_freq** (*List\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – List of meas readout LO frequencies in GHz. * **kwargs** – Additional free form key value fields to add to the configuration ## Methods ### from\_dict Create a new QobjHeader object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the QobjHeader to create. It will be in the same format as output by [`to_dict()`](#qiskit.qobj.QasmQobjExperimentConfig.to_dict ""qiskit.qobj.QasmQobjExperimentConfig.to_dict""). **Returns** The QobjDictField from the input dictionary. **Return type** QobjDictFieldr ### to\_dict Return a dictionary format representation of the OpenQASM 2 Qobj. **Returns** The dictionary form of the QobjHeader. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.QasmQobjExperimentConfig.mdx "--- title: QasmQobjInstruction description: API reference for qiskit.qobj.QasmQobjInstruction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.QasmQobjInstruction --- # QasmQobjInstruction Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A class representing a single instruction in an QasmQobj Experiment. Instantiate a new QasmQobjInstruction object. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the instruction * **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The list of parameters for the gate * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of `int` representing the qubits the instruction operates on * **register** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – If a `measure` instruction this is a list of `int` containing the list of register slots in which to store the measurement results (must be the same length as qubits). If a `bfunc` instruction this is a single `int` of the register slot in which to store the result. * **memory** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – If a `measure` instruction this is a list of `int` containing the list of memory slots to store the measurement results in (must be the same length as qubits). If a `bfunc` instruction this is a single `int` of the memory slot to store the boolean function result in. * **condition** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – A tuple of the form `(int, int)` where the first `int` is the control register and the second `int` is the control value if the gate has a condition. * **conditional** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The register index of the condition * **label** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – An optional label assigned to the instruction * **mask** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – For a `bfunc` instruction the hex value which is applied as an `AND` to the register bits. * **relation** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Relational operator for comparing the masked register to the `val` kwarg. Can be either `==` (equals) or `!=` (not equals). * **val** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Value to which to compare the masked register. In other words, the output of the function is `(register AND mask)` * **snapshot\_type** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – For snapshot instructions the type of snapshot to use ## Methods ### from\_dict Create a new QasmQobjInstruction object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary for the experiment config **Returns** The object from the input dictionary. **Return type** [QasmQobjInstruction](#qiskit.qobj.QasmQobjInstruction ""qiskit.qobj.QasmQobjInstruction"") ### to\_dict Return a dictionary format representation of the Instruction. **Returns** The dictionary form of the QasmQobjInstruction. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.QasmQobjInstruction.mdx "--- title: QobjExperimentHeader description: API reference for qiskit.qobj.QobjExperimentHeader in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.QobjExperimentHeader --- # QobjExperimentHeader Bases: [`QobjHeader`](qiskit.qobj.QobjHeader ""qiskit.qobj.common.QobjHeader"") A class representing a header dictionary for a Qobj Experiment. Instantiate a new Qobj dict field object. **Parameters** **kwargs** – arbitrary keyword arguments that can be accessed as attributes of the object. ## Methods ### from\_dict Create a new QobjHeader object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the QobjHeader to create. It will be in the same format as output by [`to_dict()`](#qiskit.qobj.QobjExperimentHeader.to_dict ""qiskit.qobj.QobjExperimentHeader.to_dict""). **Returns** The QobjDictField from the input dictionary. **Return type** QobjDictFieldr ### to\_dict Return a dictionary format representation of the OpenQASM 2 Qobj. **Returns** The dictionary form of the QobjHeader. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.QobjExperimentHeader.mdx "--- title: QobjHeader description: API reference for qiskit.qobj.QobjHeader in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.QobjHeader --- # QobjHeader Bases: `QobjDictField` A class used to represent a dictionary header in Qobj objects. Instantiate a new Qobj dict field object. **Parameters** **kwargs** – arbitrary keyword arguments that can be accessed as attributes of the object. ## Methods ### from\_dict Create a new QobjHeader object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the QobjHeader to create. It will be in the same format as output by [`to_dict()`](#qiskit.qobj.QobjHeader.to_dict ""qiskit.qobj.QobjHeader.to_dict""). **Returns** The QobjDictField from the input dictionary. **Return type** QobjDictFieldr ### to\_dict Return a dictionary format representation of the OpenQASM 2 Qobj. **Returns** The dictionary form of the QobjHeader. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.QobjHeader.mdx "--- title: QobjMeasurementOption description: API reference for qiskit.qobj.QobjMeasurementOption in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.qobj.QobjMeasurementOption --- # QobjMeasurementOption Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") An individual measurement option. Instantiate a new QobjMeasurementOption object. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the measurement option * **params** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The parameters of the measurement option. ## Methods ### from\_dict Create a new QobjMeasurementOption object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary for the experiment config **Returns** The object from the input dictionary. **Return type** [QobjMeasurementOption](#qiskit.qobj.QobjMeasurementOption ""qiskit.qobj.QobjMeasurementOption"") ### to\_dict Return a dict format representation of the QobjMeasurementOption. **Returns** The dictionary form of the QasmMeasurementOption. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.qobj.QobjMeasurementOption.mdx "--- title: Chi description: API reference for qiskit.quantum_info.Chi in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.Chi --- # Chi Bases: `QuantumChannel` Pauli basis Chi-matrix representation of a quantum channel. The Chi-matrix representation of an $n$-qubit quantum channel $\mathcal{E}$ is a matrix $\chi$ such that the evolution of a [`DensityMatrix`](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") $\rho$ is given by $$ \mathcal{E}(ρ) = \frac{1}{2^n} \sum_{i, j} \chi_{i,j} P_i ρ P_j $$ where $[P_0, P_1, ..., P_{4^{n}-1}]$ is the $n$-qubit Pauli basis in lexicographic order. It is related to the [`Choi`](qiskit.quantum_info.Choi ""qiskit.quantum_info.Choi"") representation by a change of basis of the Choi-matrix into the Pauli basis. The $\frac{1}{2^n}$ in the definition above is a normalization factor that arises from scaling the Pauli basis to make it orthonormal. See reference \[1] for further details. **References** 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). [arXiv:1111.6950 \[quant-ph\]](https://arxiv.org/abs/1111.6950) Initialize a quantum channel Chi-matrix operator. **Parameters** * **or** (*data (*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – Instruction or BaseOperator or matrix): data to initialize superoperator. * **input\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the input subsystem dimensions. \[Default: None] * **output\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the output subsystem dimensions. \[Default: None] **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data is not an N-qubit channel or cannot be initialized as a Chi-matrix. **Additional Information:** If the input or output dimensions are None, they will be automatically determined from the input data. The Chi matrix representation is only valid for N-qubit channels. ## Attributes ### atol ### data Return data. ### dim Return tuple (input\_shape, output\_shape). ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### qargs Return the qargs for the operator. ### rtol ### settings Return settings. ## Methods ### adjoint Return the adjoint quantum channel. This is equivalent to the matrix Hermitian conjugate in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the adjoint channel $\mathcal{{E}}^\dagger$ is $S_{\mathcal{E}^\dagger} = S_{\mathcal{E}}^\dagger$. ### compose Return the operator composition with another Chi. **Parameters** * **other** ([*Chi*](#qiskit.quantum_info.Chi ""qiskit.quantum_info.Chi"")) – a Chi object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. **Returns** The composed Chi. **Return type** [Chi](#qiskit.quantum_info.Chi ""qiskit.quantum_info.Chi"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while `@` (equivalent to [`dot()`](#qiskit.quantum_info.Chi.dot ""qiskit.quantum_info.Chi.dot"")) is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B @ A == B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.Chi.dot ""qiskit.quantum_info.Chi.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate quantum channel. This is equivalent to the matrix complex conjugate in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the conjugate channel $\overline{{\mathcal{{E}}}}$ is $S_{\overline{\mathcal{E}^\dagger}} = \overline{S_{\mathcal{E}}}$. ### copy Make a deep copy of current operator. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). **Returns** The right matrix multiplied Operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The dot product can be obtained using the `@` binary operator. Hence `a.dot(b)` is equivalent to `a @ b`. ### expand Return the reverse-order tensor product with another Chi. **Parameters** **other** ([*Chi*](#qiskit.quantum_info.Chi ""qiskit.quantum_info.Chi"")) – a Chi object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current Chi, and $b$ is the other Chi. **Return type** [Chi](#qiskit.quantum_info.Chi ""qiskit.quantum_info.Chi"") ### input\_dims Return tuple of input dimension for specified subsystems. ### is\_cp Test if Choi-matrix is completely-positive (CP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_cptp Return True if completely-positive trace-preserving (CPTP). **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_tp Test if a channel is trace-preserving (TP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_unitary Return True if QuantumChannel is a unitary channel. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the power of the quantum channel. **Parameters** **n** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – the power exponent. **Returns** the channel $\mathcal{{E}} ^n$. **Return type** [SuperOp](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the SuperOp are not equal. For non-positive or non-integer exponents the power is defined as the matrix power of the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{{E}}$, the SuperOp of the powered channel $\mathcal{{E}}^\n$ is $S_{{\mathcal{{E}}^n}} = S_{{\mathcal{{E}}}}^n$. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### tensor Return the tensor product with another Chi. **Parameters** **other** ([*Chi*](#qiskit.quantum_info.Chi ""qiskit.quantum_info.Chi"")) – a Chi object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current Chi, and $b$ is the other Chi. **Return type** [Chi](#qiskit.quantum_info.Chi ""qiskit.quantum_info.Chi"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_instruction Convert to a Kraus or UnitaryGate circuit instruction. If the channel is unitary it will be added as a unitary gate, otherwise it will be added as a kraus simulator instruction. **Returns** A kraus instruction for the channel. **Return type** [qiskit.circuit.Instruction](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data is not an N-qubit CPTP quantum channel. ### to\_operator Try to convert channel to a unitary representation Operator. **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### transpose Return the transpose quantum channel. This is equivalent to the matrix transpose in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation, ie. for a channel $\mathcal{E}$, the SuperOp of the transpose channel $\mathcal{{E}}^T$ is $S_{mathcal{E}^T} = S_{\mathcal{E}}^T$. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.Chi.mdx "--- title: Choi description: API reference for qiskit.quantum_info.Choi in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.Choi --- # Choi Bases: `QuantumChannel` Choi-matrix representation of a Quantum Channel. The Choi-matrix representation of a quantum channel $\mathcal{E}$ is a matrix $$ \Lambda = \sum_{i,j} |i\rangle\!\langle j|\otimes \mathcal{E}\left(|i\rangle\!\langle j|\right) $$ Evolution of a [`DensityMatrix`](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") $\rho$ with respect to the Choi-matrix is given by $$ \mathcal{E}(\rho) = \mbox{Tr}_{1}\left[\Lambda (\rho^T \otimes \mathbb{I})\right] $$ where $\mbox{Tr}_1$ is the [`partial_trace()`](quantum_info#qiskit.quantum_info.partial_trace ""qiskit.quantum_info.partial_trace"") over subsystem 1. See reference \[1] for further details. **References** 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). [arXiv:1111.6950 \[quant-ph\]](https://arxiv.org/abs/1111.6950) Initialize a quantum channel Choi matrix operator. **Parameters** * **or** (*data (*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – Instruction or BaseOperator or matrix): data to initialize superoperator. * **input\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the input subsystem dimensions. \[Default: None] * **output\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the output subsystem dimensions. \[Default: None] **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data cannot be initialized as a Choi matrix. **Additional Information:** If the input or output dimensions are None, they will be automatically determined from the input data. If the input data is a Numpy array of shape (4\*\*N, 4\*\*N) qubit systems will be used. If the input operator is not an N-qubit operator, it will assign a single subsystem with dimension specified by the shape of the input. ## Attributes ### atol ### data Return data. ### dim Return tuple (input\_shape, output\_shape). ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### qargs Return the qargs for the operator. ### rtol ### settings Return settings. ## Methods ### adjoint Return the adjoint quantum channel. This is equivalent to the matrix Hermitian conjugate in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the adjoint channel $\mathcal{{E}}^\dagger$ is $S_{\mathcal{E}^\dagger} = S_{\mathcal{E}}^\dagger$. **Return type** *Self* ### compose Return the operator composition with another Choi. **Parameters** * **other** ([*Choi*](#qiskit.quantum_info.Choi ""qiskit.quantum_info.Choi"")) – a Choi object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. **Returns** The composed Choi. **Return type** [Choi](#qiskit.quantum_info.Choi ""qiskit.quantum_info.Choi"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while `@` (equivalent to [`dot()`](#qiskit.quantum_info.Choi.dot ""qiskit.quantum_info.Choi.dot"")) is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B @ A == B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.Choi.dot ""qiskit.quantum_info.Choi.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate quantum channel. This is equivalent to the matrix complex conjugate in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the conjugate channel $\overline{{\mathcal{{E}}}}$ is $S_{\overline{\mathcal{E}^\dagger}} = \overline{S_{\mathcal{E}}}$. ### copy Make a deep copy of current operator. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). **Returns** The right matrix multiplied Operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The dot product can be obtained using the `@` binary operator. Hence `a.dot(b)` is equivalent to `a @ b`. ### expand Return the reverse-order tensor product with another Choi. **Parameters** **other** ([*Choi*](#qiskit.quantum_info.Choi ""qiskit.quantum_info.Choi"")) – a Choi object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current Choi, and $b$ is the other Choi. **Return type** [Choi](#qiskit.quantum_info.Choi ""qiskit.quantum_info.Choi"") ### input\_dims Return tuple of input dimension for specified subsystems. ### is\_cp Test if Choi-matrix is completely-positive (CP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_cptp Return True if completely-positive trace-preserving (CPTP). **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_tp Test if a channel is trace-preserving (TP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_unitary Return True if QuantumChannel is a unitary channel. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the power of the quantum channel. **Parameters** **n** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – the power exponent. **Returns** the channel $\mathcal{{E}} ^n$. **Return type** [SuperOp](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the SuperOp are not equal. For non-positive or non-integer exponents the power is defined as the matrix power of the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{{E}}$, the SuperOp of the powered channel $\mathcal{{E}}^\n$ is $S_{{\mathcal{{E}}^n}} = S_{{\mathcal{{E}}}}^n$. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### tensor Return the tensor product with another Choi. **Parameters** **other** ([*Choi*](#qiskit.quantum_info.Choi ""qiskit.quantum_info.Choi"")) – a Choi object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current Choi, and $b$ is the other Choi. **Return type** [Choi](#qiskit.quantum_info.Choi ""qiskit.quantum_info.Choi"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_instruction Convert to a Kraus or UnitaryGate circuit instruction. If the channel is unitary it will be added as a unitary gate, otherwise it will be added as a kraus simulator instruction. **Returns** A kraus instruction for the channel. **Return type** [qiskit.circuit.Instruction](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data is not an N-qubit CPTP quantum channel. ### to\_operator Try to convert channel to a unitary representation Operator. **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### transpose Return the transpose quantum channel. This is equivalent to the matrix transpose in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation, ie. for a channel $\mathcal{E}$, the SuperOp of the transpose channel $\mathcal{{E}}^T$ is $S_{mathcal{E}^T} = S_{\mathcal{E}}^T$. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.Choi.mdx "--- title: Clifford description: API reference for qiskit.quantum_info.Clifford in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.Clifford --- # Clifford Bases: `BaseOperator`, `AdjointMixin`, [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.operation.Operation"") An N-qubit unitary operator from the Clifford group. **Representation** An *N*-qubit Clifford operator is stored as a length *2N × (2N+1)* boolean tableau using the convention from reference \[1]. * Rows 0 to *N-1* are the *destabilizer* group generators * Rows *N* to *2N-1* are the *stabilizer* group generators. The internal boolean tableau for the Clifford can be accessed using the `tableau` attribute. The destabilizer or stabilizer rows can each be accessed as a length-N Stabilizer table using [`destab`](#qiskit.quantum_info.Clifford.destab ""qiskit.quantum_info.Clifford.destab"") and [`stab`](#qiskit.quantum_info.Clifford.stab ""qiskit.quantum_info.Clifford.stab"") attributes. A more easily human readable representation of the Clifford operator can be obtained by calling the [`to_dict()`](#qiskit.quantum_info.Clifford.to_dict ""qiskit.quantum_info.Clifford.to_dict"") method. This representation is also used if a Clifford object is printed as in the following example ```python from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford # Bell state generation circuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) cliff = Clifford(qc) # Print the Clifford print(cliff) # Print the Clifford destabilizer rows print(cliff.to_labels(mode=""D"")) # Print the Clifford stabilizer rows print(cliff.to_labels(mode=""S"")) ``` ```python Clifford: Stabilizer = ['+XX', '+ZZ'], Destabilizer = ['+IZ', '+XI'] ['+IZ', '+XI'] ['+XX', '+ZZ'] ``` **Circuit Conversion** Clifford operators can be initialized from circuits containing *only* the following Clifford gates: [`IGate`](qiskit.circuit.library.IGate ""qiskit.circuit.library.IGate""), [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate""), [`YGate`](qiskit.circuit.library.YGate ""qiskit.circuit.library.YGate""), [`ZGate`](qiskit.circuit.library.ZGate ""qiskit.circuit.library.ZGate""), [`HGate`](qiskit.circuit.library.HGate ""qiskit.circuit.library.HGate""), [`SGate`](qiskit.circuit.library.SGate ""qiskit.circuit.library.SGate""), [`SdgGate`](qiskit.circuit.library.SdgGate ""qiskit.circuit.library.SdgGate""), [`SXGate`](qiskit.circuit.library.SXGate ""qiskit.circuit.library.SXGate""), [`SXdgGate`](qiskit.circuit.library.SXdgGate ""qiskit.circuit.library.SXdgGate""), [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate""), [`CZGate`](qiskit.circuit.library.CZGate ""qiskit.circuit.library.CZGate""), [`CYGate`](qiskit.circuit.library.CYGate ""qiskit.circuit.library.CYGate""), `DXGate`, [`SwapGate`](qiskit.circuit.library.SwapGate ""qiskit.circuit.library.SwapGate""), [`iSwapGate`](qiskit.circuit.library.iSwapGate ""qiskit.circuit.library.iSwapGate""), [`ECRGate`](qiskit.circuit.library.ECRGate ""qiskit.circuit.library.ECRGate""), [`LinearFunction`](qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.LinearFunction""), [`PermutationGate`](qiskit.circuit.library.PermutationGate ""qiskit.circuit.library.PermutationGate""). They can be converted back into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""), or [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") object using the [`to_circuit()`](#qiskit.quantum_info.Clifford.to_circuit ""qiskit.quantum_info.Clifford.to_circuit"") or [`to_instruction()`](#qiskit.quantum_info.Clifford.to_instruction ""qiskit.quantum_info.Clifford.to_instruction"") methods respectively. Note that this decomposition is not necessarily optimal in terms of number of gates. A minimally generating set of gates for Clifford circuits is the [`HGate`](qiskit.circuit.library.HGate ""qiskit.circuit.library.HGate"") and [`SGate`](qiskit.circuit.library.SGate ""qiskit.circuit.library.SGate"") gate and *either* the [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"") or [`CZGate`](qiskit.circuit.library.CZGate ""qiskit.circuit.library.CZGate"") two-qubit gate. Clifford operators can also be converted to [`Operator`](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") objects using the [`to_operator()`](#qiskit.quantum_info.Clifford.to_operator ""qiskit.quantum_info.Clifford.to_operator"") method. This is done via decomposing to a circuit, and then simulating the circuit as a unitary operator. **References** 1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). [arXiv:quant-ph/0406196](https://arxiv.org/abs/quant-ph/0406196) Initialize an operator object. ## Attributes ### destab The destabilizer array for the symplectic representation. ### destab\_phase Return phase of destabilizer with boolean representation. ### destab\_x The destabilizer x array for the symplectic representation. ### destab\_z The destabilizer z array for the symplectic representation. ### dim Return tuple (input\_shape, output\_shape). ### name Unique string identifier for operation type. ### num\_clbits Number of classical bits. ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### phase Return phase with boolean representation. ### qargs Return the qargs for the operator. ### stab The stabilizer array for the symplectic representation. ### stab\_phase Return phase of stabilizer with boolean representation. ### stab\_x The stabilizer x array for the symplectic representation. ### stab\_z The stabilizer array for the symplectic representation. ### symplectic\_matrix Return boolean symplectic matrix. ### x The x array for the symplectic representation. ### z The z array for the symplectic representation. ## Methods ### adjoint Return the adjoint of the Operator. ### compose Return the operator composition with another Clifford. **Parameters** * **other** ([*Clifford*](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"")) – a Clifford object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. **Returns** The composed Clifford. **Return type** [Clifford](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while `@` (equivalent to [`dot()`](#qiskit.quantum_info.Clifford.dot ""qiskit.quantum_info.Clifford.dot"")) is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B @ A == B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.Clifford.dot ""qiskit.quantum_info.Clifford.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate of the Clifford. ### copy Make a deep copy of current operator. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). **Returns** The right matrix multiplied Operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The dot product can be obtained using the `@` binary operator. Hence `a.dot(b)` is equivalent to `a @ b`. ### expand Return the reverse-order tensor product with another Clifford. **Parameters** **other** ([*Clifford*](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"")) – a Clifford object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current Clifford, and $b$ is the other Clifford. **Return type** [Clifford](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") ### from\_circuit Initialize from a QuantumCircuit or Instruction. **Parameters** **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")) – instruction to initialize. **Returns** the Clifford object for the instruction. **Return type** [Clifford](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input instruction is non-Clifford or contains classical register instruction. ### from\_dict Load a Clifford from a dictionary ### from\_label Return a tensor product of single-qubit Clifford gates. **Parameters** **label** (*string*) – single-qubit operator string. **Returns** The N-qubit Clifford operator. **Return type** [Clifford](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the label contains invalid characters. **Additional Information:** The labels correspond to the single-qubit Cliffords are * * Label * Stabilizer * Destabilizer * * `""I""` * +Z * +X * * `""X""` * -Z * +X * * `""Y""` * -Z * -X * * `""Z""` * +Z * -X * * `""H""` * +X * +Z * * `""S""` * +Z * +Y ### from\_linear\_function Create a Clifford from a Linear Function. If the linear function is represented by a nxn binary invertible matrix A, then the corresponding Clifford has symplectic matrix \[\[A^t, 0], \[0, A^\{-1}]]. **Parameters** **linear\_function** ([*LinearFunction*](qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.LinearFunction"")) – A linear function to be converted. **Returns** the Clifford object for this linear function. **Return type** [Clifford](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") ### from\_matrix Create a Clifford from a unitary matrix. Note that this function takes exponentially long time w\.r.t. the number of qubits. **Parameters** **matrix** (*np.array*) – A unitary matrix representing a Clifford to be converted. **Returns** the Clifford object for the unitary matrix. **Return type** [Clifford](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input is not a Clifford matrix. ### from\_operator Create a Clifford from a operator. Note that this function takes exponentially long time w\.r.t. the number of qubits. **Parameters** **operator** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – An operator representing a Clifford to be converted. **Returns** the Clifford object for the operator. **Return type** [Clifford](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input is not a Clifford operator. ### from\_permutation Create a Clifford from a PermutationGate. **Parameters** **permutation\_gate** ([*PermutationGate*](qiskit.circuit.library.PermutationGate ""qiskit.circuit.library.PermutationGate"")) – A permutation to be converted. **Returns** the Clifford object for this permutation. **Return type** [Clifford](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") ### input\_dims Return tuple of input dimension for specified subsystems. ### is\_unitary Return True if the Clifford table is valid. ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the compose of a operator with itself n times. **Parameters** **n** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of times to compose with self (n>0). **Returns** the n-times composed operator. **Return type** [Clifford](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the operator are not equal, or the power is not a positive integer. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### tensor Return the tensor product with another Clifford. **Parameters** **other** ([*Clifford*](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"")) – a Clifford object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current Clifford, and $b$ is the other Clifford. **Return type** [Clifford](#qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_circuit Return a QuantumCircuit implementing the Clifford. For N \<= 3 qubits this is based on optimal CX cost decomposition from reference \[1]. For N > 3 qubits this is done using the general non-optimal compilation routine from reference \[2]. **Returns** a circuit implementation of the Clifford. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **References** 1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the structure of the Clifford group*, [arXiv:2003.09412 \[quant-ph\]](https://arxiv.org/abs/2003.09412) 2. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). [arXiv:quant-ph/0406196](https://arxiv.org/abs/quant-ph/0406196) ### to\_dict Return dictionary representation of Clifford object. ### to\_instruction Return a Gate instruction implementing the Clifford. ### to\_labels Convert a Clifford to a list Pauli (de)stabilizer string labels. For large Clifford converting using the `array=True` kwarg will be more efficient since it allocates memory for the full Numpy array of labels in advance. | Label | Phase | Symplectic | Matrix | Pauli | | ------ | ----- | ---------- | ------------------------------------------------ | ----- | | `""+I""` | 0 | $[0, 0]$ | $\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}$ | $I$ | | `""-I""` | 1 | $[0, 0]$ | $\begin{bmatrix} -1 & 0 \\ 0 & -1 \end{bmatrix}$ | $-I$ | | `""X""` | 0 | $[1, 0]$ | $\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$ | $X$ | | `""-X""` | 1 | $[1, 0]$ | $\begin{bmatrix} 0 & -1 \\ -1 & 0 \end{bmatrix}$ | $-X$ | | `""Y""` | 0 | $[1, 1]$ | $\begin{bmatrix} 0 & 1 \\ -1 & 0 \end{bmatrix}$ | $iY$ | | `""-Y""` | 1 | $[1, 1]$ | $\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}$ | $-iY$ | | `""Z""` | 0 | $[0, 1]$ | $\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}$ | $Z$ | | `""-Z""` | 1 | $[0, 1]$ | $\begin{bmatrix} -1 & 0 \\ 0 & 1 \end{bmatrix}$ | $-Z$ | **Parameters** * **array** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – return a Numpy array if True, otherwise return a list (Default: False). * **mode** (*Literal\[""S"", ""D"", ""B""]*) – return both stabilizer and destabilizer if “B”, return only stabilizer if “S” and return only destabilizer if “D”. **Returns** The rows of the StabilizerTable in label form. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") or array **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if stabilizer and destabilizer are both False. ### to\_matrix Convert operator to Numpy matrix. ### to\_operator Convert to an Operator object. **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### transpose Return the transpose of the Clifford. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.Clifford.mdx "--- title: CNOTDihedral description: API reference for qiskit.quantum_info.CNOTDihedral in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.CNOTDihedral --- # CNOTDihedral Bases: `BaseOperator`, `AdjointMixin` An N-qubit operator from the CNOT-Dihedral group. > The CNOT-Dihedral group is generated by the quantum gates, [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate""), [`TGate`](qiskit.circuit.library.TGate ""qiskit.circuit.library.TGate""), and [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate""). > > **Representation** > > An $N$-qubit CNOT-Dihedral operator is stored as an affine function and a phase polynomial, based on the convention in references \[1, 2]. > > The affine function consists of an $N \times N$ invertible binary matrix, and an $N$ binary vector. > > The phase polynomial is a polynomial of degree at most 3, in $N$ variables, whose coefficients are in the ring Z\_8 with 8 elements. > > ```python > from qiskit import QuantumCircuit > from qiskit.quantum_info import CNOTDihedral > > circ = QuantumCircuit(3) > circ.cx(0, 1) > circ.x(2) > circ.t(1) > circ.t(1) > circ.t(1) > elem = CNOTDihedral(circ) > > # Print the CNOTDihedral element > print(elem) > ``` ```python phase polynomial = 0 + 3*x_0 + 3*x_1 + 2*x_0*x_1 affine function = (x_0,x_0 + x_1,x_2 + 1) ``` **Circuit Conversion** > CNOTDihedral operators can be initialized from circuits containing *only* the following gates: [`IGate`](qiskit.circuit.library.IGate ""qiskit.circuit.library.IGate""), [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate""), [`YGate`](qiskit.circuit.library.YGate ""qiskit.circuit.library.YGate""), [`ZGate`](qiskit.circuit.library.ZGate ""qiskit.circuit.library.ZGate""), [`TGate`](qiskit.circuit.library.TGate ""qiskit.circuit.library.TGate""), [`TdgGate`](qiskit.circuit.library.TdgGate ""qiskit.circuit.library.TdgGate"") [`SGate`](qiskit.circuit.library.SGate ""qiskit.circuit.library.SGate""), [`SdgGate`](qiskit.circuit.library.SdgGate ""qiskit.circuit.library.SdgGate""), [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate""), [`CZGate`](qiskit.circuit.library.CZGate ""qiskit.circuit.library.CZGate""), [`CSGate`](qiskit.circuit.library.CSGate ""qiskit.circuit.library.CSGate""), [`CSdgGate`](qiskit.circuit.library.CSdgGate ""qiskit.circuit.library.CSdgGate""), [`SwapGate`](qiskit.circuit.library.SwapGate ""qiskit.circuit.library.SwapGate""), [`CCZGate`](qiskit.circuit.library.CCZGate ""qiskit.circuit.library.CCZGate""). They can be converted back into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""), or [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") object using the [`to_circuit()`](#qiskit.quantum_info.CNOTDihedral.to_circuit ""qiskit.quantum_info.CNOTDihedral.to_circuit"") or `to_instruction()` methods respectively. Note that this decomposition is not necessarily optimal in terms of number of gates if the number of qubits is more than two. > > CNOTDihedral operators can also be converted to [`Operator`](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") objects using the [`to_operator()`](#qiskit.quantum_info.CNOTDihedral.to_operator ""qiskit.quantum_info.CNOTDihedral.to_operator"") method. This is done via decomposing to a circuit, and then simulating the circuit as a unitary operator. > > **References:** > > 1. Shelly Garion and Andrew W. Cross, *Synthesis of CNOT-Dihedral circuits with optimal number of two qubit gates*, [Quantum 4(369), 2020](https://quantum-journal.org/papers/q-2020-12-07-369/) > 2. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). Initialize a CNOTDihedral operator object. **Parameters** * **data** ([*CNOTDihedral*](#qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")) – Optional, operator to initialize. * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional, initialize an empty CNOTDihedral operator. * **validate** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, validates the CNOTDihedral element. **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the type is invalid. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if validate=True and the CNOTDihedral element is invalid. ## Attributes ### dim Return tuple (input\_shape, output\_shape). ### name Unique string identifier for operation type. ### num\_clbits Number of classical bits. ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### qargs Return the qargs for the operator. ## Methods ### adjoint Return the adjoint of the Operator. ### compose Return the operator composition with another CNOTDihedral. **Parameters** * **other** ([*CNOTDihedral*](#qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"")) – a CNOTDihedral object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. **Returns** The composed CNOTDihedral. **Return type** [CNOTDihedral](#qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while `@` (equivalent to [`dot()`](#qiskit.quantum_info.CNOTDihedral.dot ""qiskit.quantum_info.CNOTDihedral.dot"")) is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B @ A == B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.CNOTDihedral.dot ""qiskit.quantum_info.CNOTDihedral.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate of the CNOTDihedral. ### copy Make a deep copy of current operator. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). **Returns** The right matrix multiplied Operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The dot product can be obtained using the `@` binary operator. Hence `a.dot(b)` is equivalent to `a @ b`. ### expand Return the reverse-order tensor product with another CNOTDihedral. **Parameters** **other** ([*CNOTDihedral*](#qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"")) – a CNOTDihedral object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current CNOTDihedral, and $b$ is the other CNOTDihedral. **Return type** [CNOTDihedral](#qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") ### input\_dims Return tuple of input dimension for specified subsystems. ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the compose of a operator with itself n times. **Parameters** **n** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of times to compose with self (n>0). **Returns** the n-times composed operator. **Return type** [Clifford](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the operator are not equal, or the power is not a positive integer. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### tensor Return the tensor product with another CNOTDihedral. **Parameters** **other** ([*CNOTDihedral*](#qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"")) – a CNOTDihedral object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current CNOTDihedral, and $b$ is the other CNOTDihedral. **Return type** [CNOTDihedral](#qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_circuit Return a QuantumCircuit implementing the CNOT-Dihedral element. **Returns** a circuit implementation of the CNOTDihedral object. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **References** 1. Shelly Garion and Andrew W. Cross, *Synthesis of CNOT-Dihedral circuits with optimal number of two qubit gates*, [Quantum 4(369), 2020](https://quantum-journal.org/papers/q-2020-12-07-369/) 2. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). ### to\_instruction Return a Gate instruction implementing the CNOTDihedral object. ### to\_matrix Convert operator to Numpy matrix. ### to\_operator Convert to an Operator object. **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### transpose Return the transpose of the CNOTDihedral. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.CNOTDihedral.mdx "--- title: DensityMatrix description: API reference for qiskit.quantum_info.DensityMatrix in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.DensityMatrix --- # DensityMatrix Bases: `QuantumState`, `TolerancesMixin` DensityMatrix class Initialize a density matrix object. **Parameters** * **or** (*data (np.ndarray or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or matrix\_like or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – qiskit.circuit.Instruction): A statevector, quantum instruction or an object with a `to_operator` or `to_matrix` method from which the density matrix can be constructed. If a vector the density matrix is constructed as the projector of that vector. If a quantum instruction, the density matrix is constructed by assuming all qubits are initialized in the zero state. * **dims** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – Optional. The subsystem dimension of the state (See additional information). **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data is not valid. **Additional Information:** The `dims` kwarg can be None, an integer, or an iterable of integers. * `Iterable` – the subsystem dimensions are the values in the list with the total number of subsystems given by the length of the list. * `Int` or `None` – the leading dimension of the input matrix specifies the total dimension of the density matrix. If it is a power of two the state will be initialized as an N-qubit state. If it is not a power of two the state will have a single d-dimensional subsystem. ## Attributes ### atol ### data Return data. ### dim Return total state dimension. ### num\_qubits Return the number of qubits if a N-qubit state or None otherwise. ### rtol ### settings Return settings. ## Methods ### conjugate Return the conjugate of the density matrix. ### copy Make a copy of current operator. ### dims Return tuple of input dimension for specified subsystems. ### draw Return a visualization of the Statevector. **repr**: ASCII TextMatrix of the state’s `__repr__`. **text**: ASCII TextMatrix that can be printed in the console. **latex**: An IPython Latex object for displaying in Jupyter Notebooks. **latex\_source**: Raw, uncompiled ASCII source to generate array using LaTeX. **qsphere**: Matplotlib figure, rendering of density matrix using plot\_state\_qsphere(). **hinton**: Matplotlib figure, rendering of density matrix using plot\_state\_hinton(). **bloch**: Matplotlib figure, rendering of density matrix using plot\_bloch\_multivector(). **Parameters** * **output** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Select the output method to use for drawing the state. Valid choices are repr, text, latex, latex\_source, qsphere, hinton, or bloch. Default is repr. Default can be changed by adding the line `state_drawer = ` to `~/.qiskit/settings.conf` under `[default]`. * **drawer\_args** – Arguments to be passed directly to the relevant drawing function or constructor (TextMatrix(), array\_to\_latex(), plot\_state\_qsphere(), plot\_state\_hinton() or plot\_bloch\_multivector()). See the relevant function under qiskit.visualization for that function’s documentation. **Returns** `matplotlib.Figure` or [`str`](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") or `TextMatrix` or `IPython.display.Latex`: Drawing of the Statevector. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – when an invalid output method is selected. ### evolve Evolve a quantum state by an operator. **Parameters** * **QuantumChannel** (*other (Operator or*) – or Instruction or Circuit): The operator to evolve by. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – a list of QuantumState subsystem positions to apply the operator on. **Returns** the output density matrix. **Return type** [DensityMatrix](#qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the operator dimension does not match the specified QuantumState subsystem dimensions. ### expand Return the tensor product state other ⊗ self. **Parameters** **other** ([*DensityMatrix*](#qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")) – a quantum state object. **Returns** the tensor product state other ⊗ self. **Return type** [DensityMatrix](#qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other is not a quantum state. ### expectation\_value Compute the expectation value of an operator. **Parameters** * **oper** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator to evaluate expval. * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to apply the operator on. **Returns** the expectation value. **Return type** [complex](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"") ### from\_instruction Return the output density matrix of an instruction. The statevector is initialized in the state $|{0,\ldots,0}\rangle$ of the same number of qubits as the input instruction or circuit, evolved by the input instruction, and the output statevector returned. **Parameters** **instruction** ([*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – instruction or circuit **Returns** the final density matrix. **Return type** [DensityMatrix](#qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the instruction contains invalid instructions for density matrix simulation. ### from\_int Return a computational basis state density matrix. **Parameters** * **i** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the basis state element. * **dims** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The subsystem dimensions of the statevector (See additional information). **Returns** The computational basis state $|i\rangle\!\langle i|$. **Return type** [DensityMatrix](#qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") **Additional Information:** The `dims` kwarg can be an integer or an iterable of integers. * `Iterable` – the subsystem dimensions are the values in the list with the total number of subsystems given by the length of the list. * `Int` – the integer specifies the total dimension of the state. If it is a power of two the state will be initialized as an N-qubit state. If it is not a power of two the state will have a single d-dimensional subsystem. ### from\_label Return a tensor product of Pauli X,Y,Z eigenstates. | Label | Statevector | | ----- | ----------------------------------------------------------- | | `""0""` | $\begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}$ | | `""1""` | $\begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}$ | | `""+""` | $\frac{1}{2}\begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}$ | | `""-""` | $\frac{1}{2}\begin{pmatrix} 1 & -1 \\ -1 & 1 \end{pmatrix}$ | | `""r""` | $\frac{1}{2}\begin{pmatrix} 1 & -i \\ i & 1 \end{pmatrix}$ | | `""l""` | $\frac{1}{2}\begin{pmatrix} 1 & i \\ -i & 1 \end{pmatrix}$ | **Parameters** **label** (*string*) – a eigenstate string ket label (see table for allowed values). **Returns** The N-qubit basis state density matrix. **Return type** [DensityMatrix](#qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the label contains invalid characters, or the length of the label is larger than an explicitly specified num\_qubits. ### is\_valid Return True if trace 1 and positive semidefinite. ### measure Measure subsystems and return outcome and post-measure state. Note that this function uses the QuantumStates internal random number generator for sampling the measurement outcome. The RNG seed can be set using the [`seed()`](#qiskit.quantum_info.DensityMatrix.seed ""qiskit.quantum_info.DensityMatrix.seed"") method. **Parameters** **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). **Returns** **the pair `(outcome, state)` where `outcome` is the** measurement outcome string label, and `state` is the collapsed post-measurement state for the corresponding outcome. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") ### partial\_transpose Return partially transposed density matrix. **Parameters** **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The subsystems to be transposed. **Returns** The partially transposed density matrix. **Return type** [DensityMatrix](#qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") ### probabilities Return the subsystem measurement probability vector. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. **Parameters** * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to return probabilities for, if None return for all subsystems (Default: None). * **decimals** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of decimal places to round values. If None no rounding is done (Default: None). **Returns** The Numpy vector array of probabilities. **Return type** np.array **Examples** Consider a 2-qubit product state $\rho=\rho_1\otimes\rho_0$ with $\rho_1=|+\rangle\!\langle+|$, $\rho_0=|0\rangle\!\langle0|$. ```python from qiskit.quantum_info import DensityMatrix rho = DensityMatrix.from_label('+0') # Probabilities for measuring both qubits probs = rho.probabilities() print('probs: {}'.format(probs)) # Probabilities for measuring only qubit-0 probs_qubit_0 = rho.probabilities([0]) print('Qubit-0 probs: {}'.format(probs_qubit_0)) # Probabilities for measuring only qubit-1 probs_qubit_1 = rho.probabilities([1]) print('Qubit-1 probs: {}'.format(probs_qubit_1)) ``` ```python probs: [0.5 0. 0.5 0. ] Qubit-0 probs: [1. 0.] Qubit-1 probs: [0.5 0.5] ``` We can also permute the order of qubits in the `qargs` list to change the qubit position in the probabilities output ```python from qiskit.quantum_info import DensityMatrix rho = DensityMatrix.from_label('+0') # Probabilities for measuring both qubits probs = rho.probabilities([0, 1]) print('probs: {}'.format(probs)) # Probabilities for measuring both qubits # but swapping qubits 0 and 1 in output probs_swapped = rho.probabilities([1, 0]) print('Swapped probs: {}'.format(probs_swapped)) ``` ```python probs: [0.5 0. 0.5 0. ] Swapped probs: [0.5 0.5 0. 0. ] ``` ### probabilities\_dict Return the subsystem measurement probability dictionary. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. **Parameters** * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to return probabilities for, if None return for all subsystems (Default: None). * **decimals** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of decimal places to round values. If None no rounding is done (Default: None). **Returns** The measurement probabilities in dict (ket) form. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ### purity Return the purity of the quantum state. ### reset Reset state or subsystems to the 0-state. **Parameters** **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – subsystems to reset, if None all subsystems will be reset to their 0-state (Default: None). **Returns** the reset state. **Return type** [DensityMatrix](#qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") **Additional Information:** If all subsystems are reset this will return the ground state on all subsystems. If only a some subsystems are reset this function will perform evolution by the reset [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") of the reset subsystems. ### reverse\_qargs Return a DensityMatrix with reversed subsystem ordering. For a tensor product state this is equivalent to reversing the order of tensor product subsystems. For a density matrix $\rho = \rho_{n-1} \otimes ... \otimes \rho_0$ the returned state will be $\rho_0 \otimes ... \otimes \rho_{n-1}$. **Returns** the state with reversed subsystem order. **Return type** [DensityMatrix](#qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") ### sample\_counts Sample a dict of qubit measurement outcomes in the computational basis. **Parameters** * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of samples to generate. * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). **Returns** sampled counts dictionary. **Return type** [Counts](qiskit.result.Counts ""qiskit.result.Counts"") Additional Information: > This function *samples* measurement outcomes using the measure [`probabilities()`](#qiskit.quantum_info.DensityMatrix.probabilities ""qiskit.quantum_info.DensityMatrix.probabilities"") for the current state and qargs. It does not actually implement the measurement so the current state is not modified. > > The seed for random number generator used for sampling can be set to a fixed value by using the stats [`seed()`](#qiskit.quantum_info.DensityMatrix.seed ""qiskit.quantum_info.DensityMatrix.seed"") method. ### sample\_memory Sample a list of qubit measurement outcomes in the computational basis. **Parameters** * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of samples to generate. * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). **Returns** list of sampled counts if the order sampled. **Return type** np.array Additional Information: > This function *samples* measurement outcomes using the measure [`probabilities()`](#qiskit.quantum_info.DensityMatrix.probabilities ""qiskit.quantum_info.DensityMatrix.probabilities"") for the current state and qargs. It does not actually implement the measurement so the current state is not modified. > > The seed for random number generator used for sampling can be set to a fixed value by using the stats [`seed()`](#qiskit.quantum_info.DensityMatrix.seed ""qiskit.quantum_info.DensityMatrix.seed"") method. ### seed Set the seed for the quantum state RNG. ### tensor Return the tensor product state self ⊗ other. **Parameters** **other** ([*DensityMatrix*](#qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")) – a quantum state object. **Returns** the tensor product operator self ⊗ other. **Return type** [DensityMatrix](#qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other is not a quantum state. ### to\_dict Convert the density matrix to dictionary form. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. **Parameters** **decimals** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of decimal places to round values. If None no rounding is done (Default: None). **Returns** the dictionary form of the DensityMatrix. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") **Examples** The ket-form of a 2-qubit density matrix $rho = |-\rangle\!\langle -|\otimes |0\rangle\!\langle 0|$ ```python from qiskit.quantum_info import DensityMatrix rho = DensityMatrix.from_label('-0') print(rho.to_dict()) ``` ```python { '00|00': (0.4999999999999999+0j), '10|00': (-0.4999999999999999-0j), '00|10': (-0.4999999999999999+0j), '10|10': (0.4999999999999999+0j) } ``` For non-qubit subsystems the integer range can go from 0 to 9. For example in a qutrit system ```python import numpy as np from qiskit.quantum_info import DensityMatrix mat = np.zeros((9, 9)) mat[0, 0] = 0.25 mat[3, 3] = 0.25 mat[6, 6] = 0.25 mat[-1, -1] = 0.25 rho = DensityMatrix(mat, dims=(3, 3)) print(rho.to_dict()) ``` ```python {'00|00': (0.25+0j), '10|10': (0.25+0j), '20|20': (0.25+0j), '22|22': (0.25+0j)} ``` For large subsystem dimensions delimiters are required. The following example is for a 20-dimensional system consisting of a qubit and 10-dimensional qudit. ```python import numpy as np from qiskit.quantum_info import DensityMatrix mat = np.zeros((2 * 10, 2 * 10)) mat[0, 0] = 0.5 mat[-1, -1] = 0.5 rho = DensityMatrix(mat, dims=(2, 10)) print(rho.to_dict()) ``` ```python {'00|00': (0.5+0j), '91|91': (0.5+0j)} ``` ### to\_operator Convert to Operator **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### to\_statevector Return a statevector from a pure density matrix. **Parameters** * **atol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Absolute tolerance for checking operation validity. * **rtol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Relative tolerance for checking operation validity. **Returns** **The pure density matrix’s corresponding statevector.** Corresponds to the eigenvector of the only non-zero eigenvalue. **Return type** [Statevector](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the state is not pure. ### trace Return the trace of the density matrix. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.DensityMatrix.mdx "--- title: Kraus description: API reference for qiskit.quantum_info.Kraus in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.Kraus --- # Kraus Bases: `QuantumChannel` Kraus representation of a quantum channel. For a quantum channel $\mathcal{E}$, the Kraus representation is given by a set of matrices $[A_0,...,A_{K-1}]$ such that the evolution of a [`DensityMatrix`](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") $\rho$ is given by $$ \mathcal{E}(\rho) = \sum_{i=0}^{K-1} A_i \rho A_i^\dagger $$ A general operator map $\mathcal{G}$ can also be written using the generalized Kraus representation which is given by two sets of matrices $[A_0,...,A_{K-1}]$, $[B_0,...,A_{B-1}]$ such that $$ \mathcal{G}(\rho) = \sum_{i=0}^{K-1} A_i \rho B_i^\dagger $$ See reference \[1] for further details. **References** 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). [arXiv:1111.6950 \[quant-ph\]](https://arxiv.org/abs/1111.6950) Initialize a quantum channel Kraus operator. **Parameters** * **data** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *|*[*circuit.instruction.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"") *| BaseOperator | np.ndarray*) – data to initialize superoperator. * **input\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") *| None*) – the input subsystem dimensions. * **output\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") *| None*) – the output subsystem dimensions. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data cannot be initialized as a list of Kraus matrices. **Additional Information:** If the input or output dimensions are None, they will be automatically determined from the input data. If the input data is a list of Numpy arrays of shape $(2^N,\,2^N)$ qubit systems will be used. If the input does not correspond to an N-qubit channel, it will assign a single subsystem with dimension specified by the shape of the input. ## Attributes ### atol ### data Return list of Kraus matrices for channel. ### dim Return tuple (input\_shape, output\_shape). ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### qargs Return the qargs for the operator. ### rtol ### settings Return settings. ## Methods ### adjoint Return the adjoint quantum channel. This is equivalent to the matrix Hermitian conjugate in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the adjoint channel $\mathcal{{E}}^\dagger$ is $S_{\mathcal{E}^\dagger} = S_{\mathcal{E}}^\dagger$. ### compose Return the operator composition with another Kraus. **Parameters** * **other** ([*Kraus*](#qiskit.quantum_info.Kraus ""qiskit.quantum_info.Kraus"")) – a Kraus object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. **Returns** The composed Kraus. **Return type** [Kraus](#qiskit.quantum_info.Kraus ""qiskit.quantum_info.Kraus"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while `@` (equivalent to [`dot()`](#qiskit.quantum_info.Kraus.dot ""qiskit.quantum_info.Kraus.dot"")) is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B @ A == B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.Kraus.dot ""qiskit.quantum_info.Kraus.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate quantum channel. This is equivalent to the matrix complex conjugate in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the conjugate channel $\overline{{\mathcal{{E}}}}$ is $S_{\overline{\mathcal{E}^\dagger}} = \overline{S_{\mathcal{E}}}$. ### copy Make a deep copy of current operator. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). **Returns** The right matrix multiplied Operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The dot product can be obtained using the `@` binary operator. Hence `a.dot(b)` is equivalent to `a @ b`. ### expand Return the reverse-order tensor product with another Kraus. **Parameters** **other** ([*Kraus*](#qiskit.quantum_info.Kraus ""qiskit.quantum_info.Kraus"")) – a Kraus object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current Kraus, and $b$ is the other Kraus. **Return type** [Kraus](#qiskit.quantum_info.Kraus ""qiskit.quantum_info.Kraus"") ### input\_dims Return tuple of input dimension for specified subsystems. ### is\_cp Test if Choi-matrix is completely-positive (CP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_cptp Return True if completely-positive trace-preserving. ### is\_tp Test if a channel is trace-preserving (TP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_unitary Return True if QuantumChannel is a unitary channel. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the power of the quantum channel. **Parameters** **n** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – the power exponent. **Returns** the channel $\mathcal{{E}} ^n$. **Return type** [SuperOp](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the SuperOp are not equal. For non-positive or non-integer exponents the power is defined as the matrix power of the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{{E}}$, the SuperOp of the powered channel $\mathcal{{E}}^\n$ is $S_{{\mathcal{{E}}^n}} = S_{{\mathcal{{E}}}}^n$. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### tensor Return the tensor product with another Kraus. **Parameters** **other** ([*Kraus*](#qiskit.quantum_info.Kraus ""qiskit.quantum_info.Kraus"")) – a Kraus object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current Kraus, and $b$ is the other Kraus. **Return type** [Kraus](#qiskit.quantum_info.Kraus ""qiskit.quantum_info.Kraus"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_instruction Convert to a Kraus or UnitaryGate circuit instruction. If the channel is unitary it will be added as a unitary gate, otherwise it will be added as a kraus simulator instruction. **Returns** A kraus instruction for the channel. **Return type** [qiskit.circuit.Instruction](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data is not an N-qubit CPTP quantum channel. ### to\_operator Try to convert channel to a unitary representation Operator. **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### transpose Return the transpose quantum channel. This is equivalent to the matrix transpose in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation, ie. for a channel $\mathcal{E}$, the SuperOp of the transpose channel $\mathcal{{E}}^T$ is $S_{mathcal{E}^T} = S_{\mathcal{E}}^T$. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.Kraus.mdx "--- title: Operator description: API reference for qiskit.quantum_info.Operator in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.Operator --- # Operator Bases: `LinearOp` Matrix operator class This represents a matrix operator $M$ that will [`evolve()`](qiskit.quantum_info.Statevector#evolve ""qiskit.quantum_info.Statevector.evolve"") a [`Statevector`](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") $|\psi\rangle$ by matrix-vector multiplication $$ |\psi\rangle \mapsto M|\psi\rangle, $$ and will [`evolve()`](qiskit.quantum_info.DensityMatrix#evolve ""qiskit.quantum_info.DensityMatrix.evolve"") a [`DensityMatrix`](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") $\rho$ by left and right multiplication $$ \rho \mapsto M \rho M^\dagger. $$ Initialize an operator object. **Parameters** * **data** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Operation*](qiskit.circuit.Operation ""qiskit.circuit.Operation"") *or BaseOperator or matrix*) – data to initialize operator. * **input\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the input subsystem dimensions. \[Default: None] * **output\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the output subsystem dimensions. \[Default: None] **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data cannot be initialized as an operator. **Additional Information:** If the input or output dimensions are None, they will be automatically determined from the input data. If the input data is a Numpy array of shape (2\*\*N, 2\*\*N) qubit systems will be used. If the input operator is not an N-qubit operator, it will assign a single subsystem with dimension specified by the shape of the input. ## Attributes ### atol ### data The underlying Numpy array. ### dim Return tuple (input\_shape, output\_shape). ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### qargs Return the qargs for the operator. ### rtol ### settings Return operator settings. ## Methods ### adjoint Return the adjoint of the Operator. **Return type** *Self* ### apply\_permutation Modifies operator’s data by composing it with a permutation. **Parameters** * **perm** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – permutation pattern, describing which qubits occupy the positions 0, 1, 2, etc. after applying the permutation. * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – When set to `True` the permutation is applied before the operator, when set to `False` the permutation is applied after the operator. **Returns** The modified operator. **Return type** [Operator](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the size of the permutation pattern does not match the dimensions of the operator. ### compose Return the operator composition with another Operator. **Parameters** * **other** ([*Operator*](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – a Operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. **Returns** The composed Operator. **Return type** [Operator](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while `@` (equivalent to [`dot()`](#qiskit.quantum_info.Operator.dot ""qiskit.quantum_info.Operator.dot"")) is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B @ A == B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.Operator.dot ""qiskit.quantum_info.Operator.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate of the Operator. ### copy Make a deep copy of current operator. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Operator*](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). **Returns** The right matrix multiplied Operator. **Return type** [Operator](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The dot product can be obtained using the `@` binary operator. Hence `a.dot(b)` is equivalent to `a @ b`. ### draw Return a visualization of the Operator. **repr**: String of the state’s `__repr__`. **text**: ASCII TextMatrix that can be printed in the console. **latex**: An IPython Latex object for displaying in Jupyter Notebooks. **latex\_source**: Raw, uncompiled ASCII source to generate array using LaTeX. **Parameters** * **output** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Select the output method to use for drawing the state. Valid choices are repr, text, latex, latex\_source, Default is repr. * **drawer\_args** – Arguments to be passed directly to the relevant drawing function or constructor (TextMatrix(), array\_to\_latex()). See the relevant function under qiskit.visualization for that function’s documentation. **Returns** Drawing of the Operator. **Return type** [`str`](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") or `TextMatrix` or `IPython.display.Latex` **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – when an invalid output method is selected. ### equiv Return True if operators are equivalent up to global phase. **Parameters** * **other** ([*Operator*](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **rtol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – relative tolerance value for comparison. * **atol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – absolute tolerance value for comparison. **Returns** True if operators are equivalent up to global phase. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### expand Return the reverse-order tensor product with another Operator. **Parameters** **other** ([*Operator*](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – a Operator object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current Operator, and $b$ is the other Operator. **Return type** [Operator](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") ### from\_circuit Create a new Operator object from a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") While a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") object can passed directly as `data` to the class constructor this provides no options on how the circuit is used to create an [`Operator`](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator""). This constructor method lets you control how the [`Operator`](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") is created so it can be adjusted for a particular use case. By default this constructor method will permute the qubits based on a configured initial layout (i.e. after it was transpiled). It also provides an option to manually provide a [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") object directly. **Parameters** * **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – The [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") to create an Operator object from. * **ignore\_set\_layout** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – When set to `True` if the input `circuit` has a layout set it will be ignored * **layout** ([*Layout*](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"")) – If specified this kwarg can be used to specify a particular layout to use to permute the qubits in the created [`Operator`](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator""). If this is specified it will be used instead of a layout contained in the `circuit` input. If specified the virtual bits in the [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") must be present in the `circuit` input. * **final\_layout** ([*Layout*](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"")) – If specified this kwarg can be used to represent the output permutation caused by swap insertions during the routing stage of the transpiler. **Returns** An operator representing the input circuit **Return type** [Operator](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") ### from\_label Return a tensor product of single-qubit operators. **Parameters** **label** (*string*) – single-qubit operator string. **Returns** The N-qubit operator. **Return type** [Operator](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the label contains invalid characters, or the length of the label is larger than an explicitly specified num\_qubits. **Additional Information:** The labels correspond to the single-qubit matrices: ‘I’: \[\[1, 0], \[0, 1]] ‘X’: \[\[0, 1], \[1, 0]] ‘Y’: \[\[0, -1j], \[1j, 0]] ‘Z’: \[\[1, 0], \[0, -1]] ‘H’: \[\[1, 1], \[1, -1]] / sqrt(2) ‘S’: \[\[1, 0], \[0 , 1j]] ‘T’: \[\[1, 0], \[0, (1+1j) / sqrt(2)]] ‘0’: \[\[1, 0], \[0, 0]] ‘1’: \[\[0, 0], \[0, 1]] ‘+’: \[\[0.5, 0.5], \[0.5 , 0.5]] ‘-’: \[\[0.5, -0.5], \[-0.5 , 0.5]] ‘r’: \[\[0.5, -0.5j], \[0.5j , 0.5]] ‘l’: \[\[0.5, 0.5j], \[-0.5j , 0.5]] ### input\_dims Return tuple of input dimension for specified subsystems. ### is\_unitary Return True if operator is a unitary matrix. ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the matrix power of the operator. **Parameters** **n** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – the power to raise the matrix to. **Returns** the resulting operator `O ** n`. **Return type** [Operator](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the operator are not equal. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### reverse\_qargs Return an Operator with reversed subsystem ordering. For a tensor product operator this is equivalent to reversing the order of tensor product subsystems. For an operator $A = A_{n-1} \otimes ... \otimes A_0$ the returned operator will be $A_0 \otimes ... \otimes A_{n-1}$. **Returns** the operator with reversed subsystem order. **Return type** [Operator](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") ### tensor Return the tensor product with another Operator. **Parameters** **other** ([*Operator*](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – a Operator object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current Operator, and $b$ is the other Operator. **Return type** [Operator](#qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_instruction Convert to a UnitaryGate instruction. ### to\_matrix Convert operator to NumPy matrix. ### to\_operator Convert operator to matrix operator class **Return type** [*Operator*](#qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### transpose Return the transpose of the Operator. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.Operator.mdx "--- title: Pauli description: API reference for qiskit.quantum_info.Pauli in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.Pauli --- # Pauli Bases: `BasePauli` N-qubit Pauli operator. This class represents an operator $P$ from the full $n$-qubit *Pauli* group $$ P = (-i)^{q} P_{n-1} \otimes ... \otimes P_{0} $$ where $q\in \mathbb{Z}_4$ and $P_i \in \{I, X, Y, Z\}$ are single-qubit Pauli matrices: $$ I = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}, X = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}, Y = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix}, Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}. $$ **Initialization** A Pauli object can be initialized in several ways: > **`Pauli(obj)`** > > where `obj` is a Pauli string, `Pauli` or [`ScalarOp`](qiskit.quantum_info.ScalarOp ""qiskit.quantum_info.ScalarOp"") operator, or a Pauli gate or `QuantumCircuit` containing only Pauli gates. > > **`Pauli((z, x, phase))`** > > where `z` and `x` are boolean `numpy.ndarrays` and `phase` is an integer in `[0, 1, 2, 3]`. > > **`Pauli((z, x))`** > > equivalent to `Pauli((z, x, 0))` with trivial phase. **String representation** An $n$-qubit Pauli may be represented by a string consisting of $n$ characters from `['I', 'X', 'Y', 'Z']`, and optionally phase coefficient in $['', '-i', '-', 'i']$. For example: `XYZ` or `'-iZIZ'`. In the string representation qubit-0 corresponds to the right-most Pauli character, and qubit-$(n-1)$ to the left-most Pauli character. For example `'XYZ'` represents $X\otimes Y \otimes Z$ with `'Z'` on qubit-0, `'Y'` on qubit-1, and `'X'` on qubit-2. The string representation can be converted to a `Pauli` using the class initialization (`Pauli('-iXYZ')`). A `Pauli` object can be converted back to the string representation using the [`to_label()`](#qiskit.quantum_info.Pauli.to_label ""qiskit.quantum_info.Pauli.to_label"") method or `str(pauli)`. Using `str` to convert a `Pauli` to a string will truncate the returned string for large numbers of qubits while [`to_label()`](#qiskit.quantum_info.Pauli.to_label ""qiskit.quantum_info.Pauli.to_label"") will return the full string with no truncation. The default truncation length is 50 characters. The default value can be changed by setting the class `__truncate__` attribute to an integer value. If set to `0` no truncation will be performed. **Array Representation** The internal data structure of an $n$-qubit Pauli is two length-$n$ boolean vectors $z \in \mathbb{Z}_2^N$, $x \in \mathbb{Z}_2^N$, and an integer $q \in \mathbb{Z}_4$ defining the Pauli operator $$ P = (-i)^{q + z\cdot x} Z^z \cdot X^x. $$ The $k$-th qubit corresponds to the $k$-th entry in the $z$ and $x$ arrays $$ \begin{aligned} P &= P_{n-1} \otimes ... \otimes P_{0} \\ P_k &= (-i)^{z[k] * x[k]} Z^{z[k]}\cdot X^{x[k]} \end{aligned} $$ where `z[k] = P.z[k]`, `x[k] = P.x[k]` respectively. The $z$ and $x$ arrays can be accessed and updated using the [`z`](#qiskit.quantum_info.Pauli.z ""qiskit.quantum_info.Pauli.z"") and [`x`](#qiskit.quantum_info.Pauli.x ""qiskit.quantum_info.Pauli.x"") properties respectively. The phase integer $q$ can be accessed and updated using the [`phase`](#qiskit.quantum_info.Pauli.phase ""qiskit.quantum_info.Pauli.phase"") property. **Matrix Operator Representation** Pauli’s can be converted to $(2^n, 2^n)$ [`Operator`](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") using the `to_operator()` method, or to a dense or sparse complex matrix using the [`to_matrix()`](#qiskit.quantum_info.Pauli.to_matrix ""qiskit.quantum_info.Pauli.to_matrix"") method. **Data Access** The individual qubit Paulis can be accessed and updated using the `[]` operator which accepts integer, lists, or slices for selecting subsets of Paulis. Note that selecting subsets of Pauli’s will discard the phase of the current Pauli. For example ```python p = Pauli('-iXYZ') print('P[0] =', repr(P[0])) print('P[1] =', repr(P[1])) print('P[2] =', repr(P[2])) print('P[:] =', repr(P[:])) print('P[::-1] =, repr(P[::-1])) ``` Initialize the Pauli. When using the symplectic array input data both z and x arguments must be provided, however the first (z) argument can be used alone for string label, Pauli operator, or ScalarOp input data. **Parameters** **data** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") *or*[*Pauli*](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") *or*[*ScalarOp*](qiskit.quantum_info.ScalarOp ""qiskit.quantum_info.ScalarOp"")) – input data for Pauli. If input is a tuple it must be of the form `(z, x)` or (z, x, phase)\`\` where `z` and `x` are boolean Numpy arrays, and phase is an integer from Z\_4. If input is a string, it must be a concatenation of a phase and a Pauli string (e.g. ‘XYZ’, ‘-iZIZ’) where a phase string is a combination of at most three characters from \[‘+’, ‘-’, ‘’], \[‘1’, ‘’], and \[‘i’, ‘j’, ‘’] in this order, e.g. ‘’, ‘-1j’ while a Pauli string is 1 or more characters of ‘I’, ‘X’, ‘Y’ or ‘Z’, e.g. ‘Z’, ‘XIYY’. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input array is invalid shape. ## Attributes ### dim Return tuple (input\_shape, output\_shape). ### name Unique string identifier for operation type. ### num\_clbits Number of classical bits. ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### phase Return the group phase exponent for the Pauli. ### qargs Return the qargs for the operator. ### settings Return settings. ### x The x vector for the Pauli. ### z The z vector for the Pauli. ## Methods ### adjoint Return the adjoint of the Operator. ### anticommutes Return True if other Pauli anticommutes with self. **Parameters** * **other** ([*Pauli*](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")) – another Pauli operator. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – qubits to apply dot product on (default: None). **Returns** True if Pauli’s anticommute, False if they commute. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### commutes Return True if the Pauli commutes with other. **Parameters** * **other** ([*Pauli*](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") *or*[*PauliList*](qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")) – another Pauli operator. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – qubits to apply dot product on (default: None). **Returns** True if Pauli’s commute, False if they anti-commute. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### compose Return the operator composition with another Pauli. **Parameters** * **other** ([*Pauli*](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")) – a Pauli object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, qubits to apply dot product on (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True update in-place (default: False). **Returns** The composed Pauli. **Return type** [Pauli](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while [`dot()`](#qiskit.quantum_info.Pauli.dot ""qiskit.quantum_info.Pauli.dot"") is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.Pauli.dot ""qiskit.quantum_info.Pauli.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate of each Pauli in the list. ### copy Make a deep copy of current operator. ### delete Return a Pauli with qubits deleted. **Parameters** **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – qubits to delete from Pauli. **Returns** the resulting Pauli with the specified qubits removed. **Return type** [Pauli](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if ind is out of bounds for the array size or number of qubits. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Pauli*](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, qubits to apply dot product on (default: None). * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True update in-place (default: False). **Returns** The operator self \* other. **Return type** [Pauli](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") ### equiv Return True if Pauli’s are equivalent up to group phase. **Parameters** **other** ([*Pauli*](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")) – an operator object. **Returns** True if the Pauli’s are equivalent up to group phase. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### evolve Performs either Heisenberg (default) or Schrödinger picture evolution of the Pauli by a Clifford and returns the evolved Pauli. Schrödinger picture evolution can be chosen by passing parameter `frame='s'`. This option yields a faster calculation. Heisenberg picture evolves the Pauli as $P^\prime = C^\dagger.P.C$. Schrödinger picture evolves the Pauli as $P^\prime = C.P.C^\dagger$. **Parameters** * **other** ([*Pauli*](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") *or*[*Clifford*](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – The Clifford operator to evolve by. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – a list of qubits to apply the Clifford to. * **frame** (*string*) – `'h'` for Heisenberg (default) or `'s'` for * **framework.** (*Schrödinger*) – **Returns** the Pauli $C^\dagger.P.C$ (Heisenberg picture) or the Pauli $C.P.C^\dagger$ (Schrödinger picture). **Return type** [Pauli](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the Clifford number of qubits and qargs don’t match. ### expand Return the reverse-order tensor product with another Pauli. **Parameters** **other** ([*Pauli*](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")) – a Pauli object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current Pauli, and $b$ is the other Pauli. **Return type** [Pauli](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") ### input\_dims Return tuple of input dimension for specified subsystems. ### insert Insert a Pauli at specific qubit value. **Parameters** * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – qubits index to insert at. * **value** ([*Pauli*](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")) – value to insert. **Returns** the resulting Pauli with the entries inserted. **Return type** [Pauli](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the insertion qubits are invalid. ### inverse Return the inverse of the Pauli. ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the compose of a operator with itself n times. **Parameters** **n** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of times to compose with self (n>0). **Returns** the n-times composed operator. **Return type** [Clifford](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the operator are not equal, or the power is not a positive integer. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### set\_truncation Set the max number of Pauli characters to display before truncation/ **Parameters** **val** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of characters. Truncation will be disabled if the truncation value is set to 0. ### tensor Return the tensor product with another Pauli. **Parameters** **other** ([*Pauli*](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")) – a Pauli object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current Pauli, and $b$ is the other Pauli. **Return type** [Pauli](#qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_instruction Convert to Pauli circuit instruction. ### to\_label Convert a Pauli to a string label. The difference between to\_label and `__str__()` is that the later will truncate the output for large numbers of qubits. **Returns** the Pauli string label. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### to\_matrix Convert to a Numpy array or sparse CSR matrix. **Parameters** **sparse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True return sparse CSR matrices, otherwise return dense Numpy arrays (default: False). **Returns** The Pauli matrix. **Return type** array ### transpose Return the transpose of each Pauli in the list. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.Pauli.mdx "--- title: PauliList description: API reference for qiskit.quantum_info.PauliList in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.PauliList --- # PauliList Bases: `BasePauli`, `LinearMixin`, `GroupMixin` List of N-qubit Pauli operators. This class is an efficient representation of a list of [`Pauli`](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") operators. It supports 1D numpy array indexing returning a [`Pauli`](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") for integer indexes or a [`PauliList`](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") for slice or list indices. **Initialization** A PauliList object can be initialized in several ways. > **`PauliList(list[str])`** > > where strings are same representation with [`Pauli`](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli""). > > **`PauliList(Pauli) and PauliList(list[Pauli])`** > > where Pauli is [`Pauli`](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli""). > > **`PauliList.from_symplectic(z, x, phase)`** > > where `z` and `x` are 2 dimensional boolean `numpy.ndarrays` and `phase` is an integer in `[0, 1, 2, 3]`. For example, ```python import numpy as np from qiskit.quantum_info import Pauli, PauliList # 1. init from list[str] pauli_list = PauliList([""II"", ""+ZI"", ""-iYY""]) print(""1. "", pauli_list) pauli1 = Pauli(""iXI"") pauli2 = Pauli(""iZZ"") # 2. init from Pauli print(""2. "", PauliList(pauli1)) # 3. init from list[Pauli] print(""3. "", PauliList([pauli1, pauli2])) # 4. init from np.ndarray z = np.array([[True, True], [False, False]]) x = np.array([[False, True], [True, False]]) phase = np.array([0, 1]) pauli_list = PauliList.from_symplectic(z, x, phase) print(""4. "", pauli_list) ``` ```python 1. ['II', 'ZI', '-iYY'] 2. ['iXI'] 3. ['iXI', 'iZZ'] 4. ['YZ', '-iIX'] ``` **Data Access** The individual Paulis can be accessed and updated using the `[]` operator which accepts integer, lists, or slices for selecting subsets of PauliList. If integer is given, it returns Pauli not PauliList. ```python pauli_list = PauliList([""XX"", ""ZZ"", ""IZ""]) print(""Integer: "", repr(pauli_list[1])) print(""List: "", repr(pauli_list[[0, 2]])) print(""Slice: "", repr(pauli_list[0:2])) ``` ```python Integer: Pauli('ZZ') List: PauliList(['XX', 'IZ']) Slice: PauliList(['XX', 'ZZ']) ``` **Iteration** Rows in the Pauli table can be iterated over like a list. Iteration can also be done using the label or matrix representation of each row using the [`label_iter()`](#qiskit.quantum_info.PauliList.label_iter ""qiskit.quantum_info.PauliList.label_iter"") and [`matrix_iter()`](#qiskit.quantum_info.PauliList.matrix_iter ""qiskit.quantum_info.PauliList.matrix_iter"") methods. Initialize the PauliList. **Parameters** **data** ([*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – input data for Paulis. If input is a list each item in the list must be a Pauli object or Pauli str. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input array is invalid shape. **Additional Information:** The input array is not copied so multiple Pauli tables can share the same underlying array. ## Attributes ### dim Return tuple (input\_shape, output\_shape). ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### phase Return the phase exponent of the PauliList. ### qargs Return the qargs for the operator. ### settings Return settings. ### shape The full shape of the `array()` ### size The number of Pauli rows in the table. ### x The x array for the symplectic representation. ### z The z array for the symplectic representation. ## Methods ### adjoint Return the adjoint of each Pauli in the list. ### anticommutes Return `True` if other Pauli that anticommutes with other. **Parameters** * **other** ([*PauliList*](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")) – another PauliList operator. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – qubits to apply dot product on (default: `None`). **Returns** `True` if Paulis anticommute, `False` if they commute. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### anticommutes\_with\_all Return indexes of rows that commute other. If `other` is a multi-row Pauli list the returned vector indexes rows of the current PauliList that anti-commute with *all* Paulis in other. If no rows satisfy the condition the returned array will be empty. **Parameters** **other** ([*PauliList*](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")) – a single Pauli or multi-row PauliList. **Returns** index array of the anti-commuting rows. **Return type** array ### argsort Return indices for sorting the rows of the table. The default sort method is lexicographic sorting by qubit number. By using the weight kwarg the output can additionally be sorted by the number of non-identity terms in the Pauli, where the set of all Paulis of a given weight are still ordered lexicographically. **Parameters** * **weight** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Optionally sort by weight if `True` (Default: `False`). * **phase** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Optionally sort by phase before weight or order (Default: `False`). **Returns** the indices for sorting the table. **Return type** array ### commutes Return True for each Pauli that commutes with other. **Parameters** * **other** ([*PauliList*](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")) – another PauliList operator. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – qubits to apply dot product on (default: `None`). **Returns** `True` if Paulis commute, `False` if they anti-commute. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### commutes\_with\_all Return indexes of rows that commute `other`. If `other` is a multi-row Pauli list the returned vector indexes rows of the current PauliList that commute with *all* Paulis in other. If no rows satisfy the condition the returned array will be empty. **Parameters** **other** ([*PauliList*](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")) – a single Pauli or multi-row PauliList. **Returns** index array of the commuting rows. **Return type** array ### compose Return the composition self∘other for each Pauli in the list. **Parameters** * **other** ([*PauliList*](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")) – another PauliList. * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – qubits to apply dot product on (Default: `None`). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True use dot composition method \[default: `False`]. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True` update in-place (default: `False`). **Returns** the list of composed Paulis. **Return type** [PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list, or has the wrong number of qubits for the specified `qargs`. ### conjugate Return the conjugate of each Pauli in the list. ### copy Make a deep copy of current operator. ### delete Return a copy with Pauli rows deleted from table. When deleting qubits the qubit index is the same as the column index of the underlying `X` and `Z` arrays. **Parameters** * **ind** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – index(es) to delete. * **qubit** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if `True` delete qubit columns, otherwise delete Pauli rows (Default: `False`). **Returns** the resulting table with the entries removed. **Return type** [PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if `ind` is out of bounds for the array size or number of qubits. ### dot Return the composition other∘self for each Pauli in the list. **Parameters** * **other** ([*PauliList*](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")) – another PauliList. * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – qubits to apply dot product on (Default: `None`). * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True update in-place (default: `False`). **Returns** the list of composed Paulis. **Return type** [PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list, or has the wrong number of qubits for the specified `qargs`. ### equiv Entrywise comparison of Pauli equivalence up to global phase. **Parameters** **other** ([*PauliList*](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") *or*[*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")) – a comparison object. **Returns** **An array of `True` or `False` for entrywise equivalence** of the current table. **Return type** np.ndarray ### evolve Performs either Heisenberg (default) or Schrödinger picture evolution of the Pauli by a Clifford and returns the evolved Pauli. Schrödinger picture evolution can be chosen by passing parameter `frame='s'`. This option yields a faster calculation. Heisenberg picture evolves the Pauli as $P^\prime = C^\dagger.P.C$. Schrödinger picture evolves the Pauli as $P^\prime = C.P.C^\dagger$. **Parameters** * **other** ([*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") *or*[*Clifford*](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – The Clifford operator to evolve by. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – a list of qubits to apply the Clifford to. * **frame** (*string*) – `'h'` for Heisenberg (default) or `'s'` for Schrödinger framework. **Returns** the Pauli $C^\dagger.P.C$ (Heisenberg picture) or the Pauli $C.P.C^\dagger$ (Schrödinger picture). **Return type** [PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the Clifford number of qubits and qargs don’t match. ### expand Return the expand product of each Pauli in the list. **Parameters** **other** ([*PauliList*](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")) – another PauliList. **Returns** the list of tensor product Paulis. **Return type** [PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list. ### from\_symplectic Construct a PauliList from a symplectic data. **Parameters** * **z** (*np.ndarray*) – 2D boolean Numpy array. * **x** (*np.ndarray*) – 2D boolean Numpy array. * **phase** (*np.ndarray or None*) – Optional, 1D integer array from Z\_4. **Returns** the constructed PauliList. **Return type** [PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") ### group\_commuting Partition a PauliList into sets of commuting Pauli strings. **Parameters** **qubit\_wise** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – whether the commutation rule is applied to the whole operator, or on a per-qubit basis. For example: ```python >>> from qiskit.quantum_info import PauliList >>> op = PauliList([""XX"", ""YY"", ""IZ"", ""ZZ""]) >>> op.group_commuting() [PauliList(['XX', 'YY']), PauliList(['IZ', 'ZZ'])] >>> op.group_commuting(qubit_wise=True) [PauliList(['XX']), PauliList(['YY']), PauliList(['IZ', 'ZZ'])] ``` **Returns** List of PauliLists where each PauliList contains commuting Pauli operators. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")] ### group\_qubit\_wise\_commuting Partition a PauliList into sets of mutually qubit-wise commuting Pauli strings. **Returns** List of PauliLists where each PauliList contains commutable Pauli operators. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")] ### input\_dims Return tuple of input dimension for specified subsystems. ### insert Insert Paulis into the table. When inserting qubits the qubit index is the same as the column index of the underlying `X` and `Z` arrays. **Parameters** * **ind** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – index to insert at. * **value** ([*PauliList*](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")) – values to insert. * **qubit** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if `True` insert qubit columns, otherwise insert Pauli rows (Default: `False`). **Returns** the resulting table with the entries inserted. **Return type** [PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the insertion index is invalid. ### inverse Return the inverse of each Pauli in the list. ### label\_iter Return a label representation iterator. This is a lazy iterator that converts each row into the string label only as it is used. To convert the entire table to labels use the [`to_labels()`](#qiskit.quantum_info.PauliList.to_labels ""qiskit.quantum_info.PauliList.to_labels"") method. **Returns** label iterator object for the PauliList. **Return type** LabelIterator ### matrix\_iter Return a matrix representation iterator. This is a lazy iterator that converts each row into the Pauli matrix representation only as it is used. To convert the entire table to matrices use the [`to_matrix()`](#qiskit.quantum_info.PauliList.to_matrix ""qiskit.quantum_info.PauliList.to_matrix"") method. **Parameters** **sparse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – optionally return sparse CSR matrices if `True`, otherwise return Numpy array matrices (Default: `False`) **Returns** matrix iterator object for the PauliList. **Return type** MatrixIterator ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the compose of a operator with itself n times. **Parameters** **n** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of times to compose with self (n>0). **Returns** the n-times composed operator. **Return type** [Clifford](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the operator are not equal, or the power is not a positive integer. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### sort Sort the rows of the table. The default sort method is lexicographic sorting by qubit number. By using the weight kwarg the output can additionally be sorted by the number of non-identity terms in the Pauli, where the set of all Paulis of a given weight are still ordered lexicographically. **Example** Consider sorting all a random ordering of all 2-qubit Paulis ```python from numpy.random import shuffle from qiskit.quantum_info.operators import PauliList # 2-qubit labels labels = ['II', 'IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ', 'YI', 'YX', 'YY', 'YZ', 'ZI', 'ZX', 'ZY', 'ZZ'] # Shuffle Labels shuffle(labels) pt = PauliList(labels) print('Initial Ordering') print(pt) # Lexicographic Ordering srt = pt.sort() print('Lexicographically sorted') print(srt) # Weight Ordering srt = pt.sort(weight=True) print('Weight sorted') print(srt) ``` ```python Initial Ordering ['YX', 'ZZ', 'XZ', 'YI', 'YZ', 'II', 'XX', 'XI', 'XY', 'YY', 'IX', 'IZ', 'ZY', 'ZI', 'ZX', 'IY'] Lexicographically sorted ['II', 'IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ', 'YI', 'YX', 'YY', 'YZ', 'ZI', 'ZX', 'ZY', 'ZZ'] Weight sorted ['II', 'IX', 'IY', 'IZ', 'XI', 'YI', 'ZI', 'XX', 'XY', 'XZ', 'YX', 'YY', 'YZ', 'ZX', 'ZY', 'ZZ'] ``` **Parameters** * **weight** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – optionally sort by weight if `True` (Default: `False`). * **phase** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Optionally sort by phase before weight or order (Default: `False`). **Returns** a sorted copy of the original table. **Return type** [PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") ### tensor Return the tensor product with each Pauli in the list. **Parameters** **other** ([*PauliList*](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")) – another PauliList. **Returns** the list of tensor product Paulis. **Return type** [PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list. ### to\_labels Convert a PauliList to a list Pauli string labels. For large PauliLists converting using the `array=True` kwarg will be more efficient since it allocates memory for the full Numpy array of labels in advance. | Label | Symplectic | Matrix | | ----- | ---------- | ----------------------------------------------- | | `""I""` | $[0, 0]$ | $\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}$ | | `""X""` | $[1, 0]$ | $\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$ | | `""Y""` | $[1, 1]$ | $\begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}$ | | `""Z""` | $[0, 1]$ | $\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}$ | **Parameters** **array** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – return a Numpy array if `True`, otherwise return a list (Default: `False`). **Returns** The rows of the PauliList in label form. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") or array ### to\_matrix Convert to a list or array of Pauli matrices. For large PauliLists converting using the `array=True` kwarg will be more efficient since it allocates memory a full rank-3 Numpy array of matrices in advance. | Label | Symplectic | Matrix | | ----- | ---------- | ----------------------------------------------- | | `""I""` | $[0, 0]$ | $\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}$ | | `""X""` | $[1, 0]$ | $\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$ | | `""Y""` | $[1, 1]$ | $\begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}$ | | `""Z""` | $[0, 1]$ | $\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}$ | **Parameters** * **sparse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if `True` return sparse CSR matrices, otherwise return dense Numpy arrays (Default: `False`). * **array** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – return as rank-3 numpy array if `True`, otherwise return a list of Numpy arrays (Default: `False`). **Returns** A list of dense Pauli matrices if ```array=False` and ``sparse=False`. list: A list of sparse Pauli matrices if ``array=False``` and `sparse=True`. array: A dense rank-3 array of Pauli matrices if `array=True`. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") ### transpose Return the transpose of each Pauli in the list. ### unique Return unique Paulis from the table. **Example** ```python from qiskit.quantum_info.operators import PauliList pt = PauliList(['X', 'Y', '-X', 'I', 'I', 'Z', 'X', 'iZ']) unique = pt.unique() print(unique) ``` ```python ['X', 'Y', '-X', 'I', 'Z', 'iZ'] ``` **Parameters** * **return\_index** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True`, also return the indices that result in the unique array. (Default: `False`) * **return\_counts** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True`, also return the number of times each unique item appears in the table. **Returns** **unique** the table of the unique rows. **unique\_indices: np.ndarray, optional** The indices of the first occurrences of the unique values in the original array. Only provided if `return_index` is `True`. **unique\_counts: np.array, optional** The number of times each of the unique values comes up in the original array. Only provided if `return_counts` is `True`. **Return type** [PauliList](#qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.PauliList.mdx "--- title: pauli_basis description: API reference for qiskit.quantum_info.pauli_basis in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.quantum_info.pauli_basis --- # qiskit.quantum\_info.pauli\_basis Return the ordered PauliList for the n-qubit Pauli basis. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubits * **weight** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True optionally return the basis sorted by Pauli weight rather than lexicographic order (Default: False) **Returns** the Paulis for the basis **Return type** [PauliList](qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.pauli_basis.mdx "--- title: PTM description: API reference for qiskit.quantum_info.PTM in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.PTM --- # PTM Bases: `QuantumChannel` Pauli Transfer Matrix (PTM) representation of a Quantum Channel. The PTM representation of an $n$-qubit quantum channel $\mathcal{E}$ is an $n$-qubit [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") $R$ defined with respect to vectorization in the Pauli basis instead of column-vectorization. The elements of the PTM $R$ are given by $$ R_{i,j} = \frac{1}{2^n} \mbox{Tr}\left[P_i \mathcal{E}(P_j) \right] $$ where $[P_0, P_1, ..., P_{4^{n}-1}]$ is the $n$-qubit Pauli basis in lexicographic order. Evolution of a [`DensityMatrix`](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") $\rho$ with respect to the PTM is given by $$ |\mathcal{E}(\rho)\rangle\!\rangle_P = S_P |\rho\rangle\!\rangle_P $$ where $|A\rangle\!\rangle_P$ denotes vectorization in the Pauli basis $\langle i | A\rangle\!\rangle_P = \sqrt{\frac{1}{2^n}} \mbox{Tr}[P_i A]$. See reference \[1] for further details. **References** 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). [arXiv:1111.6950 \[quant-ph\]](https://arxiv.org/abs/1111.6950) Initialize a PTM quantum channel operator. **Parameters** * **or** (*data (*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – Instruction or BaseOperator or matrix): data to initialize superoperator. * **input\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the input subsystem dimensions. \[Default: None] * **output\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the output subsystem dimensions. \[Default: None] **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data is not an N-qubit channel or cannot be initialized as a PTM. **Additional Information:** If the input or output dimensions are None, they will be automatically determined from the input data. The PTM representation is only valid for N-qubit channels. ## Attributes ### atol ### data Return data. ### dim Return tuple (input\_shape, output\_shape). ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### qargs Return the qargs for the operator. ### rtol ### settings Return settings. ## Methods ### adjoint Return the adjoint quantum channel. This is equivalent to the matrix Hermitian conjugate in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the adjoint channel $\mathcal{{E}}^\dagger$ is $S_{\mathcal{E}^\dagger} = S_{\mathcal{E}}^\dagger$. ### compose Return the operator composition with another PTM. **Parameters** * **other** ([*PTM*](#qiskit.quantum_info.PTM ""qiskit.quantum_info.PTM"")) – a PTM object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. **Returns** The composed PTM. **Return type** [PTM](#qiskit.quantum_info.PTM ""qiskit.quantum_info.PTM"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while `@` (equivalent to [`dot()`](#qiskit.quantum_info.PTM.dot ""qiskit.quantum_info.PTM.dot"")) is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B @ A == B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.PTM.dot ""qiskit.quantum_info.PTM.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate quantum channel. This is equivalent to the matrix complex conjugate in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the conjugate channel $\overline{{\mathcal{{E}}}}$ is $S_{\overline{\mathcal{E}^\dagger}} = \overline{S_{\mathcal{E}}}$. ### copy Make a deep copy of current operator. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). **Returns** The right matrix multiplied Operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The dot product can be obtained using the `@` binary operator. Hence `a.dot(b)` is equivalent to `a @ b`. ### expand Return the reverse-order tensor product with another PTM. **Parameters** **other** ([*PTM*](#qiskit.quantum_info.PTM ""qiskit.quantum_info.PTM"")) – a PTM object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current PTM, and $b$ is the other PTM. **Return type** [PTM](#qiskit.quantum_info.PTM ""qiskit.quantum_info.PTM"") ### input\_dims Return tuple of input dimension for specified subsystems. ### is\_cp Test if Choi-matrix is completely-positive (CP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_cptp Return True if completely-positive trace-preserving (CPTP). **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_tp Test if a channel is trace-preserving (TP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_unitary Return True if QuantumChannel is a unitary channel. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the power of the quantum channel. **Parameters** **n** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – the power exponent. **Returns** the channel $\mathcal{{E}} ^n$. **Return type** [SuperOp](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the SuperOp are not equal. For non-positive or non-integer exponents the power is defined as the matrix power of the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{{E}}$, the SuperOp of the powered channel $\mathcal{{E}}^\n$ is $S_{{\mathcal{{E}}^n}} = S_{{\mathcal{{E}}}}^n$. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### tensor Return the tensor product with another PTM. **Parameters** **other** ([*PTM*](#qiskit.quantum_info.PTM ""qiskit.quantum_info.PTM"")) – a PTM object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current PTM, and $b$ is the other PTM. **Return type** [PTM](#qiskit.quantum_info.PTM ""qiskit.quantum_info.PTM"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_instruction Convert to a Kraus or UnitaryGate circuit instruction. If the channel is unitary it will be added as a unitary gate, otherwise it will be added as a kraus simulator instruction. **Returns** A kraus instruction for the channel. **Return type** [qiskit.circuit.Instruction](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data is not an N-qubit CPTP quantum channel. ### to\_operator Try to convert channel to a unitary representation Operator. **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### transpose Return the transpose quantum channel. This is equivalent to the matrix transpose in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation, ie. for a channel $\mathcal{E}$, the SuperOp of the transpose channel $\mathcal{{E}}^T$ is $S_{mathcal{E}^T} = S_{\mathcal{E}}^T$. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.PTM.mdx "--- title: Quaternion description: API reference for qiskit.quantum_info.Quaternion in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.Quaternion --- # Quaternion Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A class representing a Quaternion. ## Methods ### from\_axis\_rotation Return quaternion for rotation about given axis. **Parameters** * **angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Angle in radians. * **axis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Axis for rotation **Returns** Quaternion for axis rotation. **Return type** [Quaternion](#qiskit.quantum_info.Quaternion ""qiskit.quantum_info.Quaternion"") **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – Invalid input axis. ### from\_euler Generate a quaternion from a set of Euler angles. **Parameters** * **angles** (*array\_like*) – Array of Euler angles. * **order** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Order of Euler rotations. ‘yzy’ is default. **Returns** Quaternion representation of Euler rotation. **Return type** [Quaternion](#qiskit.quantum_info.Quaternion ""qiskit.quantum_info.Quaternion"") ### norm Norm of quaternion. ### normalize Normalizes a Quaternion to unit length so that it represents a valid rotation. **Parameters** **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Do an inplace normalization. **Returns** Normalized quaternion. **Return type** [Quaternion](#qiskit.quantum_info.Quaternion ""qiskit.quantum_info.Quaternion"") ### to\_matrix Converts a unit-length quaternion to a rotation matrix. **Returns** Rotation matrix. **Return type** ndarray ### to\_zyz Converts a unit-length quaternion to a sequence of ZYZ Euler angles. **Returns** Array of Euler angles. **Return type** ndarray ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.Quaternion.mdx "--- title: ScalarOp description: API reference for qiskit.quantum_info.ScalarOp in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.ScalarOp --- # ScalarOp Bases: `LinearOp` Scalar identity operator class. This is a symbolic representation of an scalar identity operator on multiple subsystems. It may be used to initialize a symbolic scalar multiplication of an identity and then be implicitly converted to other kinds of operator subclasses by using the [`compose()`](#qiskit.quantum_info.ScalarOp.compose ""qiskit.quantum_info.ScalarOp.compose""), [`dot()`](#qiskit.quantum_info.ScalarOp.dot ""qiskit.quantum_info.ScalarOp.dot""), [`tensor()`](#qiskit.quantum_info.ScalarOp.tensor ""qiskit.quantum_info.ScalarOp.tensor""), [`expand()`](#qiskit.quantum_info.ScalarOp.expand ""qiskit.quantum_info.ScalarOp.expand"") methods. Initialize an operator object. **Parameters** * **dims** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – subsystem dimensions. * **coeff** (*Number*) – scalar coefficient for the identity operator (Default: 1). **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If the optional coefficient is invalid. ## Attributes ### atol ### coeff Return the coefficient ### dim Return tuple (input\_shape, output\_shape). ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### qargs Return the qargs for the operator. ### rtol ## Methods ### adjoint Return the adjoint of the Operator. **Return type** *Self* ### compose Return the operator composition with another ScalarOp. **Parameters** * **other** ([*ScalarOp*](#qiskit.quantum_info.ScalarOp ""qiskit.quantum_info.ScalarOp"")) – a ScalarOp object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. **Returns** The composed ScalarOp. **Return type** [ScalarOp](#qiskit.quantum_info.ScalarOp ""qiskit.quantum_info.ScalarOp"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while `@` (equivalent to [`dot()`](#qiskit.quantum_info.ScalarOp.dot ""qiskit.quantum_info.ScalarOp.dot"")) is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B @ A == B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.ScalarOp.dot ""qiskit.quantum_info.ScalarOp.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate of the ScalarOp. ### copy Make a deep copy of current operator. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). **Returns** The right matrix multiplied Operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The dot product can be obtained using the `@` binary operator. Hence `a.dot(b)` is equivalent to `a @ b`. ### expand Return the reverse-order tensor product with another ScalarOp. **Parameters** **other** ([*ScalarOp*](#qiskit.quantum_info.ScalarOp ""qiskit.quantum_info.ScalarOp"")) – a ScalarOp object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current ScalarOp, and $b$ is the other ScalarOp. **Return type** [ScalarOp](#qiskit.quantum_info.ScalarOp ""qiskit.quantum_info.ScalarOp"") ### input\_dims Return tuple of input dimension for specified subsystems. ### is\_unitary Return True if operator is a unitary matrix. ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the power of the ScalarOp. **Parameters** **n** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – the exponent for the scalar op. **Returns** the `coeff ** n` ScalarOp. **Return type** [ScalarOp](#qiskit.quantum_info.ScalarOp ""qiskit.quantum_info.ScalarOp"") ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### tensor Return the tensor product with another ScalarOp. **Parameters** **other** ([*ScalarOp*](#qiskit.quantum_info.ScalarOp ""qiskit.quantum_info.ScalarOp"")) – a ScalarOp object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current ScalarOp, and $b$ is the other ScalarOp. **Return type** [ScalarOp](#qiskit.quantum_info.ScalarOp ""qiskit.quantum_info.ScalarOp"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_matrix Convert to a Numpy matrix. ### to\_operator Convert to an Operator object. **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### transpose Return the transpose of the ScalarOp. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.ScalarOp.mdx "--- title: SparsePauliOp description: API reference for qiskit.quantum_info.SparsePauliOp in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.SparsePauliOp --- # SparsePauliOp Bases: `LinearOp` Sparse N-qubit operator in a Pauli basis representation. This is a sparse representation of an N-qubit matrix [`Operator`](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") in terms of N-qubit [`PauliList`](qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") and complex coefficients. It can be used for performing operator arithmetic for hundred of qubits if the number of non-zero Pauli basis terms is sufficiently small. The Pauli basis components are stored as a [`PauliList`](qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") object and can be accessed using the [`paulis`](#qiskit.quantum_info.SparsePauliOp.paulis ""qiskit.quantum_info.SparsePauliOp.paulis"") attribute. The coefficients are stored as a complex Numpy array vector and can be accessed using the [`coeffs`](#qiskit.quantum_info.SparsePauliOp.coeffs ""qiskit.quantum_info.SparsePauliOp.coeffs"") attribute. **Data type of coefficients** The default `dtype` of the internal `coeffs` Numpy array is `complex128`. Users can configure this by passing `np.ndarray` with a different dtype. For example, a parameterized [`SparsePauliOp`](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") can be made as follows: ```python >>> import numpy as np >>> from qiskit.circuit import ParameterVector >>> from qiskit.quantum_info import SparsePauliOp >>> SparsePauliOp([""II"", ""XZ""], np.array(ParameterVector(""a"", 2))) SparsePauliOp(['II', 'XZ'], coeffs=[ParameterExpression(1.0*a[0]), ParameterExpression(1.0*a[1])]) ``` Parameterized [`SparsePauliOp`](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") does not support the following methods: * `to_matrix(sparse=True)` since `scipy.sparse` cannot have objects as elements. * `to_operator()` since [`Operator`](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") does not support objects. * `sort`, `argsort` since [`ParameterExpression`](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") does not support comparison. * `equiv` since [`ParameterExpression`](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") cannot be converted into complex. * `chop` since [`ParameterExpression`](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") does not support absolute value. Initialize an operator object. **Parameters** * **data** ([*PauliList*](qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") *or*[*SparsePauliOp*](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") *or*[*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Pauli list of terms. A list of Pauli strings or a Pauli string is also allowed. * **coeffs** (*np.ndarray*) – complex coefficients for Pauli terms. If `data` is a [`SparsePauliOp`](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") and `coeffs` is not `None`, the value of the `SparsePauliOp.coeffs` will be ignored, and only the passed keyword argument `coeffs` will be used. * **ignore\_pauli\_phase** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if true, any `phase` component of a given [`PauliList`](qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") will be assumed to be zero. This is more efficient in cases where a [`PauliList`](qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") has been constructed purely for this object, and it is already known that the phases in the ZX-convention are zero. It only makes sense to pass this option when giving [`PauliList`](qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") data. (Default: False) * **copy** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – copy the input data if True, otherwise assign it directly, if possible. (Default: True) **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If the input data or coeffs are invalid. ## Attributes ### atol ### coeffs Return the Pauli coefficients. ### dim Return tuple (input\_shape, output\_shape). ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### parameters Return the free `Parameter`s in the coefficients. ### paulis Return the PauliList. ### qargs Return the qargs for the operator. ### rtol ### settings Return settings. ### size The number of Pauli of Pauli terms in the operator. ## Methods ### adjoint Return the adjoint of the Operator. ### apply\_layout Apply a transpiler layout to this [`SparsePauliOp`](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") **Parameters** * **layout** ([*TranspileLayout*](qiskit.transpiler.TranspileLayout ""qiskit.transpiler.TranspileLayout"") *| List\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None*) – Either a [`TranspileLayout`](qiskit.transpiler.TranspileLayout ""qiskit.transpiler.TranspileLayout""), a list of integers or None. If both layout and num\_qubits are none, a copy of the operator is returned. * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits to expand the operator to. If not provided then if `layout` is a [`TranspileLayout`](qiskit.transpiler.TranspileLayout ""qiskit.transpiler.TranspileLayout"") the number of the transpiler output circuit qubits will be used by default. If `layout` is a list of integers the permutation specified will be applied without any expansion. If layout is None, the operator will be expanded to the given number of qubits. **Returns** A new [`SparsePauliOp`](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") with the provided layout applied **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") ### argsort Return indices for sorting the rows of the table. Returns the composition of permutations in the order of sorting by coefficient and sorting by Pauli. By using the weight kwarg the output can additionally be sorted by the number of non-identity terms in the Pauli, where the set of all Pauli’s of a given weight are still ordered lexicographically. **Example** Here is an example of how to use SparsePauliOp argsort. ```python import numpy as np from qiskit.quantum_info import SparsePauliOp # 2-qubit labels labels = [""XX"", ""XX"", ""XX"", ""YI"", ""II"", ""XZ"", ""XY"", ""XI""] # coeffs coeffs = [2.+1.j, 2.+2.j, 3.+0.j, 3.+0.j, 4.+0.j, 5.+0.j, 6.+0.j, 7.+0.j] # init spo = SparsePauliOp(labels, coeffs) print('Initial Ordering') print(spo) # Lexicographic Ordering srt = spo.argsort() print('Lexicographically sorted') print(srt) # Lexicographic Ordering srt = spo.argsort(weight=False) print('Lexicographically sorted') print(srt) # Weight Ordering srt = spo.argsort(weight=True) print('Weight sorted') print(srt) ``` ```python Initial Ordering SparsePauliOp(['XX', 'XX', 'XX', 'YI', 'II', 'XZ', 'XY', 'XI'], coeffs=[2.+1.j, 2.+2.j, 3.+0.j, 3.+0.j, 4.+0.j, 5.+0.j, 6.+0.j, 7.+0.j]) Lexicographically sorted [4 7 0 1 2 6 5 3] Lexicographically sorted [4 7 0 1 2 6 5 3] Weight sorted [4 7 3 0 1 2 6 5] ``` **Parameters** * **weight** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – optionally sort by weight if True (Default: False). * **sorted** (*By using the weight kwarg the output can additionally be*) – * **Pauli.** (*by the number of non-identity terms in the*) – **Returns** the indices for sorting the table. **Return type** array ### assign\_parameters Bind the free `Parameter`s in the coefficients to provided values. **Parameters** * **parameters** (*Mapping\[*[*Parameter*](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")*,* [*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")*] | Sequence\[*[*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")*]*) – The values to bind the parameters to. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `False`, a copy of the operator with the bound parameters is returned. If `True` the operator itself is modified. **Returns** A copy of the operator with bound parameters, if `inplace` is `False`, otherwise `None`. **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") | None ### chop Set real and imaginary parts of the coefficients to 0 if `< tol` in magnitude. For example, the operator representing `1+1e-17j X + 1e-17 Y` with a tolerance larger than `1e-17` will be reduced to `1 X` whereas [`SparsePauliOp.simplify()`](#qiskit.quantum_info.SparsePauliOp.simplify ""qiskit.quantum_info.SparsePauliOp.simplify"") would return `1+1e-17j X`. If a both the real and imaginary part of a coefficient is 0 after chopping, the corresponding Pauli is removed from the operator. **Parameters** **tol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The absolute tolerance to check whether a real or imaginary part should be set to 0. **Returns** This operator with chopped coefficients. **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") ### compose Return the operator composition with another SparsePauliOp. **Parameters** * **other** ([*SparsePauliOp*](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"")) – a SparsePauliOp object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. **Returns** The composed SparsePauliOp. **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while `@` (equivalent to [`dot()`](#qiskit.quantum_info.SparsePauliOp.dot ""qiskit.quantum_info.SparsePauliOp.dot"")) is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B @ A == B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.SparsePauliOp.dot ""qiskit.quantum_info.SparsePauliOp.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate of the SparsePauliOp. ### copy Make a deep copy of current operator. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). **Returns** The right matrix multiplied Operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The dot product can be obtained using the `@` binary operator. Hence `a.dot(b)` is equivalent to `a @ b`. ### equiv Check if two SparsePauliOp operators are equivalent. **Parameters** * **other** ([*SparsePauliOp*](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"")) – an operator object. * **atol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – Absolute numerical tolerance for checking equivalence. **Returns** True if the operator is equivalent to `self`. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### expand Return the reverse-order tensor product with another SparsePauliOp. **Parameters** **other** ([*SparsePauliOp*](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"")) – a SparsePauliOp object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current SparsePauliOp, and $b$ is the other SparsePauliOp. **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") ### from\_list , *, num_qubits=None)"" modifiers=""static""> Construct from a list of Pauli strings and coefficients. For example, the 5-qubit Hamiltonian $$ H = Z_1 X_4 + 2 Y_0 Y_3 $$ can be constructed as ```python # via tuples and the full Pauli string op = SparsePauliOp.from_list([(""XIIZI"", 1), (""IYIIY"", 2)]) ``` **Parameters** * **obj** (*Iterable\[Tuple\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*,* [*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*]]*) – The list of 2-tuples specifying the Pauli terms. * **dtype** ([*type*](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"")) – The dtype of coeffs (Default: complex). * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits of the operator (Default: None). **Returns** The SparsePauliOp representation of the Pauli terms. **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If an empty list is passed and num\_qubits is None. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If num\_qubits and the objects in the input list do not match. ### from\_operator Construct from an Operator objector. Note that the cost of this construction is exponential in general because the number of possible Pauli terms in the decomposition is exponential in the number of qubits. Internally this uses an implementation of the “tensorized Pauli decomposition” presented in [Hantzko, Binkowski and Gupta (2023)](https://arxiv.org/abs/2310.13421). **Parameters** * **obj** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an N-qubit operator. * **atol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Optional. Absolute tolerance for checking if coefficients are zero (Default: 1e-8). Since the comparison is to zero, in effect the tolerance used is the maximum of `atol` and `rtol`. * **rtol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Optional. relative tolerance for checking if coefficients are zero (Default: 1e-5). Since the comparison is to zero, in effect the tolerance used is the maximum of `atol` and `rtol`. **Returns** the SparsePauliOp representation of the operator. **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input operator is not an N-qubit operator. ### from\_sparse\_list )"" modifiers=""static""> Construct from a list of local Pauli strings and coefficients. Each list element is a 3-tuple of a local Pauli string, indices where to apply it, and a coefficient. For example, the 5-qubit Hamiltonian $$ H = Z_1 X_4 + 2 Y_0 Y_3 $$ can be constructed as ```python # via triples and local Paulis with indices op = SparsePauliOp.from_sparse_list([(""ZX"", [1, 4], 1), (""YY"", [0, 3], 2)], num_qubits=5) # equals the following construction from ""dense"" Paulis op = SparsePauliOp.from_list([(""XIIZI"", 1), (""IYIIY"", 2)]) ``` **Parameters** * **obj** (*Iterable\[*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(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/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*],* [*complex*](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")*]]*) – The list 3-tuples specifying the Paulis. * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits of the operator. * **do\_checks** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – The flag of checking if the input indices are not duplicated * \*\*(\*\***Default** – True). * **dtype** ([*type*](https://docs.python.org/3/library/functions.html#type ""(in Python v3.12)"")) – The dtype of coeffs (Default: complex). **Returns** The SparsePauliOp representation of the Pauli terms. **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If the number of qubits is incompatible with the indices of the Pauli terms. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If the designated qubit is already assigned. ### group\_commuting Partition a SparsePauliOp into sets of commuting Pauli strings. **Parameters** **qubit\_wise** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – whether the commutation rule is applied to the whole operator, or on a per-qubit basis. For example: ```python >>> op = SparsePauliOp.from_list([(""XX"", 2), (""YY"", 1), (""IZ"",2j), (""ZZ"",1j)]) >>> op.group_commuting() [SparsePauliOp([""IZ"", ""ZZ""], coeffs=[0.+2.j, 0.+1j]), SparsePauliOp([""XX"", ""YY""], coeffs=[2.+0.j, 1.+0.j])] >>> op.group_commuting(qubit_wise=True) [SparsePauliOp(['XX'], coeffs=[2.+0.j]), SparsePauliOp(['YY'], coeffs=[1.+0.j]), SparsePauliOp(['IZ', 'ZZ'], coeffs=[0.+2.j, 0.+1.j])] ``` **Returns** **List of SparsePauliOp where each SparsePauliOp contains** commuting Pauli operators. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"")] ### input\_dims Return tuple of input dimension for specified subsystems. ### is\_unitary Return True if operator is a unitary matrix. **Parameters** * **atol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Optional. Absolute tolerance for checking if coefficients are zero (Default: 1e-8). * **rtol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Optional. relative tolerance for checking if coefficients are zero (Default: 1e-5). **Returns** True if the operator is unitary, False otherwise. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### label\_iter Return a label representation iterator. This is a lazy iterator that converts each term in the SparsePauliOp into a tuple (label, coeff). To convert the entire table to labels use the `to_labels()` method. **Returns** label iterator object for the SparsePauliOp. **Return type** LabelIterator ### matrix\_iter Return a matrix representation iterator. This is a lazy iterator that converts each term in the SparsePauliOp into a matrix as it is used. To convert to a single matrix use the [`to_matrix()`](#qiskit.quantum_info.SparsePauliOp.to_matrix ""qiskit.quantum_info.SparsePauliOp.to_matrix"") method. **Parameters** **sparse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – optionally return sparse CSR matrices if True, otherwise return Numpy array matrices (Default: False) **Returns** matrix iterator object for the PauliList. **Return type** MatrixIterator ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the compose of a operator with itself n times. **Parameters** **n** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of times to compose with self (n>0). **Returns** the n-times composed operator. **Return type** [Clifford](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the operator are not equal, or the power is not a positive integer. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### simplify Simplify PauliList by combining duplicates and removing zeros. **Parameters** * **atol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Optional. Absolute tolerance for checking if coefficients are zero (Default: 1e-8). * **rtol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Optional. relative tolerance for checking if coefficients are zero (Default: 1e-5). **Returns** the simplified SparsePauliOp operator. **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") ### sort Sort the rows of the table. After sorting the coefficients using numpy’s argsort, sort by Pauli. Pauli sort takes precedence. If Pauli is the same, it will be sorted by coefficient. By using the weight kwarg the output can additionally be sorted by the number of non-identity terms in the Pauli, where the set of all Pauli’s of a given weight are still ordered lexicographically. **Example** Here is an example of how to use SparsePauliOp sort. ```python import numpy as np from qiskit.quantum_info import SparsePauliOp # 2-qubit labels labels = [""XX"", ""XX"", ""XX"", ""YI"", ""II"", ""XZ"", ""XY"", ""XI""] # coeffs coeffs = [2.+1.j, 2.+2.j, 3.+0.j, 3.+0.j, 4.+0.j, 5.+0.j, 6.+0.j, 7.+0.j] # init spo = SparsePauliOp(labels, coeffs) print('Initial Ordering') print(spo) # Lexicographic Ordering srt = spo.sort() print('Lexicographically sorted') print(srt) # Lexicographic Ordering srt = spo.sort(weight=False) print('Lexicographically sorted') print(srt) # Weight Ordering srt = spo.sort(weight=True) print('Weight sorted') print(srt) ``` ```python Initial Ordering SparsePauliOp(['XX', 'XX', 'XX', 'YI', 'II', 'XZ', 'XY', 'XI'], coeffs=[2.+1.j, 2.+2.j, 3.+0.j, 3.+0.j, 4.+0.j, 5.+0.j, 6.+0.j, 7.+0.j]) Lexicographically sorted SparsePauliOp(['II', 'XI', 'XX', 'XX', 'XX', 'XY', 'XZ', 'YI'], coeffs=[4.+0.j, 7.+0.j, 2.+1.j, 2.+2.j, 3.+0.j, 6.+0.j, 5.+0.j, 3.+0.j]) Lexicographically sorted SparsePauliOp(['II', 'XI', 'XX', 'XX', 'XX', 'XY', 'XZ', 'YI'], coeffs=[4.+0.j, 7.+0.j, 2.+1.j, 2.+2.j, 3.+0.j, 6.+0.j, 5.+0.j, 3.+0.j]) Weight sorted SparsePauliOp(['II', 'XI', 'YI', 'XX', 'XX', 'XX', 'XY', 'XZ'], coeffs=[4.+0.j, 7.+0.j, 3.+0.j, 2.+1.j, 2.+2.j, 3.+0.j, 6.+0.j, 5.+0.j]) ``` **Parameters** * **weight** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – optionally sort by weight if True (Default: False). * **sorted** (*By using the weight kwarg the output can additionally be*) – * **Pauli.** (*by the number of non-identity terms in the*) – **Returns** a sorted copy of the original table. **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") ### sum Sum of SparsePauliOps. This is a specialized version of the builtin `sum` function for SparsePauliOp with smaller overhead. **Parameters** **ops** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*SparsePauliOp*](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"")*]*) – a list of SparsePauliOps. **Returns** the SparsePauliOp representing the sum of the input list. **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input list is empty. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input list includes an object that is not SparsePauliOp. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the numbers of qubits of the objects in the input list do not match. ### tensor Return the tensor product with another SparsePauliOp. **Parameters** **other** ([*SparsePauliOp*](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"")) – a SparsePauliOp object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current SparsePauliOp, and $b$ is the other SparsePauliOp. **Return type** [SparsePauliOp](#qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_list Convert to a list Pauli string labels and coefficients. For operators with a lot of terms converting using the `array=True` kwarg will be more efficient since it allocates memory for the full Numpy array of labels in advance. **Parameters** **array** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – return a Numpy array if True, otherwise return a list (Default: False). **Returns** List of pairs (label, coeff) for rows of the PauliList. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") or array ### to\_matrix Convert to a dense or sparse matrix. **Parameters** **sparse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True return a sparse CSR matrix, otherwise return dense Numpy array (Default: False). **Returns** A dense matrix if sparse=False. csr\_matrix: A sparse matrix in CSR format if sparse=True. **Return type** array ### to\_operator Convert to a matrix Operator object **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### transpose Return the transpose of the SparsePauliOp. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.SparsePauliOp.mdx "--- title: StabilizerState description: API reference for qiskit.quantum_info.StabilizerState in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.StabilizerState --- # StabilizerState Bases: `QuantumState` StabilizerState class. Stabilizer simulator using the convention from reference \[1]. Based on the internal class [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford""). ```python from qiskit import QuantumCircuit from qiskit.quantum_info import StabilizerState, Pauli # Bell state generation circuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) stab = StabilizerState(qc) # Print the StabilizerState print(stab) # Calculate the StabilizerState measurement probabilities dictionary print (stab.probabilities_dict()) # Calculate expectation value of the StabilizerState print (stab.expectation_value(Pauli('ZZ'))) ``` ```python StabilizerState(StabilizerTable: ['+XX', '+ZZ']) {'00': 0.5, '11': 0.5} 1 ``` Given a list of stabilizers, [`qiskit.quantum_info.StabilizerState.from_stabilizer_list()`](#qiskit.quantum_info.StabilizerState.from_stabilizer_list ""qiskit.quantum_info.StabilizerState.from_stabilizer_list"") returns a state stabilized by the list ```python from qiskit.quantum_info import StabilizerState stabilizer_list = [""ZXX"", ""-XYX"", ""+ZYY""] stab = StabilizerState.from_stabilizer_list(stabilizer_list) ``` **References** 1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). [arXiv:quant-ph/0406196](https://arxiv.org/abs/quant-ph/0406196) Initialize a StabilizerState object. **Parameters** * **or** (*data (*[*StabilizerState*](#qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.StabilizerState"") *or*[*Clifford*](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") *or*[*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – qiskit.circuit.Instruction): Data from which the stabilizer state can be constructed. * **validate** (*boolean*) – validate that the stabilizer state data is a valid Clifford. ## Attributes ### clifford Return StabilizerState Clifford data ### dim Return total state dimension. ### num\_qubits Return the number of qubits if a N-qubit state or None otherwise. ## Methods ### conjugate Return the conjugate of the operator. ### copy Make a copy of current operator. ### dims Return tuple of input dimension for specified subsystems. ### equiv Return True if the two generating sets generate the same stabilizer group. **Parameters** **other** ([*StabilizerState*](#qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.StabilizerState"")) – another StabilizerState. **Returns** True if other has a generating set that generates the same StabilizerState. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### evolve Evolve a stabilizer state by a Clifford operator. **Parameters** * **other** ([*Clifford*](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")) – The Clifford operator to evolve by. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – a list of stabilizer subsystem positions to apply the operator on. **Returns** the output stabilizer state. **Return type** [StabilizerState](#qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.StabilizerState"") **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other is not a StabilizerState. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the operator dimension does not match the specified StabilizerState subsystem dimensions. ### expand Return the tensor product stabilizer state other ⊗ self. **Parameters** **other** ([*StabilizerState*](#qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.StabilizerState"")) – a stabilizer state object. **Returns** the tensor product operator other ⊗ self. **Return type** [StabilizerState](#qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.StabilizerState"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other is not a StabilizerState. ### expectation\_value Compute the expectation value of a Pauli operator. **Parameters** * **oper** ([*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")) – a Pauli operator to evaluate expval. * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to apply the operator on. **Returns** the expectation value (only 0 or 1 or -1 or i or -i). **Return type** [complex](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if oper is not a Pauli operator. ### from\_stabilizer\_list Create a stabilizer state from the collection of stabilizers. **Parameters** * **stabilizers** (*Collection\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – list of stabilizer strings * **allow\_redundant** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – allow redundant stabilizers (i.e., some stabilizers can be products of the others) * **allow\_underconstrained** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – allow underconstrained set of stabilizers (i.e., the stabilizers do not specify a unique state) **Returns** a state stabilized by stabilizers. **Return type** [StabilizerState](#qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.StabilizerState"") ### is\_valid Return True if a valid StabilizerState. ### measure Measure subsystems and return outcome and post-measure state. Note that this function uses the QuantumStates internal random number generator for sampling the measurement outcome. The RNG seed can be set using the [`seed()`](#qiskit.quantum_info.StabilizerState.seed ""qiskit.quantum_info.StabilizerState.seed"") method. **Parameters** **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). **Returns** **the pair `(outcome, state)` where `outcome` is the** measurement outcome string label, and `state` is the collapsed post-measurement stabilizer state for the corresponding outcome. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") ### probabilities Return the subsystem measurement probability vector. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. **Parameters** * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to return probabilities for, if None return for all subsystems (Default: None). * **decimals** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of decimal places to round values. If None no rounding is done (Default: None). **Returns** The Numpy vector array of probabilities. **Return type** np.array ### probabilities\_dict Return the subsystem measurement probability dictionary. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. **Parameters** * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to return probabilities for, if None return for all subsystems (Default: None). * **decimals** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of decimal places to round values. If None no rounding is done (Default: None). **Returns** The measurement probabilities in dict (ket) form. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ### purity Return the purity of the quantum state, which equals to 1, since it is always a pure state. **Returns** the purity (should equal 1). **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input is not a StabilizerState. ### reset Reset state or subsystems to the 0-state. **Parameters** **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – subsystems to reset, if None all subsystems will be reset to their 0-state (Default: None). **Returns** the reset state. **Return type** [StabilizerState](#qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.StabilizerState"") **Additional Information:** If all subsystems are reset this will return the ground state on all subsystems. If only some subsystems are reset this function will perform a measurement on those subsystems and evolve the subsystems so that the collapsed post-measurement states are rotated to the 0-state. The RNG seed for this sampling can be set using the [`seed()`](#qiskit.quantum_info.StabilizerState.seed ""qiskit.quantum_info.StabilizerState.seed"") method. ### sample\_counts Sample a dict of qubit measurement outcomes in the computational basis. **Parameters** * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of samples to generate. * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). **Returns** sampled counts dictionary. **Return type** [Counts](qiskit.result.Counts ""qiskit.result.Counts"") Additional Information: > This function *samples* measurement outcomes using the measure [`probabilities()`](#qiskit.quantum_info.StabilizerState.probabilities ""qiskit.quantum_info.StabilizerState.probabilities"") for the current state and qargs. It does not actually implement the measurement so the current state is not modified. > > The seed for random number generator used for sampling can be set to a fixed value by using the stats [`seed()`](#qiskit.quantum_info.StabilizerState.seed ""qiskit.quantum_info.StabilizerState.seed"") method. ### sample\_memory Sample a list of qubit measurement outcomes in the computational basis. **Parameters** * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of samples to generate. * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). **Returns** list of sampled counts if the order sampled. **Return type** np.array Additional Information: > This function implements the measurement [`measure()`](#qiskit.quantum_info.StabilizerState.measure ""qiskit.quantum_info.StabilizerState.measure"") method. > > The seed for random number generator used for sampling can be set to a fixed value by using the stats [`seed()`](#qiskit.quantum_info.StabilizerState.seed ""qiskit.quantum_info.StabilizerState.seed"") method. ### seed Set the seed for the quantum state RNG. ### tensor Return the tensor product stabilizer state self ⊗ other. **Parameters** **other** ([*StabilizerState*](#qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.StabilizerState"")) – a stabilizer state object. **Returns** the tensor product operator self ⊗ other. **Return type** [StabilizerState](#qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.StabilizerState"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other is not a StabilizerState. ### to\_operator Convert state to matrix operator class **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### trace Return the trace of the stabilizer state as a density matrix, which equals to 1, since it is always a pure state. **Returns** the trace (should equal 1). **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input is not a StabilizerState. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.StabilizerState.mdx "--- title: Statevector description: API reference for qiskit.quantum_info.Statevector in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.Statevector --- # Statevector Bases: `QuantumState`, `TolerancesMixin` Statevector class Initialize a statevector object. **Parameters** * **or** (*data (np.array or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or*[*Statevector*](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – qiskit.circuit.Instruction): Data from which the statevector can be constructed. This can be either a complex vector, another statevector, a `Operator` with only one column or a `QuantumCircuit` or `Instruction`. If the data is a circuit or instruction, the statevector is constructed by assuming that all qubits are initialized to the zero state. * **dims** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – Optional. The subsystem dimension of the state (See additional information). **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data is not valid. **Additional Information:** The `dims` kwarg can be None, an integer, or an iterable of integers. * `Iterable` – the subsystem dimensions are the values in the list with the total number of subsystems given by the length of the list. * `Int` or `None` – the length of the input vector specifies the total dimension of the density matrix. If it is a power of two the state will be initialized as an N-qubit state. If it is not a power of two the state will have a single d-dimensional subsystem. ## Attributes ### atol ### data Return data. ### dim Return total state dimension. ### num\_qubits Return the number of qubits if a N-qubit state or None otherwise. ### rtol ### settings Return settings. ## Methods ### conjugate Return the conjugate of the operator. **Return type** [*Statevector*](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.states.statevector.Statevector"") ### copy Make a copy of current operator. ### dims Return tuple of input dimension for specified subsystems. ### draw Return a visualization of the Statevector. **repr**: ASCII TextMatrix of the state’s `__repr__`. **text**: ASCII TextMatrix that can be printed in the console. **latex**: An IPython Latex object for displaying in Jupyter Notebooks. **latex\_source**: Raw, uncompiled ASCII source to generate array using LaTeX. **qsphere**: Matplotlib figure, rendering of statevector using plot\_state\_qsphere(). **hinton**: Matplotlib figure, rendering of statevector using plot\_state\_hinton(). **bloch**: Matplotlib figure, rendering of statevector using plot\_bloch\_multivector(). **city**: Matplotlib figure, rendering of statevector using plot\_state\_city(). **paulivec**: Matplotlib figure, rendering of statevector using plot\_state\_paulivec(). **Parameters** * **output** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Select the output method to use for drawing the state. Valid choices are repr, text, latex, latex\_source, qsphere, hinton, bloch, city, or paulivec. Default is repr. Default can be changed by adding the line `state_drawer = ` to `~/.qiskit/settings.conf` under `[default]`. * **drawer\_args** – Arguments to be passed directly to the relevant drawing function or constructor (TextMatrix(), array\_to\_latex(), plot\_state\_qsphere(), plot\_state\_hinton() or plot\_bloch\_multivector()). See the relevant function under qiskit.visualization for that function’s documentation. **Returns** `matplotlib.Figure` or [`str`](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") or `TextMatrix` or `IPython.display.Latex`: Drawing of the Statevector. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – when an invalid output method is selected. **Examples** Plot one of the Bell states ```python from numpy import sqrt from qiskit.quantum_info import Statevector sv=Statevector([1/sqrt(2), 0, 0, -1/sqrt(2)]) sv.draw(output='hinton') ``` ![../\_images/qiskit-quantum\_info-Statevector-1.png](/images/api/qiskit/1.0/qiskit-quantum_info-Statevector-1.png) ### equiv Return True if other is equivalent as a statevector up to global phase. If other is not a Statevector, but can be used to initialize a statevector object, this will check that Statevector(other) is equivalent to the current statevector up to global phase. **Parameters** * **other** ([*Statevector*](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"")) – an object from which a `Statevector` can be constructed. * **rtol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – relative tolerance value for comparison. * **atol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – absolute tolerance value for comparison. **Returns** True if statevectors are equivalent up to global phase. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### evolve Evolve a quantum state by the operator. **Parameters** * **other** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") *|*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *|*[*circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")) – The operator to evolve by. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – a list of Statevector subsystem positions to apply the operator on. **Returns** the output quantum state. **Return type** [Statevector](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the operator dimension does not match the specified Statevector subsystem dimensions. ### expand Return the tensor product state other ⊗ self. **Parameters** **other** ([*Statevector*](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"")) – a quantum state object. **Returns** the tensor product state other ⊗ self. **Return type** [Statevector](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other is not a quantum state. ### expectation\_value Compute the expectation value of an operator. **Parameters** * **oper** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator to evaluate expval of. * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to apply operator on. **Returns** the expectation value. **Return type** [complex](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"") ### from\_instruction Return the output statevector of an instruction. The statevector is initialized in the state $|{0,\ldots,0}\rangle$ of the same number of qubits as the input instruction or circuit, evolved by the input instruction, and the output statevector returned. **Parameters** **instruction** ([*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – instruction or circuit **Returns** The final statevector. **Return type** [Statevector](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the instruction contains invalid instructions for the statevector simulation. ### from\_int Return a computational basis statevector. **Parameters** * **i** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the basis state element. * **dims** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The subsystem dimensions of the statevector (See additional information). **Returns** The computational basis state $|i\rangle$. **Return type** [Statevector](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") **Additional Information:** The `dims` kwarg can be an integer or an iterable of integers. * `Iterable` – the subsystem dimensions are the values in the list with the total number of subsystems given by the length of the list. * `Int` – the integer specifies the total dimension of the state. If it is a power of two the state will be initialized as an N-qubit state. If it is not a power of two the state will have a single d-dimensional subsystem. ### from\_label Return a tensor product of Pauli X,Y,Z eigenstates. | Label | Statevector | | ----- | ------------------------------- | | `""0""` | $[1, 0]$ | | `""1""` | $[0, 1]$ | | `""+""` | $[1 / \sqrt{2}, 1 / \sqrt{2}]$ | | `""-""` | $[1 / \sqrt{2}, -1 / \sqrt{2}]$ | | `""r""` | $[1 / \sqrt{2}, i / \sqrt{2}]$ | | `""l""` | $[1 / \sqrt{2}, -i / \sqrt{2}]$ | **Parameters** **label** (*string*) – a eigenstate string ket label (see table for allowed values). **Returns** The N-qubit basis state density matrix. **Return type** [Statevector](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the label contains invalid characters, or the length of the label is larger than an explicitly specified num\_qubits. ### inner Return the inner product of self and other as $\langle self| other \rangle$. **Parameters** **other** ([*Statevector*](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"")) – a quantum state object. **Returns** the inner product of self and other, $\langle self| other \rangle$. **Return type** np.complex128 **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other is not a quantum state or has different dimension. ### is\_valid Return True if a Statevector has norm 1. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### measure Measure subsystems and return outcome and post-measure state. Note that this function uses the QuantumStates internal random number generator for sampling the measurement outcome. The RNG seed can be set using the [`seed()`](#qiskit.quantum_info.Statevector.seed ""qiskit.quantum_info.Statevector.seed"") method. **Parameters** **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). **Returns** **the pair `(outcome, state)` where `outcome` is the** measurement outcome string label, and `state` is the collapsed post-measurement state for the corresponding outcome. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") ### probabilities Return the subsystem measurement probability vector. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. **Parameters** * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to return probabilities for, if None return for all subsystems (Default: None). * **decimals** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of decimal places to round values. If None no rounding is done (Default: None). **Returns** The Numpy vector array of probabilities. **Return type** np.array **Examples** Consider a 2-qubit product state $|\psi\rangle=|+\rangle\otimes|0\rangle$. ```python from qiskit.quantum_info import Statevector psi = Statevector.from_label('+0') # Probabilities for measuring both qubits probs = psi.probabilities() print('probs: {}'.format(probs)) # Probabilities for measuring only qubit-0 probs_qubit_0 = psi.probabilities([0]) print('Qubit-0 probs: {}'.format(probs_qubit_0)) # Probabilities for measuring only qubit-1 probs_qubit_1 = psi.probabilities([1]) print('Qubit-1 probs: {}'.format(probs_qubit_1)) ``` ```python probs: [0.5 0. 0.5 0. ] Qubit-0 probs: [1. 0.] Qubit-1 probs: [0.5 0.5] ``` We can also permute the order of qubits in the `qargs` list to change the qubit position in the probabilities output ```python from qiskit.quantum_info import Statevector psi = Statevector.from_label('+0') # Probabilities for measuring both qubits probs = psi.probabilities([0, 1]) print('probs: {}'.format(probs)) # Probabilities for measuring both qubits # but swapping qubits 0 and 1 in output probs_swapped = psi.probabilities([1, 0]) print('Swapped probs: {}'.format(probs_swapped)) ``` ```python probs: [0.5 0. 0.5 0. ] Swapped probs: [0.5 0.5 0. 0. ] ``` ### probabilities\_dict Return the subsystem measurement probability dictionary. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. **Parameters** * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to return probabilities for, if None return for all subsystems (Default: None). * **decimals** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of decimal places to round values. If None no rounding is done (Default: None). **Returns** The measurement probabilities in dict (ket) form. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ### purity Return the purity of the quantum state. **Return type** *float64* ### reset Reset state or subsystems to the 0-state. **Parameters** **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – subsystems to reset, if None all subsystems will be reset to their 0-state (Default: None). **Returns** the reset state. **Return type** [Statevector](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") **Additional Information:** If all subsystems are reset this will return the ground state on all subsystems. If only a some subsystems are reset this function will perform a measurement on those subsystems and evolve the subsystems so that the collapsed post-measurement states are rotated to the 0-state. The RNG seed for this sampling can be set using the [`seed()`](#qiskit.quantum_info.Statevector.seed ""qiskit.quantum_info.Statevector.seed"") method. ### reverse\_qargs Return a Statevector with reversed subsystem ordering. For a tensor product state this is equivalent to reversing the order of tensor product subsystems. For a statevector $|\psi \rangle = |\psi_{n-1} \rangle \otimes ... \otimes |\psi_0 \rangle$ the returned statevector will be $|\psi_{0} \rangle \otimes ... \otimes |\psi_{n-1} \rangle$. **Returns** the Statevector with reversed subsystem order. **Return type** [Statevector](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") ### sample\_counts Sample a dict of qubit measurement outcomes in the computational basis. **Parameters** * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of samples to generate. * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). **Returns** sampled counts dictionary. **Return type** [Counts](qiskit.result.Counts ""qiskit.result.Counts"") Additional Information: > This function *samples* measurement outcomes using the measure [`probabilities()`](#qiskit.quantum_info.Statevector.probabilities ""qiskit.quantum_info.Statevector.probabilities"") for the current state and qargs. It does not actually implement the measurement so the current state is not modified. > > The seed for random number generator used for sampling can be set to a fixed value by using the stats [`seed()`](#qiskit.quantum_info.Statevector.seed ""qiskit.quantum_info.Statevector.seed"") method. ### sample\_memory Sample a list of qubit measurement outcomes in the computational basis. **Parameters** * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of samples to generate. * **qargs** (*None or* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). **Returns** list of sampled counts if the order sampled. **Return type** np.array Additional Information: > This function *samples* measurement outcomes using the measure [`probabilities()`](#qiskit.quantum_info.Statevector.probabilities ""qiskit.quantum_info.Statevector.probabilities"") for the current state and qargs. It does not actually implement the measurement so the current state is not modified. > > The seed for random number generator used for sampling can be set to a fixed value by using the stats [`seed()`](#qiskit.quantum_info.Statevector.seed ""qiskit.quantum_info.Statevector.seed"") method. ### seed Set the seed for the quantum state RNG. ### tensor Return the tensor product state self ⊗ other. **Parameters** **other** ([*Statevector*](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"")) – a quantum state object. **Returns** the tensor product operator self ⊗ other. **Return type** [Statevector](#qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other is not a quantum state. ### to\_dict Convert the statevector to dictionary form. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. **Parameters** **decimals** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of decimal places to round values. If None no rounding is done (Default: None). **Returns** the dictionary form of the Statevector. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") **Example** The ket-form of a 2-qubit statevector $|\psi\rangle = |-\rangle\otimes |0\rangle$ ```python from qiskit.quantum_info import Statevector psi = Statevector.from_label('-0') print(psi.to_dict()) ``` ```python {'00': (0.7071067811865475+0j), '10': (-0.7071067811865475+0j)} ``` For non-qubit subsystems the integer range can go from 0 to 9. For example in a qutrit system ```python import numpy as np from qiskit.quantum_info import Statevector vec = np.zeros(9) vec[0] = 1 / np.sqrt(2) vec[-1] = 1 / np.sqrt(2) psi = Statevector(vec, dims=(3, 3)) print(psi.to_dict()) ``` ```python {'00': (0.7071067811865475+0j), '22': (0.7071067811865475+0j)} ``` For large subsystem dimensions delimiters are required. The following example is for a 20-dimensional system consisting of a qubit and 10-dimensional qudit. ```python import numpy as np from qiskit.quantum_info import Statevector vec = np.zeros(2 * 10) vec[0] = 1 / np.sqrt(2) vec[-1] = 1 / np.sqrt(2) psi = Statevector(vec, dims=(2, 10)) print(psi.to_dict()) ``` ```python {'00': (0.7071067811865475+0j), '91': (0.7071067811865475+0j)} ``` ### to\_operator Convert state to a rank-1 projector operator **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### trace Return the trace of the quantum state as a density matrix. **Return type** *float64* ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.Statevector.mdx "--- title: Stinespring description: API reference for qiskit.quantum_info.Stinespring in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.Stinespring --- # Stinespring Bases: `QuantumChannel` Stinespring representation of a quantum channel. The Stinespring representation of a quantum channel $\mathcal{E}$ is a rectangular matrix $A$ such that the evolution of a [`DensityMatrix`](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") $\rho$ is given by $$ \mathcal{E}(ρ) = \mbox{Tr}_2\left[A ρ A^\dagger\right] $$ where $\mbox{Tr}_2$ is the [`partial_trace()`](quantum_info#qiskit.quantum_info.partial_trace ""qiskit.quantum_info.partial_trace"") over subsystem 2. A general operator map $\mathcal{G}$ can also be written using the generalized Stinespring representation which is given by two matrices $A$, $B$ such that $$ \mathcal{G}(ρ) = \mbox{Tr}_2\left[A ρ B^\dagger\right] $$ See reference \[1] for further details. **References** 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). [arXiv:1111.6950 \[quant-ph\]](https://arxiv.org/abs/1111.6950) Initialize a quantum channel Stinespring operator. **Parameters** * **or** (*data (*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – Instruction or BaseOperator or matrix): data to initialize superoperator. * **input\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the input subsystem dimensions. \[Default: None] * **output\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the output subsystem dimensions. \[Default: None] **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data cannot be initialized as a a list of Kraus matrices. **Additional Information:** If the input or output dimensions are None, they will be automatically determined from the input data. This can fail for the Stinespring operator if the output dimension cannot be automatically determined. ## Attributes ### atol ### data ### dim Return tuple (input\_shape, output\_shape). ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### qargs Return the qargs for the operator. ### rtol ### settings Return settings. ## Methods ### adjoint Return the adjoint quantum channel. This is equivalent to the matrix Hermitian conjugate in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the adjoint channel $\mathcal{{E}}^\dagger$ is $S_{\mathcal{E}^\dagger} = S_{\mathcal{E}}^\dagger$. **Return type** *Self* ### compose Return the operator composition with another Stinespring. **Parameters** * **other** ([*Stinespring*](#qiskit.quantum_info.Stinespring ""qiskit.quantum_info.Stinespring"")) – a Stinespring object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. **Returns** The composed Stinespring. **Return type** [Stinespring](#qiskit.quantum_info.Stinespring ""qiskit.quantum_info.Stinespring"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while `@` (equivalent to [`dot()`](#qiskit.quantum_info.Stinespring.dot ""qiskit.quantum_info.Stinespring.dot"")) is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B @ A == B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.Stinespring.dot ""qiskit.quantum_info.Stinespring.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate quantum channel. This is equivalent to the matrix complex conjugate in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the conjugate channel $\overline{{\mathcal{{E}}}}$ is $S_{\overline{\mathcal{E}^\dagger}} = \overline{S_{\mathcal{E}}}$. ### copy Make a deep copy of current operator. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). **Returns** The right matrix multiplied Operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The dot product can be obtained using the `@` binary operator. Hence `a.dot(b)` is equivalent to `a @ b`. ### expand Return the reverse-order tensor product with another Stinespring. **Parameters** **other** ([*Stinespring*](#qiskit.quantum_info.Stinespring ""qiskit.quantum_info.Stinespring"")) – a Stinespring object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current Stinespring, and $b$ is the other Stinespring. **Return type** [Stinespring](#qiskit.quantum_info.Stinespring ""qiskit.quantum_info.Stinespring"") ### input\_dims Return tuple of input dimension for specified subsystems. ### is\_cp Test if Choi-matrix is completely-positive (CP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_cptp Return True if completely-positive trace-preserving. ### is\_tp Test if a channel is trace-preserving (TP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_unitary Return True if QuantumChannel is a unitary channel. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the power of the quantum channel. **Parameters** **n** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – the power exponent. **Returns** the channel $\mathcal{{E}} ^n$. **Return type** [SuperOp](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the SuperOp are not equal. For non-positive or non-integer exponents the power is defined as the matrix power of the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{{E}}$, the SuperOp of the powered channel $\mathcal{{E}}^\n$ is $S_{{\mathcal{{E}}^n}} = S_{{\mathcal{{E}}}}^n$. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### tensor Return the tensor product with another Stinespring. **Parameters** **other** ([*Stinespring*](#qiskit.quantum_info.Stinespring ""qiskit.quantum_info.Stinespring"")) – a Stinespring object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current Stinespring, and $b$ is the other Stinespring. **Return type** [Stinespring](#qiskit.quantum_info.Stinespring ""qiskit.quantum_info.Stinespring"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_instruction Convert to a Kraus or UnitaryGate circuit instruction. If the channel is unitary it will be added as a unitary gate, otherwise it will be added as a kraus simulator instruction. **Returns** A kraus instruction for the channel. **Return type** [qiskit.circuit.Instruction](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data is not an N-qubit CPTP quantum channel. ### to\_operator Try to convert channel to a unitary representation Operator. **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### transpose Return the transpose quantum channel. This is equivalent to the matrix transpose in the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation, ie. for a channel $\mathcal{E}$, the SuperOp of the transpose channel $\mathcal{{E}}^T$ is $S_{mathcal{E}^T} = S_{\mathcal{E}}^T$. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.Stinespring.mdx "--- title: SuperOp description: API reference for qiskit.quantum_info.SuperOp in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.SuperOp --- # SuperOp Bases: `QuantumChannel` Superoperator representation of a quantum channel. The Superoperator representation of a quantum channel $\mathcal{E}$ is a matrix $S$ such that the evolution of a [`DensityMatrix`](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") $\rho$ is given by $$ |\mathcal{E}(\rho)\rangle\!\rangle = S |\rho\rangle\!\rangle $$ where the double-ket notation $|A\rangle\!\rangle$ denotes a vector formed by stacking the columns of the matrix $A$ *(column-vectorization)*. See reference \[1] for further details. **References** 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). [arXiv:1111.6950 \[quant-ph\]](https://arxiv.org/abs/1111.6950) Initialize a quantum channel Superoperator operator. **Parameters** * **or** (*data (*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – Instruction or BaseOperator or matrix): data to initialize superoperator. * **input\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the input subsystem dimensions. \[Default: None] * **output\_dims** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the output subsystem dimensions. \[Default: None] **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data cannot be initialized as a superoperator. **Additional Information:** If the input or output dimensions are None, they will be automatically determined from the input data. If the input data is a Numpy array of shape (4\*\*N, 4\*\*N) qubit systems will be used. If the input operator is not an N-qubit operator, it will assign a single subsystem with dimension specified by the shape of the input. ## Attributes ### atol ### data Return data. ### dim Return tuple (input\_shape, output\_shape). ### num\_qubits Return the number of qubits if a N-qubit operator or None otherwise. ### qargs Return the qargs for the operator. ### rtol ### settings Return settings. ## Methods ### adjoint Return the adjoint quantum channel. This is equivalent to the matrix Hermitian conjugate in the [`SuperOp`](#qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the adjoint channel $\mathcal{{E}}^\dagger$ is $S_{\mathcal{E}^\dagger} = S_{\mathcal{E}}^\dagger$. ### compose Return the operator composition with another SuperOp. **Parameters** * **other** ([*SuperOp*](#qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"")) – a SuperOp object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). * **front** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True compose using right operator multiplication, instead of left multiplication \[default: False]. **Returns** The composed SuperOp. **Return type** [SuperOp](#qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. Composition (`&`) by default is defined as left matrix multiplication for matrix operators, while `@` (equivalent to [`dot()`](#qiskit.quantum_info.SuperOp.dot ""qiskit.quantum_info.SuperOp.dot"")) is defined as right matrix multiplication. That is that `A & B == A.compose(B)` is equivalent to `B @ A == B.dot(A)` when `A` and `B` are of the same type. Setting the `front=True` kwarg changes this to right matrix multiplication and is equivalent to the [`dot()`](#qiskit.quantum_info.SuperOp.dot ""qiskit.quantum_info.SuperOp.dot"") method `A.dot(B) == A.compose(B, front=True)`. ### conjugate Return the conjugate quantum channel. This is equivalent to the matrix complex conjugate in the [`SuperOp`](#qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{E}$, the SuperOp of the conjugate channel $\overline{{\mathcal{{E}}}}$ is $S_{\overline{\mathcal{E}^\dagger}} = \overline{S_{\mathcal{E}}}$. ### copy Make a deep copy of current operator. ### dot Return the right multiplied operator self \* other. **Parameters** * **other** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – an operator object. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None). **Returns** The right matrix multiplied Operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") The dot product can be obtained using the `@` binary operator. Hence `a.dot(b)` is equivalent to `a @ b`. ### expand Return the reverse-order tensor product with another SuperOp. **Parameters** **other** ([*SuperOp*](#qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"")) – a SuperOp object. **Returns** **the tensor product $b \otimes a$, where $a$** is the current SuperOp, and $b$ is the other SuperOp. **Return type** [SuperOp](#qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") ### input\_dims Return tuple of input dimension for specified subsystems. ### is\_cp Test if Choi-matrix is completely-positive (CP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_cptp Return True if completely-positive trace-preserving (CPTP). **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_tp Test if a channel is trace-preserving (TP) **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### is\_unitary Return True if QuantumChannel is a unitary channel. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### output\_dims Return tuple of output dimension for specified subsystems. ### power Return the power of the quantum channel. **Parameters** **n** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – the power exponent. **Returns** the channel $\mathcal{{E}} ^n$. **Return type** [SuperOp](#qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input and output dimensions of the SuperOp are not equal. For non-positive or non-integer exponents the power is defined as the matrix power of the [`SuperOp`](#qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation ie. for a channel $\mathcal{{E}}$, the SuperOp of the powered channel $\mathcal{{E}}^\n$ is $S_{{\mathcal{{E}}^n}} = S_{{\mathcal{{E}}}}^n$. ### reshape Return a shallow copy with reshaped input and output subsystem dimensions. **Parameters** * **input\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem input dimensions. If None the original input dims will be preserved \[Default: None]. * **output\_dims** (*None or* [*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – new subsystem output dimensions. If None the original output dims will be preserved \[Default: None]. * **num\_qubits** (*None or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – reshape to an N-qubit operator \[Default: None]. **Returns** returns self with reshaped input and output dimensions. **Return type** BaseOperator **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if combined size of all subsystem input dimension or subsystem output dimensions is not constant. ### tensor Return the tensor product with another SuperOp. **Parameters** **other** ([*SuperOp*](#qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"")) – a SuperOp object. **Returns** **the tensor product $a \otimes b$, where $a$** is the current SuperOp, and $b$ is the other SuperOp. **Return type** [SuperOp](#qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") The tensor product can be obtained using the `^` binary operator. Hence `a.tensor(b)` is equivalent to `a ^ b`. ### to\_instruction Convert to a Kraus or UnitaryGate circuit instruction. If the channel is unitary it will be added as a unitary gate, otherwise it will be added as a kraus simulator instruction. **Returns** A kraus instruction for the channel. **Return type** [qiskit.circuit.Instruction](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input data is not an N-qubit CPTP quantum channel. ### to\_operator Try to convert channel to a unitary representation Operator. **Return type** [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.operators.operator.Operator"") ### transpose Return the transpose quantum channel. This is equivalent to the matrix transpose in the [`SuperOp`](#qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") representation, ie. for a channel $\mathcal{E}$, the SuperOp of the transpose channel $\mathcal{{E}}^T$ is $S_{mathcal{E}^T} = S_{\mathcal{E}}^T$. ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.SuperOp.mdx "--- title: Z2Symmetries description: API reference for qiskit.quantum_info.Z2Symmetries in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.quantum_info.Z2Symmetries --- # Z2Symmetries Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") The \$Z\_2\$ symmetry converter identifies symmetries from the problem hamiltonian and uses them to provide a tapered - more efficient - representation of operators as Paulis for this problem. For each identified symmetry, one qubit can be eliminated in the Pauli representation at the cost of having to test two symmetry sectors (for the two possible eigenvalues - tapering values - of the symmetry). In certain problems such as the finding of the main operator’s ground state, one can a priori identify the symmetry sector of the solution and thus effectively reduce the computational overhead. The following attributes can be read and updated once the `Z2Symmetries` object has been constructed. ### tapering\_values Values determining the sector. **Type** [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)"")] or None ### tol The tolerance threshold for ignoring real and complex parts of a coefficient. **Type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **References** **\[1]: Bravyi, S., et al, “Tapering off qubits to simulate fermionic Hamiltonians”** [arXiv:1701.08213](https://arxiv.org/abs/1701.08213) **Parameters** * **symmetries** (*Iterable\[*[*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")*]*) – Object representing the list of \$Z\_2\$ symmetries. These correspond to the generators of the symmetry group \$langle tau\_1, tau\_2dots rangle>\$. * **sq\_paulis** (*Iterable\[*[*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")*]*) – Object representing the list of single-qubit Pauli \$sigma^x\_\{q(i)}\$ anti-commuting with the symmetry \$tau\_i\$ and commuting with all the other symmetries \$tau\_\{jneq i}\$. These operators are used to construct the unitary Clifford operators. * **sq\_list** (*Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – The list of indices \$q(i)\$ of the single-qubit Pauli operators used to build the Clifford operators. * **tapering\_values** (*Iterable\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None*) – List of eigenvalues determining the symmetry sector for each symmetry. * **tol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Tolerance threshold for ignoring real and complex parts of a coefficient. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – Invalid paulis. The lists of symmetries, single-qubit paulis support paulis and tapering values must be of equal length. This length is the number of applied symmetries and translates directly to the number of eliminated qubits. ## Attributes ### cliffords Get clifford operators, built based on symmetries and single-qubit X. **Returns** A list of unitaries used to diagonalize the Hamiltonian. ### settings Return operator settings. ### sq\_list Return sq list. ### sq\_paulis Return sq paulis. ### symmetries Return symmetries. ## Methods ### convert\_clifford This method operates the first part of the tapering. It converts the operator by composing it with the clifford unitaries defined in the current symmetry. **Parameters** **operator** ([*SparsePauliOp*](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.operators.symplectic.sparse_pauli_op.SparsePauliOp"")) – The to-be-tapered operator. **Returns** `SparsePauliOp` corresponding to the converted operator. **Return type** [*SparsePauliOp*](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.operators.symplectic.sparse_pauli_op.SparsePauliOp"") ### find\_z2\_symmetries Finds Z2 Pauli-type symmetries of a [`SparsePauliOp`](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp""). **Returns** A `Z2Symmetries` instance. **Return type** [*Z2Symmetries*](#qiskit.quantum_info.Z2Symmetries ""qiskit.quantum_info.analysis.z2_symmetries.Z2Symmetries"") ### is\_empty Check the z2\_symmetries is empty or not. **Returns** Empty or not. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### taper Taper an operator based on the z2\_symmetries info and sector defined by tapering\_values. Returns operator if the symmetry object is empty. The tapering is a two-step algorithm which first converts the operator into a [`SparsePauliOp`](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"") with same eigenvalues but where some qubits are only acted upon with the Pauli operators I or X. The number M of these redundant qubits is equal to the number M of identified symmetries. The second step of the reduction consists in replacing these qubits with the possible eigenvalues of the corresponding Pauli X, giving 2^M new operators with M less qubits. If an eigenvalue sector was previously identified for the solution, then this reduces to 1 new operator with M less qubits. **Parameters** **operator** ([*SparsePauliOp*](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.operators.symplectic.sparse_pauli_op.SparsePauliOp"")) – The to-be-tapered operator. **Returns** \[[`SparsePauliOp`](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"")]; otherwise, [`SparsePauliOp`](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp""). **Return type** If tapering\_values is None ### taper\_clifford Operate the second part of the tapering. This function assumes that the input operators have already been transformed using [`convert_clifford()`](#qiskit.quantum_info.Z2Symmetries.convert_clifford ""qiskit.quantum_info.Z2Symmetries.convert_clifford""). The redundant qubits due to the symmetries are dropped and replaced by their two possible eigenvalues. **Parameters** **operator** ([*SparsePauliOp*](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.operators.symplectic.sparse_pauli_op.SparsePauliOp"")) – Partially tapered operator resulting from a call to [`convert_clifford()`](#qiskit.quantum_info.Z2Symmetries.convert_clifford ""qiskit.quantum_info.Z2Symmetries.convert_clifford""). **Returns** \[[`SparsePauliOp`](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"")]; otherwise, [`SparsePauliOp`](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp""). **Return type** If tapering\_values is None ",repo/docs/api/qiskit/1.0\qiskit.quantum_info.Z2Symmetries.mdx "--- title: BaseReadoutMitigator description: API reference for qiskit.result.BaseReadoutMitigator in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.result.BaseReadoutMitigator --- # BaseReadoutMitigator Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Base readout error mitigator class. ## Methods ### expectation\_value Calculate the expectation value of a diagonal Hermitian operator. **Parameters** * **data** ([*Counts*](qiskit.result.Counts ""qiskit.result.counts.Counts"")) – Counts object to be mitigated. * **diagonal** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"") *|*[*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – the diagonal operator. This may either be specified as a string containing I,Z,0,1 characters, or as a real valued 1D array\_like object supplying the full diagonal, or as a dictionary, or as Callable. * **qubits** ([*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*) – the physical qubits measured to obtain the counts clbits. If None these are assumed to be qubits \[0, …, N-1] for N-bit counts. * **clbits** ([*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*) – Optional, marginalize counts to just these bits. * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Optional, the total number of shots, if None shots will be calculated as the sum of all counts. **Returns** The mean and an upper bound of the standard deviation of operator expectation value calculated from the current counts. **Return type** [*Tuple*](https://docs.python.org/3/library/typing.html#typing.Tuple ""(in Python v3.12)"")\[[float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)""), [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")] ### quasi\_probabilities Convert counts to a dictionary of quasi-probabilities **Parameters** * **data** ([*Counts*](qiskit.result.Counts ""qiskit.result.counts.Counts"")) – Counts to be mitigated. * **qubits** ([*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*) – the physical qubits measured to obtain the counts clbits. If None these are assumed to be qubits \[0, …, N-1] for N-bit counts. * **clbits** ([*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*) – Optional, marginalize counts to just these bits. * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Optional, the total number of shots, if None shots will be calculated as the sum of all counts. **Returns** **A dictionary containing pairs of \[output, mean] where “output”** is the key in the dictionaries, which is the length-N bitstring of a measured standard basis state, and “mean” is the mean of non-zero quasi-probability estimates. **Return type** [QuasiDistribution](qiskit.result.QuasiDistribution ""qiskit.result.QuasiDistribution"") ",repo/docs/api/qiskit/1.0\qiskit.result.BaseReadoutMitigator.mdx "--- title: CorrelatedReadoutMitigator description: API reference for qiskit.result.CorrelatedReadoutMitigator in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.result.CorrelatedReadoutMitigator --- # CorrelatedReadoutMitigator Bases: [`BaseReadoutMitigator`](qiskit.result.BaseReadoutMitigator ""qiskit.result.mitigation.base_readout_mitigator.BaseReadoutMitigator"") N-qubit readout error mitigator. Mitigates [`expectation_value()`](#qiskit.result.CorrelatedReadoutMitigator.expectation_value ""qiskit.result.CorrelatedReadoutMitigator.expectation_value"") and [`quasi_probabilities()`](#qiskit.result.CorrelatedReadoutMitigator.quasi_probabilities ""qiskit.result.CorrelatedReadoutMitigator.quasi_probabilities""). The mitigation\_matrix should be calibrated using qiskit experiments. This mitigation method should be used in case the readout errors of the qubits are assumed to be correlated. The mitigation\_matrix of *N* qubits is of size $2^N x 2^N$ so the mitigation complexity is $O(4^N)$. Initialize a CorrelatedReadoutMitigator **Parameters** * **assignment\_matrix** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – readout error assignment matrix. * **qubits** ([*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*) – Optional, the measured physical qubits for mitigation. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – matrix size does not agree with number of qubits ## Attributes ### qubits The device qubits for this mitigator ### settings Return settings. ## Methods ### assignment\_matrix Return the readout assignment matrix for specified qubits. The assignment matrix is the stochastic matrix $A$ which assigns a noisy readout probability distribution to an ideal input readout distribution: $P(i|j) = \langle i | A | j \rangle$. **Parameters** **qubits** ([*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*) – Optional, qubits being measured. **Returns** the assignment matrix A. **Return type** np.ndarray ### expectation\_value Compute the mitigated expectation value of a diagonal observable. This computes the mitigated estimator of $\langle O \rangle = \mbox{Tr}[\rho. O]$ of a diagonal observable $O = \sum_{x\in\{0, 1\}^n} O(x)|x\rangle\!\langle x|$. **Parameters** * **data** ([*Counts*](qiskit.result.Counts ""qiskit.result.counts.Counts"")) – Counts object * **diagonal** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"") *|*[*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"") *| None*) – Optional, the vector of diagonal values for summing the expectation value. If `None` the default value is $[1, -1]^\otimes n$. * **qubits** ([*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*) – Optional, the measured physical qubits the count bitstrings correspond to. If None qubits are assumed to be $[0, ..., n-1]$. * **clbits** ([*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*) – Optional, if not None marginalize counts to the specified bits. * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – the number of shots. **Returns** the expectation value and an upper bound of the standard deviation. **Return type** ([float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)""), [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) **Additional Information:** The diagonal observable $O$ is input using the `diagonal` kwarg as a list or Numpy array $[O(0), ..., O(2^n -1)]$. If no diagonal is specified the diagonal of the Pauli operator :math\`O = mbox\{diag}(Z^\{otimes n}) = \[1, -1]^\{otimes n}\` is used. The `clbits` kwarg is used to marginalize the input counts dictionary over the specified bit-values, and the `qubits` kwarg is used to specify which physical qubits these bit-values correspond to as `circuit.measure(qubits, clbits)`. ### mitigation\_matrix Return the readout mitigation matrix for the specified qubits. The mitigation matrix $A^{-1}$ is defined as the inverse of the [`assignment_matrix()`](#qiskit.result.CorrelatedReadoutMitigator.assignment_matrix ""qiskit.result.CorrelatedReadoutMitigator.assignment_matrix"") $A$. **Parameters** **qubits** ([*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*) – Optional, qubits being measured. **Returns** the measurement error mitigation matrix $A^{-1}$. **Return type** np.ndarray ### quasi\_probabilities Compute mitigated quasi probabilities value. **Parameters** * **data** ([*Counts*](qiskit.result.Counts ""qiskit.result.counts.Counts"")) – counts object * **qubits** ([*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*) – qubits the count bitstrings correspond to. * **clbits** ([*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*) – Optional, marginalize counts to just these bits. * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Optional, the total number of shots, if None shots will be calculated as the sum of all counts. **Returns** **A dictionary containing pairs of \[output, mean] where “output”** is the key in the dictionaries, which is the length-N bitstring of a measured standard basis state, and “mean” is the mean of non-zero quasi-probability estimates. **Return type** [QuasiDistribution](qiskit.result.QuasiDistribution ""qiskit.result.QuasiDistribution"") ### stddev\_upper\_bound Return an upper bound on standard deviation of expval estimator. **Parameters** **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of shots used for expectation value measurement. **Returns** the standard deviation upper bound. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.result.CorrelatedReadoutMitigator.mdx "--- title: Counts description: API reference for qiskit.result.Counts in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.result.Counts --- # Counts Bases: [`dict`](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") A class to store a counts result from a circuit execution. Build a counts object **Parameters** * **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – The dictionary input for the counts. Where the keys represent a measured classical value and the value is an integer the number of shots with that result. The keys can be one of several formats: > * A hexadecimal string of the form `'0x4a'` > * A bit string prefixed with `0b` for example `'0b1011'` > * A bit string formatted across register and memory slots. For example, `'00 10'`. > * A dit string, for example `'02'`. Note for objects created with dit strings the `creg_sizes` and `memory_slots` kwargs don’t work and [`hex_outcomes()`](#qiskit.result.Counts.hex_outcomes ""qiskit.result.Counts.hex_outcomes"") and [`int_outcomes()`](#qiskit.result.Counts.int_outcomes ""qiskit.result.Counts.int_outcomes"") also do not work. * **time\_taken** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The duration of the experiment that generated the counts in seconds. * **creg\_sizes** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – a nested list where the inner element is a list of tuples containing both the classical register name and classical register size. For example, `[('c_reg', 2), ('my_creg', 4)]`. * **memory\_slots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of total `memory_slots` in the experiment. **Raises** * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – If the input key type is not an `int` or `str`. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If a dit string key is input with `creg_sizes` and/or `memory_slots`. ## Attributes ### bitstring\_regex ## Methods ### clear ### copy ### fromkeys Create a new dictionary with keys from iterable and values set to value. ### get Return the value for key if key is in the dictionary, else default. ### hex\_outcomes Return a counts dictionary with hexadecimal string keys **Returns** **A dictionary with the keys as hexadecimal strings instead of** bitstrings **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If the Counts object contains counts for dit strings ### int\_outcomes Build a counts dictionary with integer keys instead of count strings **Returns** A dictionary with the keys as integers instead of bitstrings **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If the Counts object contains counts for dit strings ### items ### keys ### most\_frequent Return the most frequent count **Returns** The bit string for the most frequent result **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – when there is >1 count with the same max counts, or an empty object. ### pop If key is not found, default is returned if given, otherwise KeyError is raised ### popitem Remove and return a (key, value) pair as a 2-tuple. Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty. ### setdefault Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. ### shots Return the number of shots ### update If E is present and has a .keys() method, then does: for k in E: D\[k] = E\[k] If E is present and lacks a .keys() method, then does: for k, v in E: D\[k] = v In either case, this is followed by: for k in F: D\[k] = F\[k] ### values ",repo/docs/api/qiskit/1.0\qiskit.result.Counts.mdx "--- title: LocalReadoutMitigator description: API reference for qiskit.result.LocalReadoutMitigator in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.result.LocalReadoutMitigator --- # LocalReadoutMitigator Bases: [`BaseReadoutMitigator`](qiskit.result.BaseReadoutMitigator ""qiskit.result.mitigation.base_readout_mitigator.BaseReadoutMitigator"") 1-qubit tensor product readout error mitigator. Mitigates [`expectation_value()`](#qiskit.result.LocalReadoutMitigator.expectation_value ""qiskit.result.LocalReadoutMitigator.expectation_value"") and [`quasi_probabilities()`](#qiskit.result.LocalReadoutMitigator.quasi_probabilities ""qiskit.result.LocalReadoutMitigator.quasi_probabilities""). The mitigator should either be calibrated using qiskit experiments, or calculated directly from the backend properties. This mitigation method should be used in case the readout errors of the qubits are assumed to be uncorrelated. For *N* qubits there are *N* mitigation matrices, each of size $2 x 2$ and the mitigation complexity is $O(2^N)$, so it is more efficient than the [`CorrelatedReadoutMitigator`](qiskit.result.CorrelatedReadoutMitigator ""qiskit.result.CorrelatedReadoutMitigator"") class. Initialize a LocalReadoutMitigator **Parameters** * **assignment\_matrices** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")*] | None*) – Optional, list of single-qubit readout error assignment matrices. * **qubits** ([*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*) – Optional, the measured physical qubits for mitigation. * **backend** – Optional, backend name. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – matrices sizes do not agree with number of qubits ## Attributes ### qubits The device qubits for this mitigator ### settings Return settings. ## Methods ### assignment\_matrix Return the measurement assignment matrix for specified qubits. The assignment matrix is the stochastic matrix $A$ which assigns a noisy measurement probability distribution to an ideal input measurement distribution: $P(i|j) = \langle i | A | j \rangle$. **Parameters** **qubits** ([*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*) – Optional, qubits being measured for operator expval. **Returns** the assignment matrix A. **Return type** np.ndarray ### expectation\_value Compute the mitigated expectation value of a diagonal observable. This computes the mitigated estimator of $\langle O \rangle = \mbox{Tr}[\rho. O]$ of a diagonal observable $O = \sum_{x\in\{0, 1\}^n} O(x)|x\rangle\!\langle x|$. **Parameters** * **data** ([*Counts*](qiskit.result.Counts ""qiskit.result.counts.Counts"")) – Counts object * **diagonal** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"") *|*[*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"") *| None*) – Optional, the vector of diagonal values for summing the expectation value. If `None` the default value is $[1, -1]^\otimes n$. * **qubits** ([*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*) – Optional, the measured physical qubits the count bitstrings correspond to. If None qubits are assumed to be $[0, ..., n-1]$. * **clbits** ([*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*) – Optional, if not None marginalize counts to the specified bits. * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – the number of shots. **Returns** the expectation value and an upper bound of the standard deviation. **Return type** ([float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)""), [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) **Additional Information:** The diagonal observable $O$ is input using the `diagonal` kwarg as a list or Numpy array $[O(0), ..., O(2^n -1)]$. If no diagonal is specified the diagonal of the Pauli operator :math\`O = mbox\{diag}(Z^\{otimes n}) = \[1, -1]^\{otimes n}\` is used. The `clbits` kwarg is used to marginalize the input counts dictionary over the specified bit-values, and the `qubits` kwarg is used to specify which physical qubits these bit-values correspond to as `circuit.measure(qubits, clbits)`. ### mitigation\_matrix Return the measurement mitigation matrix for the specified qubits. The mitigation matrix $A^{-1}$ is defined as the inverse of the [`assignment_matrix()`](#qiskit.result.LocalReadoutMitigator.assignment_matrix ""qiskit.result.LocalReadoutMitigator.assignment_matrix"") $A$. **Parameters** **qubits** ([*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)"")*] |* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Optional, qubits being measured for operator expval. if a single int is given, it is assumed to be the index of the qubit in self.\_qubits **Returns** the measurement error mitigation matrix $A^{-1}$. **Return type** np.ndarray ### quasi\_probabilities Compute mitigated quasi probabilities value. **Parameters** * **data** ([*Counts*](qiskit.result.Counts ""qiskit.result.counts.Counts"")) – counts object * **qubits** ([*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*) – qubits the count bitstrings correspond to. * **clbits** ([*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*) – Optional, marginalize counts to just these bits. * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Optional, the total number of shots, if None shots will be calculated as the sum of all counts. **Returns** **A dictionary containing pairs of \[output, mean] where “output”** is the key in the dictionaries, which is the length-N bitstring of a measured standard basis state, and “mean” is the mean of non-zero quasi-probability estimates. **Return type** [QuasiDistribution](qiskit.result.QuasiDistribution ""qiskit.result.QuasiDistribution"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if qubit and clbit kwargs are not valid. ### stddev\_upper\_bound Return an upper bound on standard deviation of expval estimator. **Parameters** * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of shots used for expectation value measurement. * **qubits** ([*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*) – qubits being measured for operator expval. **Returns** the standard deviation upper bound. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.result.LocalReadoutMitigator.mdx "--- title: ProbDistribution description: API reference for qiskit.result.ProbDistribution in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.result.ProbDistribution --- # ProbDistribution Bases: [`dict`](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") A generic dict-like class for probability distributions. Builds a probability distribution object. **Parameters** * **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Input probability data. Where the keys represent a measured classical value and the value is a float for the probability of that result. The keys can be one of several formats: > * A hexadecimal string of the form `""0x4a""` > * A bit string e.g. `'0b1011'` or `""01011""` > * An integer * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of shots the distribution was derived from. **Raises** * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – If the input keys are not a string or int * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the string format of the keys is incorrect ## Methods ### binary\_probabilities Build a probabilities dictionary with binary string keys **Parameters** **num\_bits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of bits in the binary bitstrings (leading zeros will be padded). If None, a default value will be used. If keys are given as integers or strings with binary or hex prefix, the default value will be derived from the largest key present. If keys are given as bitstrings without prefix, the default value will be derived from the largest key length. **Returns** **A dictionary where the keys are binary strings in the format** `""0110""` **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ### clear ### copy ### fromkeys Create a new dictionary with keys from iterable and values set to value. ### get Return the value for key if key is in the dictionary, else default. ### hex\_probabilities Build a probabilities dictionary with hexadecimal string keys **Returns** **A dictionary where the keys are hexadecimal strings in the** format `""0x1a""` **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ### items ### keys ### pop If key is not found, default is returned if given, otherwise KeyError is raised ### popitem Remove and return a (key, value) pair as a 2-tuple. Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty. ### setdefault Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. ### update If E is present and has a .keys() method, then does: for k in E: D\[k] = E\[k] If E is present and lacks a .keys() method, then does: for k, v in E: D\[k] = v In either case, this is followed by: for k in F: D\[k] = F\[k] ### values ",repo/docs/api/qiskit/1.0\qiskit.result.ProbDistribution.mdx "--- title: QuasiDistribution description: API reference for qiskit.result.QuasiDistribution in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.result.QuasiDistribution --- # QuasiDistribution Bases: [`dict`](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") A dict-like class for representing quasi-probabilities. Builds a quasiprobability distribution object. The quasiprobability values might include floating-point errors. `QuasiDistribution.__repr__` rounds using `numpy.round()` and the parameter `ndigits` can be manipulated with the class attribute `__ndigits__`. The default is `15`. **Parameters** * **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Input quasiprobability data. Where the keys represent a measured classical value and the value is a float for the quasiprobability of that result. The keys can be one of several formats: > * A hexadecimal string of the form `""0x4a""` > * A bit string e.g. `'0b1011'` or `""01011""` > * An integer * **shots** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of shots the distribution was derived from. * **stddev\_upper\_bound** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – An upper bound for the standard deviation **Raises** * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – If the input keys are not a string or int * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the string format of the keys is incorrect ## Attributes ### stddev\_upper\_bound Return an upper bound on standard deviation of expval estimator. ## Methods ### binary\_probabilities Build a quasi-probabilities dictionary with binary string keys **Parameters** **num\_bits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of bits in the binary bitstrings (leading zeros will be padded). If None, a default value will be used. If keys are given as integers or strings with binary or hex prefix, the default value will be derived from the largest key present. If keys are given as bitstrings without prefix, the default value will be derived from the largest key length. **Returns** **A dictionary where the keys are binary strings in the format** `""0110""` **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ### clear ### copy ### fromkeys Create a new dictionary with keys from iterable and values set to value. ### get Return the value for key if key is in the dictionary, else default. ### hex\_probabilities Build a quasi-probabilities dictionary with hexadecimal string keys **Returns** **A dictionary where the keys are hexadecimal strings in the** format `""0x1a""` **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ### items ### keys ### nearest\_probability\_distribution Takes a quasiprobability distribution and maps it to the closest probability distribution as defined by the L2-norm. **Parameters** **return\_distance** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Return the L2 distance between distributions. **Returns** Nearest probability distribution. float: Euclidean (L2) distance of distributions. **Return type** [ProbDistribution](qiskit.result.ProbDistribution ""qiskit.result.ProbDistribution"") **Notes** Method from Smolin et al., Phys. Rev. Lett. 108, 070502 (2012). ### pop If key is not found, default is returned if given, otherwise KeyError is raised ### popitem Remove and return a (key, value) pair as a 2-tuple. Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty. ### setdefault Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. ### update If E is present and has a .keys() method, then does: for k in E: D\[k] = E\[k] If E is present and lacks a .keys() method, then does: for k, v in E: D\[k] = v In either case, this is followed by: for k in F: D\[k] = F\[k] ### values ",repo/docs/api/qiskit/1.0\qiskit.result.QuasiDistribution.mdx "--- title: Result description: API reference for qiskit.result.Result in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.result.Result --- # Result Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Model for Results. ### backend\_name backend name. **Type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### backend\_version backend version, in the form X.Y.Z. **Type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### qobj\_id user-generated Qobj id. **Type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### job\_id unique execution id from the backend. **Type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### success True if complete input qobj executed correctly. (Implies each experiment success) **Type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### results corresponding results for array of experiments of the input qobj **Type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[ExperimentResult] ## Methods ### data Get the raw data for an experiment. Note this data will be a single classical and quantum register and in a format required by the results schema. We recommend that most users use the get\_xxx method, and the data will be post-processed for the data type. **Parameters** **experiment** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *or*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or None*) – the index of the experiment. Several types are accepted for convenience:: \* str: the name of the experiment. \* QuantumCircuit: the name of the circuit instance will be used. \* Schedule: the name of the schedule instance will be used. \* int: the position of the experiment. \* None: if there is only one experiment, returns it. **Returns** A dictionary of results data for an experiment. The data depends on the backend it ran on and the settings of meas\_level, meas\_return and memory. OpenQASM backends return a dictionary of dictionary with the key ‘counts’ and with the counts, with the second dictionary keys containing a string in hex format (`0x123`) and values equal to the number of times this outcome was measured. Statevector backends return a dictionary with key ‘statevector’ and values being a list\[list\[complex components]] list of 2^num\_qubits complex amplitudes. Where each complex number is represented as a 2 entry list for each component. For example, a list of \[0.5+1j, 0-1j] would be represented as \[\[0.5, 1], \[0, -1]]. Unitary backends return a dictionary with key ‘unitary’ and values being a list\[list\[list\[complex components]]] list of 2^num\_qubits x 2^num\_qubits complex amplitudes in a two entry list for each component. For example if the amplitude is \[\[0.5+0j, 0-1j], …] the value returned will be \[\[\[0.5, 0], \[0, -1]], …]. The simulator backends also have an optional key ‘snapshots’ which returns a dict of snapshots specified by the simulator backend. The value is of the form dict\[slot: dict\[str: array]] where the keys are the requested snapshot slots, and the values are a dictionary of the snapshots. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if data for the experiment could not be retrieved. ### from\_dict Create a new ExperimentResultData object from a dictionary. **Parameters** **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary representing the Result to create. It will be in the same format as output by [`to_dict()`](#qiskit.result.Result.to_dict ""qiskit.result.Result.to_dict""). **Returns** The `Result` object from the input dictionary. **Return type** [Result](#qiskit.result.Result ""qiskit.result.Result"") ### get\_counts Get the histogram data of an experiment. **Parameters** **experiment** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *or*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or None*) – the index of the experiment, as specified by `data([experiment])`. **Returns** a dictionary or a list of dictionaries. A dictionary has the counts for each qubit with the keys containing a string in binary format and separated according to the registers in circuit (e.g. `0100 1110`). The string is little-endian (cr\[0] on the right hand side). **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#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)"")] or [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)"")\[[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)"")]] **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if there are no counts for the experiment. ### get\_memory Get the sequence of memory states (readouts) for each shot The data from the experiment is a list of format \[‘00000’, ‘01000’, ‘10100’, ‘10100’, ‘11101’, ‘11100’, ‘00101’, …, ‘01010’] **Parameters** **experiment** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *or*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or None*) – the index of the experiment, as specified by `data()`. **Returns** Either the list of each outcome, formatted according to registers in circuit or a complex numpy np.ndarray with shape: > | meas\_level | meas\_return | shape | > | ----------- | ------------ | ----------------------------------------------------- | > | 0 | single | np.ndarray\[shots, memory\_slots, memory\_slot\_size] | > | 0 | avg | np.ndarray\[memory\_slots, memory\_slot\_size] | > | 1 | single | np.ndarray\[shots, memory\_slots] | > | 1 | avg | np.ndarray\[memory\_slots] | > | 2 | memory=True | list | **Return type** List\[[str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")] or np.ndarray **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if there is no memory data for the circuit. ### get\_statevector Get the final statevector of an experiment. **Parameters** * **experiment** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *or*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or None*) – the index of the experiment, as specified by `data()`. * **decimals** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of decimals in the statevector. If None, does not round. **Returns** list of 2^num\_qubits complex amplitudes. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[[complex](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")] **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if there is no statevector for the experiment. ### get\_unitary Get the final unitary of an experiment. **Parameters** * **experiment** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") *or*[*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *or*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or None*) – the index of the experiment, as specified by `data()`. * **decimals** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of decimals in the unitary. If None, does not round. **Returns** **list of 2^num\_qubits x 2^num\_qubits complex** amplitudes. **Return type** [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)"")\[[complex](https://docs.python.org/3/library/functions.html#complex ""(in Python v3.12)"")]] **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if there is no unitary for the experiment. ### to\_dict Return a dictionary format representation of the Result **Returns** The dictionary form of the Result **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.result.Result.mdx "--- title: ResultError description: API reference for qiskit.result.ResultError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit.result.ResultError --- # qiskit.result.ResultError Exceptions raised due to errors in result output. It may be better for the Qiskit API to raise this exception. **Parameters** **error** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – This is the error record as it comes back from the API. The format is like: ```python error = {'status': 403, 'message': 'Your credits are not enough.', 'code': 'MAX_CREDITS_EXCEEDED'} ``` Set the error message. ",repo/docs/api/qiskit/1.0\qiskit.result.ResultError.mdx "--- title: EvolutionSynthesis description: API reference for qiskit.synthesis.EvolutionSynthesis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.EvolutionSynthesis --- # EvolutionSynthesis Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Interface for evolution synthesis algorithms. ## Attributes ### settings Return the settings in a dictionary, which can be used to reconstruct the object. **Returns** A dictionary containing the settings of this product formula. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – The interface does not implement this method. ## Methods ### synthesize Synthesize an `qiskit.circuit.library.PauliEvolutionGate`. **Parameters** **evolution** ([*PauliEvolutionGate*](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate"")) – The evolution gate to synthesize. **Returns** A circuit implementing the evolution. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.synthesis.EvolutionSynthesis.mdx "--- title: LieTrotter description: API reference for qiskit.synthesis.LieTrotter in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.LieTrotter --- # LieTrotter Bases: [`ProductFormula`](qiskit.synthesis.ProductFormula ""qiskit.synthesis.evolution.product_formula.ProductFormula"") The Lie-Trotter product formula. The Lie-Trotter formula approximates the exponential of two non-commuting operators with products of their exponentials up to a second order error: $$ e^{A + B} \approx e^{A}e^{B}. $$ In this implementation, the operators are provided as sum terms of a Pauli operator. For example, we approximate $$ e^{-it(XX + ZZ)} = e^{-it XX}e^{-it ZZ} + \mathcal{O}(t^2). $$ **References** \[1]: D. Berry, G. Ahokas, R. Cleve and B. Sanders, “Efficient quantum algorithms for simulating sparse Hamiltonians” (2006). [arXiv:quant-ph/0508139](https://arxiv.org/abs/quant-ph/0508139) \[2]: N. Hatano and M. Suzuki, “Finding Exponential Product Formulas of Higher Orders” (2005). [arXiv:math-ph/0506007](https://arxiv.org/pdf/math-ph/0506007.pdf) **Parameters** * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of time steps. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to insert barriers between the atomic evolutions. * **cx\_structure** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – How to arrange the CX gates for the Pauli evolutions, can be `""chain""`, where next neighbor connections are used, or `""fountain""`, where all qubits are connected to one. * **atomic\_evolution** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[*[*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.operators.symplectic.pauli.Pauli"") *|*[*SparsePauliOp*](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.operators.symplectic.sparse_pauli_op.SparsePauliOp"")*,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")*] | None*) – A function to construct the circuit for the evolution of single Pauli string. Per default, a single Pauli evolution is decomposed in a CX chain and a single qubit Z rotation. ## Attributes ### settings Return the settings in a dictionary, which can be used to reconstruct the object. **Returns** A dictionary containing the settings of this product formula. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – If a custom atomic evolution is set, which cannot be serialized. ## Methods ### synthesize Synthesize an `qiskit.circuit.library.PauliEvolutionGate`. **Parameters** **evolution** ([*PauliEvolutionGate*](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate"")) – The evolution gate to synthesize. **Returns** A circuit implementing the evolution. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.synthesis.LieTrotter.mdx "--- title: MatrixExponential description: API reference for qiskit.synthesis.MatrixExponential in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.MatrixExponential --- # MatrixExponential Bases: [`EvolutionSynthesis`](qiskit.synthesis.EvolutionSynthesis ""qiskit.synthesis.evolution.evolution_synthesis.EvolutionSynthesis"") Exact operator evolution via matrix exponentiation and unitary synthesis. This class synthesis the exponential of operators by calculating their exponentially-sized matrix representation and using exact matrix exponentiation followed by unitary synthesis to obtain a circuit. This process is not scalable and serves as comparison or benchmark for small systems. ## Attributes ### settings Return the settings in a dictionary, which can be used to reconstruct the object. **Returns** A dictionary containing the settings of this product formula. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – The interface does not implement this method. ## Methods ### synthesize Synthesize an `qiskit.circuit.library.PauliEvolutionGate`. **Parameters** **evolution** ([*PauliEvolutionGate*](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate"")) – The evolution gate to synthesize. **Returns** A circuit implementing the evolution. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.synthesis.MatrixExponential.mdx "--- title: OneQubitEulerDecomposer description: API reference for qiskit.synthesis.OneQubitEulerDecomposer in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.OneQubitEulerDecomposer --- # OneQubitEulerDecomposer Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A class for decomposing 1-qubit unitaries into Euler angle rotations. The resulting decomposition is parameterized by 3 Euler rotation angle parameters $(\theta, \phi, \lambda)$, and a phase parameter $\gamma$. The value of the parameters for an input unitary depends on the decomposition basis. Allowed bases and the resulting circuits are shown in the following table. Note that for the non-Euler bases ($U3$, $U1X$, $RR$), the $ZYZ$ Euler parameters are used. | Basis | Euler Angle Basis | Decomposition Circuit | | ------ | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | | ‘ZYZ’ | $Z(\phi) Y(\theta) Z(\lambda)$ | $e^{i\gamma} R_Z(\phi).R_Y(\theta).R_Z(\lambda)$ | | ‘ZXZ’ | $Z(\phi) X(\theta) Z(\lambda)$ | $e^{i\gamma} R_Z(\phi).R_X(\theta).R_Z(\lambda)$ | | ‘XYX’ | $X(\phi) Y(\theta) X(\lambda)$ | $e^{i\gamma} R_X(\phi).R_Y(\theta).R_X(\lambda)$ | | ‘XZX’ | $X(\phi) Z(\theta) X(\lambda)$ | $e^{i\gamma} R_X(\phi).R_Z(\theta).R_X(\lambda)$ | | ‘U3’ | $Z(\phi) Y(\theta) Z(\lambda)$ | $e^{i\gamma} U_3(\theta,\phi,\lambda)$ | | ‘U321’ | $Z(\phi) Y(\theta) Z(\lambda)$ | $e^{i\gamma} U_3(\theta,\phi,\lambda)$ | | ‘U’ | $Z(\phi) Y(\theta) Z(\lambda)$ | $e^{i\gamma} U_3(\theta,\phi,\lambda)$ | | ‘PSX’ | $Z(\phi) Y(\theta) Z(\lambda)$ | $e^{i\gamma} U_1(\phi+\pi).R_X\left(\frac{\pi}{2}\right).$ $U_1(\theta+\pi).R_X\left(\frac{\pi}{2}\right).U_1(\lambda)$ | | ‘ZSX’ | $Z(\phi) Y(\theta) Z(\lambda)$ | $e^{i\gamma} R_Z(\phi+\pi).\sqrt{X}.$ $R_Z(\theta+\pi).\sqrt{X}.R_Z(\lambda)$ | | ‘ZSXX’ | $Z(\phi) Y(\theta) Z(\lambda)$ | $e^{i\gamma} R_Z(\phi+\pi).\sqrt{X}.R_Z(\theta+\pi).\sqrt{X}.R_Z(\lambda)$ or $e^{i\gamma} R_Z(\phi+\pi).X.R_Z(\lambda)$ | | ‘U1X’ | $Z(\phi) Y(\theta) Z(\lambda)$ | $e^{i\gamma} U_1(\phi+\pi).R_X\left(\frac{\pi}{2}\right).$ $U_1(\theta+\pi).R_X\left(\frac{\pi}{2}\right).U_1(\lambda)$ | | ‘RR’ | $Z(\phi) Y(\theta) Z(\lambda)$ | $e^{i\gamma} R\left(-\pi,\frac{\phi-\lambda+\pi}{2}\right).$ $R\left(\theta+\pi,\frac{\pi}{2}-\lambda\right)$ | ### \_\_call\_\_ Decompose single qubit gate into a circuit. **Parameters** * **unitary** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") *|*[*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"") *| np.ndarray*) – 1-qubit unitary matrix * **simplify** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – reduce gate count in decomposition \[Default: True]. * **atol** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – absolute tolerance for checking angles when simplifying returned circuit \[Default: 1e-12]. **Returns** the decomposed single-qubit gate circuit **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input is invalid or synthesis fails. Initialize decomposer Supported bases are: `'U'`, `'PSX'`, `'ZSXX'`, `'ZSX'`, `'U321'`, `'U3'`, `'U1X'`, `'RR'`, `'ZYZ'`, `'ZXZ'`, `'XYX'`, `'XZX'`. **Parameters** * **basis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – the decomposition basis \[Default: `'U3'`] * **use\_dag** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If true the output from calls to the decomposer will be a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") object instead of [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If input basis is not recognized. ## Attributes ### basis The decomposition basis. ## Methods ### angles Return the Euler angles for input array. **Parameters** **unitary** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – $2\times2$ unitary matrix. **Returns** `(theta, phi, lambda)`. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") ### angles\_and\_phase Return the Euler angles and phase for input array. **Parameters** **unitary** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – $2\times2$ **Returns** `(theta, phi, lambda, phase)`. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") ### build\_circuit Return the circuit or dag object from a list of gates. ",repo/docs/api/qiskit/1.0\qiskit.synthesis.OneQubitEulerDecomposer.mdx "--- title: ProductFormula description: API reference for qiskit.synthesis.ProductFormula in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.ProductFormula --- # ProductFormula Bases: [`EvolutionSynthesis`](qiskit.synthesis.EvolutionSynthesis ""qiskit.synthesis.evolution.evolution_synthesis.EvolutionSynthesis"") Product formula base class for the decomposition of non-commuting operator exponentials. [`LieTrotter`](qiskit.synthesis.LieTrotter ""qiskit.synthesis.LieTrotter"") and [`SuzukiTrotter`](qiskit.synthesis.SuzukiTrotter ""qiskit.synthesis.SuzukiTrotter"") inherit from this class. **Parameters** * **order** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The order of the product formula. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of time steps. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to insert barriers between the atomic evolutions. * **cx\_structure** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – How to arrange the CX gates for the Pauli evolutions, can be `""chain""`, where next neighbor connections are used, or `""fountain""`, where all qubits are connected to one. * **atomic\_evolution** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[*[*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.operators.symplectic.pauli.Pauli"") *|*[*SparsePauliOp*](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.operators.symplectic.sparse_pauli_op.SparsePauliOp"")*,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")*] | None*) – A function to construct the circuit for the evolution of single Pauli string. Per default, a single Pauli evolution is decomposed in a CX chain and a single qubit Z rotation. ## Attributes ### settings Return the settings in a dictionary, which can be used to reconstruct the object. **Returns** A dictionary containing the settings of this product formula. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – If a custom atomic evolution is set, which cannot be serialized. ## Methods ### synthesize Synthesize an `qiskit.circuit.library.PauliEvolutionGate`. **Parameters** **evolution** ([*PauliEvolutionGate*](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate"")) – The evolution gate to synthesize. **Returns** A circuit implementing the evolution. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.synthesis.ProductFormula.mdx "--- title: QDrift description: API reference for qiskit.synthesis.QDrift in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.QDrift --- # QDrift Bases: [`ProductFormula`](qiskit.synthesis.ProductFormula ""qiskit.synthesis.evolution.product_formula.ProductFormula"") The QDrift Trotterization method, which selects each each term in the Trotterization randomly, with a probability proportional to its weight. Based on the work of Earl Campbell in Ref. \[1]. **References** \[1]: E. Campbell, “A random compiler for fast Hamiltonian simulation” (2018). [arXiv:quant-ph/1811.08017](https://arxiv.org/abs/1811.08017) **Parameters** * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of times to repeat the Trotterization circuit. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to insert barriers between the atomic evolutions. * **cx\_structure** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – How to arrange the CX gates for the Pauli evolutions, can be `""chain""`, where next neighbor connections are used, or `""fountain""`, where all qubits are connected to one. * **atomic\_evolution** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[*[*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.operators.symplectic.pauli.Pauli"") *|*[*SparsePauliOp*](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.operators.symplectic.sparse_pauli_op.SparsePauliOp"")*,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")*] | None*) – A function to construct the circuit for the evolution of single Pauli string. Per default, a single Pauli evolution is decomposed in a CX chain and a single qubit Z rotation. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – An optional seed for reproducibility of the random sampling process. ## Attributes ### settings Return the settings in a dictionary, which can be used to reconstruct the object. **Returns** A dictionary containing the settings of this product formula. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – If a custom atomic evolution is set, which cannot be serialized. ## Methods ### synthesize Synthesize an `qiskit.circuit.library.PauliEvolutionGate`. **Parameters** **evolution** ([*PauliEvolutionGate*](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate"")) – The evolution gate to synthesize. **Returns** A circuit implementing the evolution. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.synthesis.QDrift.mdx "--- title: SolovayKitaevDecomposition description: API reference for qiskit.synthesis.SolovayKitaevDecomposition in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.SolovayKitaevDecomposition --- # SolovayKitaevDecomposition Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") The Solovay Kitaev discrete decomposition algorithm. This class is called recursively by the transpiler pass, which is why it is separeted. See [`qiskit.transpiler.passes.SolovayKitaev`](qiskit.transpiler.passes.SolovayKitaev ""qiskit.transpiler.passes.SolovayKitaev"") for more information. **Parameters** **basic\_approximations** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, np.ndarray] |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[GateSequence] | None*) – A specification of the basic SU(2) approximations in terms of discrete gates. At each iteration this algorithm, the remaining error is approximated with the closest sequence of gates in this set. If a `str`, this specifies a `.npy` filename from which to load the approximation. If a `dict`, then this contains `{gates: effective_SO3_matrix}` pairs, e.g. `{""h t"": np.array([[0, 0.7071, -0.7071], [0, -0.7071, -0.7071], [-1, 0, 0]]}`. If a list, this contains the same information as the dict, but already converted to `GateSequence` objects, which contain the SO(3) matrix and gates. ## Methods ### find\_basic\_approximation Finds gate in `self._basic_approximations` that best represents `sequence`. **Parameters** **sequence** (*GateSequence*) – The gate to find the approximation to. **Returns** Gate in basic approximations that is closest to `sequence`. **Return type** [*Gate*](qiskit.circuit.Gate ""qiskit.circuit.gate.Gate"") ### load\_basic\_approximations Load basic approximations. **Parameters** **data** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – If a string, specifies the path to the file from where to load the data. If a dictionary, directly specifies the decompositions as `{gates: matrix}`. There `gates` are the names of the gates producing the SO(3) matrix `matrix`, e.g. `{""h t"": np.array([[0, 0.7071, -0.7071], [0, -0.7071, -0.7071], [-1, 0, 0]]}`. **Returns** A list of basic approximations as type `GateSequence`. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the number of gate combinations and associated matrices does not match. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[GateSequence] ### run Run the algorithm. **Parameters** * **gate\_matrix** (*np.ndarray*) – The 2x2 matrix representing the gate. This matrix has to be SU(2) up to global phase. * **recursion\_degree** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The recursion degree, called $n$ in the paper. * **return\_dag** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True` return a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit""), else a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). * **check\_input** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True` check that the input matrix is valid for the decomposition. **Returns** A one-qubit circuit approximating the `gate_matrix` in the specified discrete basis. **Return type** QuantumCircuit’ | ‘DAGCircuit ",repo/docs/api/qiskit/1.0\qiskit.synthesis.SolovayKitaevDecomposition.mdx "--- title: SuzukiTrotter description: API reference for qiskit.synthesis.SuzukiTrotter in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.SuzukiTrotter --- # SuzukiTrotter Bases: [`ProductFormula`](qiskit.synthesis.ProductFormula ""qiskit.synthesis.evolution.product_formula.ProductFormula"") The (higher order) Suzuki-Trotter product formula. The Suzuki-Trotter formulas improve the error of the Lie-Trotter approximation. For example, the second order decomposition is $$ e^{A + B} \approx e^{B/2} e^{A} e^{B/2}. $$ Higher order decompositions are based on recursions, see Ref. \[1] for more details. In this implementation, the operators are provided as sum terms of a Pauli operator. For example, in the second order Suzuki-Trotter decomposition we approximate $$ e^{-it(XX + ZZ)} = e^{-it/2 ZZ}e^{-it XX}e^{-it/2 ZZ} + \mathcal{O}(t^3). $$ **References** \[1]: D. Berry, G. Ahokas, R. Cleve and B. Sanders, “Efficient quantum algorithms for simulating sparse Hamiltonians” (2006). [arXiv:quant-ph/0508139](https://arxiv.org/abs/quant-ph/0508139) \[2]: N. Hatano and M. Suzuki, “Finding Exponential Product Formulas of Higher Orders” (2005). [arXiv:math-ph/0506007](https://arxiv.org/pdf/math-ph/0506007.pdf) **Parameters** * **order** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The order of the product formula. * **reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of time steps. * **insert\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to insert barriers between the atomic evolutions. * **cx\_structure** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – How to arrange the CX gates for the Pauli evolutions, can be `""chain""`, where next neighbor connections are used, or `""fountain""`, where all qubits are connected to one. * **atomic\_evolution** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"")*\[\[*[*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.operators.symplectic.pauli.Pauli"") *|*[*SparsePauliOp*](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.operators.symplectic.sparse_pauli_op.SparsePauliOp"")*,* [*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")*] | None*) – A function to construct the circuit for the evolution of single Pauli string. Per default, a single Pauli evolution is decomposed in a CX chain and a single qubit Z rotation. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If order is not even ## Attributes ### settings Return the settings in a dictionary, which can be used to reconstruct the object. **Returns** A dictionary containing the settings of this product formula. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – If a custom atomic evolution is set, which cannot be serialized. ## Methods ### synthesize Synthesize an `qiskit.circuit.library.PauliEvolutionGate`. **Parameters** **evolution** ([*PauliEvolutionGate*](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate"")) – The evolution gate to synthesize. **Returns** A circuit implementing the evolution. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.synthesis.SuzukiTrotter.mdx "--- title: TwoQubitBasisDecomposer description: API reference for qiskit.synthesis.TwoQubitBasisDecomposer in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.TwoQubitBasisDecomposer --- # TwoQubitBasisDecomposer Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A class for decomposing 2-qubit unitaries into minimal number of uses of a 2-qubit basis gate. **Parameters** * **gate** ([*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"")) – Two-qubit gate to be used in the KAK decomposition. * **basis\_fidelity** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Fidelity to be assumed for applications of KAK Gate. Defaults to `1.0`. * **euler\_basis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Basis string to be provided to [`OneQubitEulerDecomposer`](qiskit.synthesis.OneQubitEulerDecomposer ""qiskit.synthesis.OneQubitEulerDecomposer"") for 1Q synthesis. Valid options are \[`'ZYZ'`, `'ZXZ'`, `'XYX'`, `'U'`, `'U3'`, `'U1X'`, `'PSX'`, `'ZSX'`, `'RR'`]. * **pulse\_optimize** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If `True`, try to do decomposition which minimizes local unitaries in between entangling gates. This will raise an exception if an optimal decomposition is not implemented. Currently, only \[\{CX, SX, RZ}] is known. If `False`, don’t attempt optimization. If `None`, attempt optimization but don’t raise if unknown. ### \_\_call\_\_ Decompose a two-qubit `unitary` over fixed basis and $SU(2)$ using the best approximation given that each basis application has a finite `basis_fidelity`. **Parameters** * **unitary** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") *or ndarray*) – $4 \times 4$ unitary to synthesize. * **basis\_fidelity** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *or None*) – Fidelity to be assumed for applications of KAK Gate. If given, overrides `basis_fidelity` given at init. * **approximate** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Approximates if basis fidelities are less than 1.0. * **\_num\_basis\_uses** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – force a particular approximation by passing a number in \[0, 3]. **Returns** Synthesized quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if `pulse_optimize` is True but we don’t know how to do it. ## Methods ### decomp0 Decompose target $\sim U_d(x, y, z)$ with $0$ uses of the basis gate. Result $U_r$ has trace: $$ \Big\vert\text{Tr}(U_r\cdot U_\text{target}^{\dag})\Big\vert = 4\Big\vert (\cos(x)\cos(y)\cos(z)+ j \sin(x)\sin(y)\sin(z)\Big\vert $$ which is optimal for all targets and bases ### decomp1 Decompose target $\sim U_d(x, y, z)$ with $1$ use of the basis gate $\sim U_d(a, b, c)$. Result $U_r$ has trace: $$ \Big\vert\text{Tr}(U_r \cdot U_\text{target}^{\dag})\Big\vert = 4\Big\vert \cos(x-a)\cos(y-b)\cos(z-c) + j \sin(x-a)\sin(y-b)\sin(z-c)\Big\vert $$ which is optimal for all targets and bases with `z==0` or `c==0`. ### decomp2\_supercontrolled Decompose target $\sim U_d(x, y, z)$ with $2$ uses of the basis gate. For supercontrolled basis $\sim U_d(\pi/4, b, 0)$, all b, result $U_r$ has trace $$ \Big\vert\text{Tr}(U_r \cdot U_\text{target}^\dag) \Big\vert = 4\cos(z) $$ which is the optimal approximation for basis of CNOT-class $\sim U_d(\pi/4, 0, 0)$ or DCNOT-class $\sim U_d(\pi/4, \pi/4, 0)$ and any target. It may be sub-optimal for $b \neq 0$ (i.e. there exists an exact decomposition for any target using $B \sim U_d(\pi/4, \pi/8, 0)$, but it may not be this decomposition). This is an exact decomposition for supercontrolled basis and target $\sim U_d(x, y, 0)$. No guarantees for non-supercontrolled basis. ### decomp3\_supercontrolled Decompose target with $3$ uses of the basis. This is an exact decomposition for supercontrolled basis $\sim U_d(\pi/4, b, 0)$, all b, and any target. No guarantees for non-supercontrolled basis. ### num\_basis\_gates Computes the number of basis gates needed in a decomposition of input unitary ### traces Give the expected traces $\Big\vert\text{Tr}(U \cdot U_\text{target}^{\dag})\Big\vert$ for a different number of basis gates. ",repo/docs/api/qiskit/1.0\qiskit.synthesis.TwoQubitBasisDecomposer.mdx "--- title: TwoQubitWeylDecomposition description: API reference for qiskit.synthesis.TwoQubitWeylDecomposition in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.TwoQubitWeylDecomposition --- # TwoQubitWeylDecomposition Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Two-qubit Weyl decomposition. Decompose two-qubit unitary $$ U = ({K_1}^l \otimes {K_1}^r) e^{(i a XX + i b YY + i c ZZ)} ({K_2}^l \otimes {K_2}^r) $$ where $$ U \in U(4),~ {K_1}^l, {K_1}^r, {K_2}^l, {K_2}^r \in SU(2) $$ and we stay in the “Weyl Chamber” $$ \pi /4 \geq a \geq b \geq |c| $$ This is an abstract factory class that instantiates itself as specialized subclasses based on the fidelity, such that the approximation error from specialization has an average gate fidelity at least as high as requested. The specialized subclasses have unique canonical representations thus avoiding problems of numerical stability. Passing non-None fidelity to specializations is treated as an assertion, raising QiskitError if forcing the specialization is more approximate than asserted. **References** 1. Cross, A. W., Bishop, L. S., Sheldon, S., Nation, P. D. & Gambetta, J. M., *Validating quantum computers using randomized model circuits*, [arXiv:1811.12926 \[quant-ph\]](https://arxiv.org/abs/1811.12926) 2. B. Kraus, J. I. Cirac, *Optimal Creation of Entanglement Using a Two-Qubit Gate*, [arXiv:0011050 \[quant-ph\]](https://arxiv.org/abs/quant-ph/0011050) 3. B. Drury, P. J. Love, *Constructive Quantum Shannon Decomposition from Cartan Involutions*, [arXiv:0806.4015 \[quant-ph\]](https://arxiv.org/abs/0806.4015) **Parameters** * **unitary\_matrix** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – The unitary to decompose. * **fidelity** – The target fidelity of the decomposed operation. ## Attributes ### a ### b ### c ### global\_phase ### K1l ### K2l ### K1r ### K2r ### unitary\_matrix ### requested\_fidelity ### calculated\_fidelity ## Methods ### actual\_fidelity Calculates the actual fidelity of the decomposed circuit to the input unitary. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### circuit Returns Weyl decomposition in circuit form. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### from\_bytes Decode bytes into [`TwoQubitWeylDecomposition`](#qiskit.synthesis.TwoQubitWeylDecomposition ""qiskit.synthesis.TwoQubitWeylDecomposition""). **Return type** [*TwoQubitWeylDecomposition*](#qiskit.synthesis.TwoQubitWeylDecomposition ""qiskit.synthesis.two_qubit.two_qubit_decompose.TwoQubitWeylDecomposition"") ### specialize Make changes to the decomposition to comply with any specialization. ",repo/docs/api/qiskit/1.0\qiskit.synthesis.TwoQubitWeylDecomposition.mdx "--- title: ApproximateCircuit description: API reference for qiskit.synthesis.unitary.aqc.ApproximateCircuit in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.unitary.aqc.ApproximateCircuit --- # ApproximateCircuit Bases: [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit""), [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") A base class that represents an approximate circuit. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubit this circuit will span. * **name** (*Optional\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – a name of the circuit. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ### thetas The property is not implemented and raises a `NotImplementedException` exception. **Returns** a vector of parameters of this circuit. ## Methods ### build **Constructs this circuit out of the parameters(thetas). Parameter values must be set before** constructing the circuit. **Parameters** **thetas** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – a vector of parameters to be set in this circuit. ",repo/docs/api/qiskit/1.0\qiskit.synthesis.unitary.aqc.ApproximateCircuit.mdx "--- title: ApproximatingObjective description: API reference for qiskit.synthesis.unitary.aqc.ApproximatingObjective in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.unitary.aqc.ApproximatingObjective --- # ApproximatingObjective Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") A base class for an optimization problem definition. An implementing class must provide at least an implementation of the `objective` method. In such case only gradient free optimizers can be used. Both method, `objective` and `gradient`, preferable to have in an implementation. ## Attributes ### num\_thetas Returns: the number of parameters in this optimization problem. ### target\_matrix Returns: a matrix being approximated ## Methods ### gradient Computes a gradient with respect to parameters given a vector of parameter values. **Parameters** **param\_values** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – a vector of parameter values for the optimization problem. **Returns** an array of gradient values. **Return type** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"") ### objective Computes a value of the objective function given a vector of parameter values. **Parameters** **param\_values** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – a vector of parameter values for the optimization problem. **Returns** a float value of the objective function. **Return type** [*SupportsFloat*](https://docs.python.org/3/library/typing.html#typing.SupportsFloat ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.synthesis.unitary.aqc.ApproximatingObjective.mdx "--- title: AQC description: API reference for qiskit.synthesis.unitary.aqc.AQC in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.unitary.aqc.AQC --- # AQC Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A generic implementation of the Approximate Quantum Compiler. This implementation is agnostic of the underlying implementation of the approximate circuit, objective, and optimizer. Users may pass corresponding implementations of the abstract classes: * The *optimizer* is an implementation of the `Minimizer` protocol, a callable used to run the optimization process. The choice of optimizer may affect overall convergence, required time for the optimization process and achieved objective value. * The *approximate circuit* represents a template which parameters we want to optimize. Currently, there’s only one implementation based on 4-rotations CNOT unit blocks: [`CNOTUnitCircuit`](qiskit.synthesis.unitary.aqc.CNOTUnitCircuit ""qiskit.synthesis.unitary.aqc.CNOTUnitCircuit""). See the paper for more details. * The *approximate objective* is tightly coupled with the approximate circuit implementation and provides two methods for computing objective function and gradient with respect to approximate circuit parameters. This objective is passed to the optimizer. Currently, there are two implementations based on 4-rotations CNOT unit blocks: [`DefaultCNOTUnitObjective`](qiskit.synthesis.unitary.aqc.DefaultCNOTUnitObjective ""qiskit.synthesis.unitary.aqc.DefaultCNOTUnitObjective"") and its accelerated version [`FastCNOTUnitObjective`](qiskit.synthesis.unitary.aqc.FastCNOTUnitObjective ""qiskit.synthesis.unitary.aqc.FastCNOTUnitObjective""). Both implementations share the same idea of maximization the Hilbert-Schmidt product between the target matrix and its approximation. The former implementation approach should be considered as a baseline one. It may suffer from performance issues, and is mostly suitable for a small number of qubits (up to 5 or 6), whereas the latter, accelerated one, can be applied to larger problems. * One should take into consideration the exponential growth of matrix size with the number of qubits because the implementation not only creates a potentially large target matrix, but also allocates a number of temporary memory buffers comparable in size to the target matrix. **Parameters** * **optimizer** (*Minimizer | None*) – an optimizer to be used in the optimization procedure of the search for the best approximate circuit. By default, the scipy minimizer with the `L-BFGS-B` method is used with max iterations set to 1000. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – a seed value to be used by a random number generator. ## Methods ### compile\_unitary Approximately compiles a circuit represented as a unitary matrix by solving an optimization problem defined by `approximating_objective` and using `approximate_circuit` as a template for the approximate circuit. **Parameters** * **target\_matrix** (*np.ndarray*) – a unitary matrix to approximate. * **approximate\_circuit** ([*ApproximateCircuit*](qiskit.synthesis.unitary.aqc.ApproximateCircuit ""qiskit.synthesis.unitary.aqc.ApproximateCircuit"")) – a template circuit that will be filled with the parameter values obtained in the optimization procedure. * **approximating\_objective** ([*ApproximatingObjective*](qiskit.synthesis.unitary.aqc.ApproximatingObjective ""qiskit.synthesis.unitary.aqc.ApproximatingObjective"")) – a definition of the optimization problem. * **initial\_point** (*np.ndarray | None*) – initial values of angles/parameters to start optimization from. ",repo/docs/api/qiskit/1.0\qiskit.synthesis.unitary.aqc.AQC.mdx "--- title: CNOTUnitCircuit description: API reference for qiskit.synthesis.unitary.aqc.CNOTUnitCircuit in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.unitary.aqc.CNOTUnitCircuit --- # CNOTUnitCircuit Bases: [`ApproximateCircuit`](qiskit.synthesis.unitary.aqc.ApproximateCircuit ""qiskit.synthesis.unitary.aqc.approximate.ApproximateCircuit"") A class that represents an approximate circuit based on CNOT unit blocks. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of qubits in this circuit. * **cnots** (*np.ndarray*) – an array of dimensions `(2, L)` indicating where the CNOT units will be placed. * **tol** (*Optional\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – angle parameter less or equal this (small) value is considered equal zero and corresponding gate is not inserted into the output circuit (because it becomes identity one in this case). * **name** (*Optional\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – name of this circuit **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – if an unsupported parameter is passed. ## Attributes ### ancillas Returns a list of ancilla bits in the order that the registers were added. ### calibrations Return calibration dictionary. The custom pulse definition of a given gate is of the form `{'gate_name': {(qubits, params): schedule}}` ### clbits Returns a list of classical bits in the order that the registers were added. ### 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 ### global\_phase Return the global phase of the current circuit scope in radians. ### instances ### 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. ### 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. ### num\_ancillas Return the number of ancilla qubits. ### num\_clbits Return number of classical bits. ### num\_parameters The number of parameter objects in the circuit. ### num\_qubits Return number of qubits. ### 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. ### 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. ### prefix ### qubits Returns a list of quantum bits in the order that the registers were added. ### thetas Returns a vector of rotation angles used by CNOT units in this circuit. **Returns** Parameters of the rotation gates in this circuit. ## Methods ### build **Constructs a Qiskit quantum circuit out of the parameters (angles) of this circuit. If a** parameter value is less in absolute value than the specified tolerance then the corresponding rotation gate will be skipped in the circuit. ",repo/docs/api/qiskit/1.0\qiskit.synthesis.unitary.aqc.CNOTUnitCircuit.mdx "--- title: CNOTUnitObjective description: API reference for qiskit.synthesis.unitary.aqc.CNOTUnitObjective in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.unitary.aqc.CNOTUnitObjective --- # CNOTUnitObjective Bases: [`ApproximatingObjective`](qiskit.synthesis.unitary.aqc.ApproximatingObjective ""qiskit.synthesis.unitary.aqc.approximate.ApproximatingObjective""), [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") A base class for a problem definition based on CNOT unit. This class may have different subclasses for objective and gradient computations. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubits. * **cnots** (*np.ndarray*) – a CNOT structure to be used in the optimization procedure. ## Attributes ### num\_cnots Returns: A number of CNOT units to be used by the approximate circuit. ### num\_thetas Returns: Number of parameters (angles) of rotation gates in this circuit. ### target\_matrix Returns: a matrix being approximated ",repo/docs/api/qiskit/1.0\qiskit.synthesis.unitary.aqc.CNOTUnitObjective.mdx "--- title: DefaultCNOTUnitObjective description: API reference for qiskit.synthesis.unitary.aqc.DefaultCNOTUnitObjective in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.unitary.aqc.DefaultCNOTUnitObjective --- # DefaultCNOTUnitObjective Bases: [`CNOTUnitObjective`](qiskit.synthesis.unitary.aqc.CNOTUnitObjective ""qiskit.synthesis.unitary.aqc.cnot_unit_objective.CNOTUnitObjective"") A naive implementation of the objective function based on CNOT units. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubits. * **cnots** (*np.ndarray*) – a CNOT structure to be used in the optimization procedure. ## Attributes ### num\_cnots Returns: A number of CNOT units to be used by the approximate circuit. ### num\_thetas Returns: Number of parameters (angles) of rotation gates in this circuit. ### target\_matrix Returns: a matrix being approximated ## Methods ### gradient Computes a gradient with respect to parameters given a vector of parameter values. **Parameters** **param\_values** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – a vector of parameter values for the optimization problem. **Returns** an array of gradient values. **Return type** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"") ### objective Computes a value of the objective function given a vector of parameter values. **Parameters** **param\_values** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – a vector of parameter values for the optimization problem. **Returns** a float value of the objective function. **Return type** [*SupportsFloat*](https://docs.python.org/3/library/typing.html#typing.SupportsFloat ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.synthesis.unitary.aqc.DefaultCNOTUnitObjective.mdx "--- title: FastCNOTUnitObjective description: API reference for qiskit.synthesis.unitary.aqc.FastCNOTUnitObjective in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.unitary.aqc.FastCNOTUnitObjective --- # FastCNOTUnitObjective Bases: [`CNOTUnitObjective`](qiskit.synthesis.unitary.aqc.CNOTUnitObjective ""qiskit.synthesis.unitary.aqc.cnot_unit_objective.CNOTUnitObjective"") Implementation of objective function and gradient calculator, which is similar to `DefaultCNOTUnitObjective` but several times faster. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubits. * **cnots** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – a CNOT structure to be used in the optimization procedure. ## Attributes ### num\_cnots Returns: A number of CNOT units to be used by the approximate circuit. ### num\_thetas Returns: Number of parameters (angles) of rotation gates in this circuit. ### target\_matrix Returns: a matrix being approximated ## Methods ### gradient Computes the gradient of objective function. See description of the base class method. **Return type** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"") ### objective Computes the objective function and some intermediate data for the subsequent gradient computation. See description of the base class method. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.synthesis.unitary.aqc.FastCNOTUnitObjective.mdx "--- title: aqc description: API reference for qiskit.synthesis.unitary.aqc in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.synthesis.unitary.aqc --- # qiskit.synthesis.unitary.aqc ## Approximate Quantum Compiler `qiskit.synthesis.unitary.aqc` Implementation of Approximate Quantum Compiler as described in the paper \[1]. ### Interface The main public interface of this module is reached by passing `unitary_synthesis_method='aqc'` to [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile""). This will swap the synthesis method to use `AQCSynthesisPlugin`. The individual classes are: | | | | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | [`AQC`](qiskit.synthesis.unitary.aqc.AQC ""qiskit.synthesis.unitary.aqc.AQC"")(\[optimizer, seed]) | A generic implementation of the Approximate Quantum Compiler. | | [`ApproximateCircuit`](qiskit.synthesis.unitary.aqc.ApproximateCircuit ""qiskit.synthesis.unitary.aqc.ApproximateCircuit"")(num\_qubits\[, name]) | A base class that represents an approximate circuit. | | [`ApproximatingObjective`](qiskit.synthesis.unitary.aqc.ApproximatingObjective ""qiskit.synthesis.unitary.aqc.ApproximatingObjective"")() | A base class for an optimization problem definition. | | [`CNOTUnitCircuit`](qiskit.synthesis.unitary.aqc.CNOTUnitCircuit ""qiskit.synthesis.unitary.aqc.CNOTUnitCircuit"")(num\_qubits, cnots\[, tol, name]) | A class that represents an approximate circuit based on CNOT unit blocks. | | [`CNOTUnitObjective`](qiskit.synthesis.unitary.aqc.CNOTUnitObjective ""qiskit.synthesis.unitary.aqc.CNOTUnitObjective"")(num\_qubits, cnots) | A base class for a problem definition based on CNOT unit. | | [`DefaultCNOTUnitObjective`](qiskit.synthesis.unitary.aqc.DefaultCNOTUnitObjective ""qiskit.synthesis.unitary.aqc.DefaultCNOTUnitObjective"")(num\_qubits, cnots) | A naive implementation of the objective function based on CNOT units. | | [`FastCNOTUnitObjective`](qiskit.synthesis.unitary.aqc.FastCNOTUnitObjective ""qiskit.synthesis.unitary.aqc.FastCNOTUnitObjective"")(num\_qubits, cnots) | Implementation of objective function and gradient calculator, which is similar to `DefaultCNOTUnitObjective` but several times faster. | ### Mathematical Detail We are interested in compiling a quantum circuit, which we formalize as finding the best circuit representation in terms of an ordered gate sequence of a target unitary matrix $U\in U(d)$, with some additional hardware constraints. In particular, we look at representations that could be constrained in terms of hardware connectivity, as well as gate depth, and we choose a gate basis in terms of CNOT and rotation gates. We recall that the combination of CNOT and rotation gates is universal in $SU(d)$ and therefore it does not limit compilation. To properly define what we mean by best circuit representation, we define the metric as the Frobenius norm between the unitary matrix of the compiled circuit $V$ and the target unitary matrix $U$, i.e., $\|V - U\|_{\mathrm{F}}$. This choice is motivated by mathematical programming considerations, and it is related to other formulations that appear in the literature. Let’s take a look at the problem in more details. Let $n$ be the number of qubits and $d=2^n$. Given a CNOT structure $ct$ and a vector of rotation angles $\theta$, the parametric circuit forms a matrix $Vct(\theta)\in SU(d)$. If we are given a target circuit forming a matrix $U\in SU(d)$, then we would like to compute $$ \mathrm{argmax}_{\theta}\frac{1}{d}|\langle Vct(\theta),U\rangle| $$ where the inner product is the Frobenius inner product. Note that $|\langle V,U\rangle|\leq d$ for all unitaries $U$ and $V$, so the objective has range in $[0,1]$. Our strategy is to maximize $$ \frac{1}{d}\Re \langle Vct(\theta),U\rangle $$ using its gradient. We will now discuss the specifics by going through an example. While the range of $Vct$ is a subset of $SU(d)$ by construction, the target circuit may form a general unitary matrix. However, for any $U\in U(d)$, $$ \frac{\exp(2\pi i k/d)}{\det(U)^{1/d}}U\in SU(d)\text{ for all }k\in\{0,\ldots,d-1\}. $$ Thus, we should normalize the target circuit by its global phase and then approximately compile the normalized circuit. We can add the global phase back in afterwards. In the algorithm let $U'$ denote the un-normalized target matrix and $U$ the normalized target matrix. Now that we have $U$, we give the gradient function to the Nesterov’s method optimizer and compute $\theta$. To add the global phase back in, we can form the control circuit as $$ \frac{\langle Vct(\theta),U'\rangle}{|\langle Vct(\theta),U'\rangle|}Vct(\theta). $$ Note that while we optimized using Nesterov’s method in the paper, this was for its convergence guarantees, not its speed in practice. It is much faster to use L-BFGS which is used as a default optimizer in this implementation. A basic usage of the AQC algorithm should consist of the following steps: ```python # Define a target circuit as a unitary matrix unitary = ... # Define a number of qubits for the algorithm, at least 3 qubits num_qubits = int(round(np.log2(unitary.shape[0]))) # Choose a layout of the CNOT structure for the approximate circuit, e.g. ``spin`` for # a linear layout. layout = options.get(""layout"") or ""spin"" # Choose a connectivity type, e.g. ``full`` for full connectivity between qubits. connectivity = options.get(""connectivity"") or ""full"" # Define a targeted depth of the approximate circuit in the number of CNOT units. depth = int(options.get(""depth"") or 0) # Generate a network made of CNOT units cnots = make_cnot_network( num_qubits=num_qubits, network_layout=layout, connectivity_type=connectivity, depth=depth ) # Create an optimizer to be used by AQC optimizer = partial(scipy.optimize.minimize, method=""L-BFGS-B"") # Create an instance aqc = AQC(optimizer) # Create a template circuit that will approximate our target circuit approximate_circuit = CNOTUnitCircuit(num_qubits=num_qubits, cnots=cnots) # Create an objective that defines our optimization problem approximating_objective = DefaultCNOTUnitObjective(num_qubits=num_qubits, cnots=cnots) # Run optimization process to compile the unitary aqc.compile_unitary( target_matrix=unitary, approximate_circuit=approximate_circuit, approximating_objective=approximating_objective ) ``` Now `approximate_circuit` is a circuit that approximates the target unitary to a certain degree and can be used instead of the original matrix. This uses a helper function, [`make_cnot_network`](#qiskit.synthesis.unitary.aqc.make_cnot_network ""qiskit.synthesis.unitary.aqc.make_cnot_network""). #### make\_cnot\_network Generates a network consisting of building blocks each containing a CNOT gate and possibly some single-qubit ones. This network models a quantum operator in question. Note, each building block has 2 input and outputs corresponding to a pair of qubits. What we actually return here is a chain of indices of qubit pairs shared by every building block in a row. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – number of qubits. * **network\_layout** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – type of network geometry, `{""sequ"", ""spin"", ""cart"", ""cyclic_spin"", ""cyclic_line""}`. * **connectivity\_type** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – type of inter-qubit connectivity, `{""full"", ""line"", ""star""}`. * **depth** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – depth of the CNOT-network, i.e. the number of layers, where each layer consists of a single CNOT-block; default value will be selected, if `L <= 0`. **Returns** **A matrix of size `(2, N)` matrix that defines layers in cnot-network, where `N`** is either equal `L`, or defined by a concrete type of the network. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – if unsupported type of CNOT-network layout or number of qubits or combination of parameters are passed. **Return type** [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"") One can take advantage of accelerated version of objective function. It implements the same mathematical algorithm as the default one `DefaultCNOTUnitObjective` but runs several times faster. Instantiation of accelerated objective function class is similar to the default case: > \# Create an objective that defines our optimization problem approximating\_objective = FastCNOTUnitObjective(num\_qubits=num\_qubits, cnots=cnots) The rest of the code in the above example does not change. **References** **\[1]: Liam Madden, Andrea Simonetto, Best Approximate Quantum Compiling Problems.** [arXiv:2106.05649](https://arxiv.org/abs/2106.05649) ",repo/docs/api/qiskit/1.0\qiskit.synthesis.unitary.aqc.mdx "--- title: XXDecomposer description: API reference for qiskit.synthesis.XXDecomposer in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.synthesis.XXDecomposer --- # XXDecomposer Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A class for optimal decomposition of 2-qubit unitaries into 2-qubit basis gates of `XX` type (i.e., each locally equivalent to $CAN(\alpha, 0, 0)$ for a possibly varying $alpha$). **Parameters** * **basis\_fidelity** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *|*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – available strengths and fidelity of each. Can be either (1) a dictionary mapping `XX` angle values to fidelity at that angle; or (2) a single float `f`, interpreted as `{pi: f, pi/2: f/2, pi/3: f/3}`. * **euler\_basis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Basis string provided to [`OneQubitEulerDecomposer`](qiskit.synthesis.OneQubitEulerDecomposer ""qiskit.synthesis.OneQubitEulerDecomposer"") for 1Q synthesis. Defaults to `""U""`. * **embodiments** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*,* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] | None*) – A dictionary mapping interaction strengths alpha to native circuits which embody the gate $CAN(\alpha, 0, 0)$. Strengths are taken so that $\pi/2$ represents the class of a full [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate""). * **backup\_optimizer** (*Callable\[...,* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] | None*) – If supplied, defers synthesis to this callable when [`XXDecomposer`](#qiskit.synthesis.XXDecomposer ""qiskit.synthesis.XXDecomposer"") has no efficient decomposition of its own. Useful for special cases involving 2 or 3 applications of $XX(\pi/2)$, in which case standard synthesis methods provide lower 1Q gate count. If `embodiments` is not passed, or if an entry is missing, it will be populated as needed using the method `_default_embodiment`. ### \_\_call\_\_ Fashions a circuit which (perhaps approximately) models the special unitary operation `unitary`, using the circuit templates supplied at initialization as `embodiments`. The routine uses `basis_fidelity` to select the optimal circuit template, including when performing exact synthesis; the contents of `basis_fidelity` is a dictionary mapping interaction strengths (scaled so that $CX = RZX(\pi/2)$ corresponds to $\pi/2$) to circuit fidelities. **Parameters** * **unitary** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") *or ndarray*) – $4 \times 4$ unitary to synthesize. * **basis\_fidelity** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *or*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Fidelity of basis gates. Can be either (1) a dictionary mapping `XX` angle values to fidelity at that angle; or (2) a single float `f`, interpreted as `{pi: f, pi/2: f/2, pi/3: f/3}`. If given, overrides the basis\_fidelity given at init. * **approximate** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Approximates if basis fidelities are less than 1.0 . **Returns** Synthesized circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ## Methods ### num\_basis\_gates Counts the number of gates that would be emitted during re-synthesis. This method is used by [`ConsolidateBlocks`](qiskit.transpiler.passes.ConsolidateBlocks ""qiskit.transpiler.passes.ConsolidateBlocks""). ",repo/docs/api/qiskit/1.0\qiskit.synthesis.XXDecomposer.mdx "--- title: AnalysisPass description: API reference for qiskit.transpiler.AnalysisPass in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.AnalysisPass --- # AnalysisPass Bases: `BasePass` An analysis pass: change property set, not DAG. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run a pass on the DAGCircuit. This is implemented by the pass developer. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – the dag on which the pass is run. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – when this is left unimplemented for a pass. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.AnalysisPass.mdx "--- title: CouplingMap description: API reference for qiskit.transpiler.CouplingMap in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.CouplingMap --- # CouplingMap Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Directed graph specifying fixed coupling. Nodes correspond to physical qubits (integers) and directed edges correspond to permitted CNOT gates, with source and destination corresponding to control and target qubits, respectively. Create coupling graph. By default, the generated coupling has no nodes. **Parameters** * **couplinglist** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or None*) – An initial coupling graph, specified as an adjacency list containing couplings, e.g. \[\[0,1], \[0,2], \[1,2]]. It is required that nodes are contiguously indexed starting at 0. Missed nodes will be added as isolated nodes in the coupling map. * **description** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A string to describe the coupling map. ## Attributes ### description ### graph ### distance\_matrix Return the distance matrix for the coupling map. For any qubits where there isn’t a path available between them the value in this position of the distance matrix will be `math.inf`. ### is\_symmetric Test if the graph is symmetric. Return True if symmetric, False otherwise ### physical\_qubits Returns a sorted list of physical\_qubits ## Methods ### add\_edge Add directed edge to coupling graph. src (int): source physical qubit dst (int): destination physical qubit ### add\_physical\_qubit Add a physical qubit to the coupling graph as a node. physical\_qubit (int): An integer representing a physical qubit. **Raises** [**CouplingError**](transpiler#qiskit.transpiler.CouplingError ""qiskit.transpiler.CouplingError"") – if trying to add duplicate qubit ### compute\_distance\_matrix Compute the full distance matrix on pairs of nodes. The distance map self.\_dist\_matrix is computed from the graph using all\_pairs\_shortest\_path\_length. This is normally handled internally by the [`distance_matrix`](#qiskit.transpiler.CouplingMap.distance_matrix ""qiskit.transpiler.CouplingMap.distance_matrix"") attribute or the [`distance()`](#qiskit.transpiler.CouplingMap.distance ""qiskit.transpiler.CouplingMap.distance"") method but can be called if you’re accessing the distance matrix outside of those or want to pre-generate it. ### connected\_components Separate a [`CouplingMap`](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") into subgraph [`CouplingMap`](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") for each connected component. The connected components of a [`CouplingMap`](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") are the subgraphs that are not part of any larger subgraph. For example, if you had a coupling map that looked like: ```python 0 --> 1 4 --> 5 ---> 6 --> 7 | | | | V V 2 --> 3 ``` then the connected components of that graph are the subgraphs: ```python 0 --> 1 | | | | V V 2 --> 3 ``` and: ```python 4 --> 5 ---> 6 --> 7 ``` For a connected [`CouplingMap`](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") object there is only a single connected component, the entire [`CouplingMap`](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap""). This method will return a list of [`CouplingMap`](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") objects, one for each connected component in this [`CouplingMap`](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap""). The data payload of each node in the [`graph`](#qiskit.transpiler.CouplingMap.graph ""qiskit.transpiler.CouplingMap.graph"") attribute will contain the qubit number in the original graph. This will enables mapping the qubit index in a component subgraph to the original qubit in the combined [`CouplingMap`](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap""). For example: ```python from qiskit.transpiler import CouplingMap cmap = CouplingMap([[0, 1], [1, 2], [2, 0], [3, 4], [4, 5], [5, 3]]) component_cmaps = cmap.connected_components() print(component_cmaps[1].graph[0]) ``` will print `3` as index `0` in the second component is qubit 3 in the original cmap. **Returns** **A list of [`CouplingMap`](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") objects for each connected** components. The order of this list is deterministic but implementation specific and shouldn’t be relied upon as part of the API. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") ### distance Returns the undirected distance between physical\_qubit1 and physical\_qubit2. **Parameters** * **physical\_qubit1** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – A physical qubit * **physical\_qubit2** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Another physical qubit **Returns** The undirected distance **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") **Raises** [**CouplingError**](transpiler#qiskit.transpiler.CouplingError ""qiskit.transpiler.CouplingError"") – if the qubits do not exist in the CouplingMap ### draw Draws the coupling map. This function calls the [`graphviz_draw()`](https://www.rustworkx.org/apiref/rustworkx.visualization.graphviz_draw.html#rustworkx.visualization.graphviz_draw ""(in rustworkx v0.14)"") function from the `rustworkx` package to draw the [`CouplingMap`](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") object. **Returns** Drawn coupling map. **Return type** PIL.Image ### from\_full Return a fully connected coupling map on n qubits. **Return type** [*CouplingMap*](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.coupling.CouplingMap"") ### from\_grid Return a coupling map of qubits connected on a grid of num\_rows x num\_columns. **Return type** [*CouplingMap*](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.coupling.CouplingMap"") ### from\_heavy\_hex Return a heavy hexagon graph coupling map. A heavy hexagon graph is described in: [https://journals.aps.org/prx/abstract/10.1103/PhysRevX.10.011022](https://journals.aps.org/prx/abstract/10.1103/PhysRevX.10.011022) **Parameters** * **distance** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The code distance for the generated heavy hex graph. The value for distance can be any odd positive integer. The distance relates to the number of qubits by: $n = \frac{5d^2 - 2d - 1}{2}$ where $n$ is the number of qubits and $d$ is the `distance` parameter. * **bidirectional** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether the edges in the output coupling graph are bidirectional or not. By default this is set to `True` **Returns** A heavy hex coupling graph **Return type** [CouplingMap](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") ### from\_heavy\_square Return a heavy square graph coupling map. A heavy square graph is described in: [https://journals.aps.org/prx/abstract/10.1103/PhysRevX.10.011022](https://journals.aps.org/prx/abstract/10.1103/PhysRevX.10.011022) **Parameters** * **distance** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The code distance for the generated heavy square graph. The value for distance can be any odd positive integer. The distance relates to the number of qubits by: $n = 3d^2 - 2d$ where $n$ is the number of qubits and $d$ is the `distance` parameter. * **bidirectional** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether the edges in the output coupling graph are bidirectional or not. By default this is set to `True` **Returns** A heavy square coupling graph **Return type** [CouplingMap](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") ### from\_hexagonal\_lattice Return a hexagonal lattice graph coupling map. **Parameters** * **rows** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of rows to generate the graph with. * **cols** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of columns to generate the graph with. * **bidirectional** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether the edges in the output coupling graph are bidirectional or not. By default this is set to `True` **Returns** A hexagonal lattice coupling graph **Return type** [CouplingMap](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") ### from\_line Return a coupling map of n qubits connected in a line. **Return type** [*CouplingMap*](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.coupling.CouplingMap"") ### from\_ring Return a coupling map of n qubits connected to each of their neighbors in a ring. **Return type** [*CouplingMap*](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.coupling.CouplingMap"") ### get\_edges Gets the list of edges in the coupling graph. **Returns** Each edge is a pair of physical qubits. **Return type** Tuple([int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)""),[int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) ### is\_connected Test if the graph is connected. Return True if connected, False otherwise ### largest\_connected\_component Return a set of qubits in the largest connected component. ### make\_symmetric Convert uni-directional edges into bi-directional. ### neighbors Return the nearest neighbors of a physical qubit. Directionality matters, i.e. a neighbor must be reachable by going one hop in the direction of an edge. ### reduce Returns a reduced coupling map that corresponds to the subgraph of qubits selected in the mapping. **Parameters** * **mapping** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A mapping of reduced qubits to device qubits. * **check\_if\_connected** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, checks that the reduced coupling map is connected. **Returns** A reduced coupling\_map for the selected qubits. **Return type** [CouplingMap](#qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") **Raises** [**CouplingError**](transpiler#qiskit.transpiler.CouplingError ""qiskit.transpiler.CouplingError"") – Reduced coupling map must be connected. ### shortest\_undirected\_path Returns the shortest undirected path between physical\_qubit1 and physical\_qubit2. **Parameters** * **physical\_qubit1** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – A physical qubit * **physical\_qubit2** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Another physical qubit **Returns** The shortest undirected path **Return type** List **Raises** [**CouplingError**](transpiler#qiskit.transpiler.CouplingError ""qiskit.transpiler.CouplingError"") – When there is no path between physical\_qubit1, physical\_qubit2. ### size Return the number of physical qubits in this graph. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.CouplingMap.mdx "--- title: InstructionDurations description: API reference for qiskit.transpiler.InstructionDurations in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.InstructionDurations --- # InstructionDurations Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Helper class to provide durations of instructions for scheduling. It stores durations (gate lengths) and dt to be used at the scheduling stage of transpiling. It can be constructed from `backend` or `instruction_durations`, which is an argument of `transpile()`. The duration of an instruction depends on the instruction (given by name), the qubits, and optionally the parameters of the instruction. Note that these fields are used as keys in dictionaries that are used to retrieve the instruction durations. Therefore, users must use the exact same parameter value to retrieve an instruction duration as the value with which it was added. ## Methods ### from\_backend Construct an [`InstructionDurations`](#qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"") object from the backend. **Parameters** **backend** ([*Backend*](qiskit.providers.Backend ""qiskit.providers.backend.Backend"")) – backend from which durations (gate lengths) and dt are extracted. **Returns** The InstructionDurations constructed from backend. **Return type** [InstructionDurations](#qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If dt and dtm is different in the backend. ### get Get the duration of the instruction with the name, qubits, and parameters. Some instructions may have a parameter dependent duration. **Parameters** * **inst** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")) – An instruction or its name to be queried. * **qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *|*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – Qubit indices that the instruction acts on. * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The unit of duration to be returned. It must be ‘s’ or ‘dt’. * **parameters** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*] | None*) – The value of the parameters of the desired instruction. **Returns** The duration of the instruction on the qubits. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")|[int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – No duration is defined for the instruction. ### units\_used Get the set of all units used in this instruction durations. **Returns** Set of units used in this instruction durations. **Return type** [set](https://docs.python.org/3/library/stdtypes.html#set ""(in Python v3.12)"")\[[str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")] ### update Update self with inst\_durations (inst\_durations overwrite self). **Parameters** * **inst\_durations** (*'InstructionDurationsType' | None*) – Instruction durations to be merged into self (overwriting self). * **dt** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Sampling duration in seconds of the target backend. **Returns** The updated InstructionDurations. **Return type** [InstructionDurations](#qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If the format of instruction\_durations is invalid. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.InstructionDurations.mdx "--- title: InstructionProperties description: API reference for qiskit.transpiler.InstructionProperties in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.InstructionProperties --- # InstructionProperties Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") A representation of the properties of a gate implementation. This class provides the optional properties that a backend can provide about an instruction. These represent the set that the transpiler can currently work with if present. However, if your backend provides additional properties for instructions you should subclass this to add additional custom attributes for those custom/additional properties by the backend. Create a new `InstructionProperties` object **Parameters** * **duration** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – The duration, in seconds, of the instruction on the specified set of qubits * **error** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – The average error rate for the instruction on the specified set of qubits. * **calibration** ([*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") *|*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") *| CalibrationEntry | None*) – The pulse representation of the instruction. ## Attributes ### duration ### error ### calibration The pulse representation of the instruction. This attribute always returns a Qiskit pulse program, but it is internally wrapped by the `CalibrationEntry` to manage unbound parameters and to uniformly handle different data representation, for example, un-parsed Pulse Qobj JSON that a backend provider may provide. This value can be overridden through the property setter in following manner. When you set either [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") or [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") this is always treated as a user-defined (custom) calibration and the transpiler may automatically attach the calibration data to the output circuit. This calibration data may appear in the wire format as an inline calibration, which may further update the backend standard instruction set architecture. If you are a backend provider who provides a default calibration data that is not needed to be attached to the transpiled quantum circuit, you can directly set `CalibrationEntry` instance to this attribute, in which you should set `user_provided=False` when you define calibration data for the entry. End users can still intentionally utilize the calibration data, for example, to run pulse-level simulation of the circuit. However, such entry doesn’t appear in the wire format, and backend must use own definition to compile the circuit down to the execution format. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.InstructionProperties.mdx "--- title: Layout description: API reference for qiskit.transpiler.Layout in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.Layout --- # Layout Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Two-ways dict to represent a Layout. construct a Layout from a bijective dictionary, mapping virtual qubits to physical qubits ## Methods ### add Adds a map element between bit and physical\_bit. If physical\_bit is not defined, bit will be mapped to a new physical bit. **Parameters** * **virtual\_bit** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – A (qu)bit. For example, (QuantumRegister(3, ‘qr’), 2). * **physical\_bit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – A physical bit. For example, 3. ### add\_register Adds at the end physical\_qubits that map each bit in reg. **Parameters** **reg** ([*Register*](qiskit.circuit.Register ""qiskit.circuit.Register"")) – A (qu)bit Register. For example, QuantumRegister(3, ‘qr’). ### combine\_into\_edge\_map Combines self and another\_layout into an “edge map”. For example: ```python self another_layout resulting edge map qr_1 -> 0 0 <- q_2 qr_1 -> q_2 qr_2 -> 2 2 <- q_1 qr_2 -> q_1 qr_3 -> 3 3 <- q_0 qr_3 -> q_0 ``` The edge map is used to compose dags via, for example, compose. **Parameters** **another\_layout** ([*Layout*](#qiskit.transpiler.Layout ""qiskit.transpiler.Layout"")) – The other layout to combine. **Returns** A “edge map”. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") **Raises** [**LayoutError**](transpiler#qiskit.transpiler.LayoutError ""qiskit.transpiler.LayoutError"") – another\_layout can be bigger than self, but not smaller. Otherwise, raises. ### copy Returns a copy of a Layout instance. ### from\_dict Populates a Layout from a dictionary. The dictionary must be a bijective mapping between virtual qubits (tuple) and physical qubits (int). **Parameters** **input\_dict** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – e.g.: ```python {(QuantumRegister(3, 'qr'), 0): 0, (QuantumRegister(3, 'qr'), 1): 1, (QuantumRegister(3, 'qr'), 2): 2} Can be written more concisely as follows: * virtual to physical:: {qr[0]: 0, qr[1]: 1, qr[2]: 2} * physical to virtual:: {0: qr[0], 1: qr[1], 2: qr[2]} ``` ### from\_intlist Converts a list of integers to a Layout mapping virtual qubits (index of the list) to physical qubits (the list values). **Parameters** * **int\_list** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of integers. * **\*qregs** (*QuantumRegisters*) – The quantum registers to apply the layout to. **Returns** The corresponding Layout object. **Return type** [Layout](#qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") **Raises** [**LayoutError**](transpiler#qiskit.transpiler.LayoutError ""qiskit.transpiler.LayoutError"") – Invalid input layout. ### from\_qubit\_list Populates a Layout from a list containing virtual qubits, Qubit or None. **Parameters** * **qubit\_list** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – e.g.: \[qr\[0], None, qr\[2], qr\[3]] * **\*qregs** (*QuantumRegisters*) – The quantum registers to apply the layout to. **Returns** the corresponding Layout object **Return type** [Layout](#qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") **Raises** [**LayoutError**](transpiler#qiskit.transpiler.LayoutError ""qiskit.transpiler.LayoutError"") – If the elements are not Qubit or None ### generate\_trivial\_layout Creates a trivial (“one-to-one”) Layout with the registers and qubits in regs. **Parameters** **\*regs** (*Registers, Qubits*) – registers and qubits to include in the layout. **Returns** A layout with all the regs in the given order. **Return type** [Layout](#qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") ### get\_physical\_bits Returns the dictionary where the keys are physical (qu)bits and the values are virtual (qu)bits. ### get\_registers Returns the registers in the layout \[QuantumRegister(2, ‘qr0’), QuantumRegister(3, ‘qr1’)] :returns: A set of Registers in the layout :rtype: Set ### get\_virtual\_bits Returns the dictionary where the keys are virtual (qu)bits and the values are physical (qu)bits. ### order\_based\_on\_type decides which one is physical/virtual based on the type. Returns (virtual, physical) ### reorder\_bits Given an ordered list of bits, reorder them according to this layout. The list of bits must exactly match the virtual bits in this layout. **Parameters** **bits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Bit*](qiskit.circuit.Bit ""qiskit.circuit.Bit"")*]*) – the bits to reorder. **Returns** ordered bits. **Return type** List ### swap Swaps the map between left and right. **Parameters** * **left** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") *or*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Item to swap with right. * **right** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"") *or*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Item to swap with left. **Raises** [**LayoutError**](transpiler#qiskit.transpiler.LayoutError ""qiskit.transpiler.LayoutError"") – If left and right have not the same type. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.Layout.mdx "--- title: ALAPSchedule description: API reference for qiskit.transpiler.passes.ALAPSchedule in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.ALAPSchedule --- # ALAPSchedule Bases: `BaseSchedulerTransform` ALAP Scheduling pass, which schedules the **stop** time of instructions as late as possible. See `BaseSchedulerTransform` for the detailed behavior of the control flow operation, i.e. `c_if`. The class `qiskit.transpiler.passes.scheduling.alap.ALAPSchedule` is pending deprecation as of qiskit 0.21.0. It will be marked deprecated in a future release, and then removed no earlier than 3 months after the release date. Instead, use [`ALAPScheduleAnalysis`](qiskit.transpiler.passes.ALAPScheduleAnalysis ""qiskit.transpiler.passes.ALAPScheduleAnalysis""), which is an analysis pass that requires a padding pass to later modify the circuit. ## Attributes ### CONDITIONAL\_SUPPORTED , )"" /> ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the ALAPSchedule pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to schedule. **Returns** A scheduled DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the circuit is not mapped on physical qubits. * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if conditional bit is added to non-supported instruction. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.ALAPSchedule.mdx "--- title: ALAPScheduleAnalysis description: API reference for qiskit.transpiler.passes.ALAPScheduleAnalysis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.ALAPScheduleAnalysis --- # ALAPScheduleAnalysis Bases: `BaseScheduler` ALAP Scheduling pass, which schedules the **stop** time of instructions as late as possible. See the [Scheduling Stage](transpiler#scheduling-stage) section in the [`qiskit.transpiler`](transpiler#module-qiskit.transpiler ""qiskit.transpiler"") module documentation for the detailed behavior of the control flow operation, i.e. `c_if`. Scheduler initializer. **Parameters** * **durations** – Durations of instructions to be used in scheduling * **target** – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend, if both `durations` and this are specified then this argument will take precedence and `durations` will be ignored. ## Attributes ### CONDITIONAL\_SUPPORTED , )"" /> ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the ALAPSchedule pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to schedule. **Returns** A scheduled DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the circuit is not mapped on physical qubits. * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if conditional bit is added to non-supported instruction. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.ALAPScheduleAnalysis.mdx "--- title: AlignMeasures description: API reference for qiskit.transpiler.passes.AlignMeasures in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.AlignMeasures --- # AlignMeasures Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Measurement alignment. This is a control electronics aware optimization pass. In many quantum computing architectures gates (instructions) are implemented with shaped analog stimulus signals. These signals are digitally stored in the waveform memory of the control electronics and converted into analog voltage signals by electronic components called digital to analog converters (DAC). In a typical hardware implementation of superconducting quantum processors, a single qubit instruction is implemented by a microwave signal with the duration of around several tens of ns with a per-sample time resolution of \~0.1-10ns, as reported by `backend.configuration().dt`. In such systems requiring higher DAC bandwidth, control electronics often defines a pulse granularity, in other words a data chunk, to allow the DAC to perform the signal conversion in parallel to gain the bandwidth. Measurement alignment is required if a backend only allows triggering `measure` instructions at a certain multiple value of this pulse granularity. This value is usually provided by `backend.configuration().timing_constraints`. In Qiskit SDK, the duration of delay can take arbitrary value in units of `dt`, thus circuits involving delays may violate the above alignment constraint (i.e. misalignment). This pass shifts measurement instructions to a new time position to fix the misalignment, by inserting extra delay right before the measure instructions. The input of this pass should be scheduled [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit""), thus one should select one of the scheduling passes ([`ALAPSchedule`](qiskit.transpiler.passes.ALAPSchedule ""qiskit.transpiler.passes.ALAPSchedule"") or `ASAPSchedule`) before calling this. **Examples** We assume executing the following circuit on a backend with `alignment=16`. ```python ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├ └───┘└────────────────┘└╥┘ c: 1/════════════════════════╩═ 0 ``` Note that delay of 100 dt induces a misalignment of 4 dt at the measurement. This pass appends an extra 12 dt time shift to the input circuit. ```python ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├ └───┘└────────────────┘└╥┘ c: 1/════════════════════════╩═ 0 ``` This pass always inserts a positive delay before measurements rather than reducing other delays. **Notes** The Backend may allow users to execute circuits violating the alignment constraint. However, it may return meaningless measurement data mainly due to the phase error. Create new pass. The class `qiskit.transpiler.passes.scheduling.alignments.align_measures.AlignMeasures` is pending deprecation as of qiskit 0.21.0. It will be marked deprecated in a future release, and then removed no earlier than 3 months after the release date. Instead, use [`ConstrainedReschedule`](qiskit.transpiler.passes.ConstrainedReschedule ""qiskit.transpiler.passes.ConstrainedReschedule""), which performs the same function but also supports aligning to additional timing constraints. **Parameters** **alignment** – Integer number representing the minimum time resolution to trigger measure instruction in units of `dt`. This value depends on the control electronics of your quantum processor. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the measurement alignment pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to be checked. **Returns** DAG with consistent timing and op nodes annotated with duration. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If circuit is not scheduled. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.AlignMeasures.mdx "--- title: ApplyLayout description: API reference for qiskit.transpiler.passes.ApplyLayout in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.ApplyLayout --- # ApplyLayout Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Transform a circuit with virtual qubits into a circuit with physical qubits. Transforms a DAGCircuit with virtual qubits into a DAGCircuit with physical qubits by applying the Layout given in property\_set. Requires either of passes to set/select Layout, e.g. SetLayout, TrivialLayout. Assumes the Layout has full physical qubits. If a post layout pass is run and sets the `post_layout` property set field with a new layout to use after `ApplyLayout` has already run once this pass will compact the layouts so that we apply `original_virtual` -> `existing_layout` -> `new_layout` -> `new_physical` so that the output circuit and layout combination become: `original_virtual` -> `new_physical` ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the ApplyLayout pass on `dag`. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to map. **Returns** A mapped DAG (with physical qubits). **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if no layout is found in `property_set` or no full physical qubits. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.ApplyLayout.mdx "--- title: ASAPSchedule description: API reference for qiskit.transpiler.passes.ASAPSchedule in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.ASAPSchedule --- # ASAPSchedule Bases: `BaseSchedulerTransform` ASAP Scheduling pass, which schedules the start time of instructions as early as possible.. See `BaseSchedulerTransform` for the detailed behavior of the control flow operation, i.e. `c_if`. This base class has been superseded by [`ASAPScheduleAnalysis`](qiskit.transpiler.passes.ASAPScheduleAnalysis ""qiskit.transpiler.passes.ASAPScheduleAnalysis"") and the new scheduling workflow. It will be deprecated and subsequently removed in a future release. The class `qiskit.transpiler.passes.scheduling.asap.ASAPSchedule` is pending deprecation as of qiskit 0.21.0. It will be marked deprecated in a future release, and then removed no earlier than 3 months after the release date. Instead, use [`ASAPScheduleAnalysis`](qiskit.transpiler.passes.ASAPScheduleAnalysis ""qiskit.transpiler.passes.ASAPScheduleAnalysis""), which is an analysis pass that requires a padding pass to later modify the circuit. ## Attributes ### CONDITIONAL\_SUPPORTED , )"" /> ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the ASAPSchedule pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to schedule. **Returns** A scheduled DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the circuit is not mapped on physical qubits. * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if conditional bit is added to non-supported instruction. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.ASAPSchedule.mdx "--- title: ASAPScheduleAnalysis description: API reference for qiskit.transpiler.passes.ASAPScheduleAnalysis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.ASAPScheduleAnalysis --- # ASAPScheduleAnalysis Bases: `BaseScheduler` ASAP Scheduling pass, which schedules the start time of instructions as early as possible. See the [Scheduling Stage](transpiler#scheduling-stage) section in the [`qiskit.transpiler`](transpiler#module-qiskit.transpiler ""qiskit.transpiler"") module documentation for the detailed behavior of the control flow operation, i.e. `c_if`. Scheduler initializer. **Parameters** * **durations** – Durations of instructions to be used in scheduling * **target** – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend, if both `durations` and this are specified then this argument will take precedence and `durations` will be ignored. ## Attributes ### CONDITIONAL\_SUPPORTED , )"" /> ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the ASAPSchedule pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to schedule. **Returns** A scheduled DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the circuit is not mapped on physical qubits. * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if conditional bit is added to non-supported instruction. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.ASAPScheduleAnalysis.mdx "--- title: BarrierBeforeFinalMeasurements description: API reference for qiskit.transpiler.passes.BarrierBeforeFinalMeasurements in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.BarrierBeforeFinalMeasurements --- # BarrierBeforeFinalMeasurements Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Add a barrier before final measurements. This pass adds a barrier before the set of final measurements. Measurements are considered final if they are followed by no other operations (aside from other measurements or barriers.) ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the BarrierBeforeFinalMeasurements pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.BarrierBeforeFinalMeasurements.mdx "--- title: BasicSwap description: API reference for qiskit.transpiler.passes.BasicSwap in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.BasicSwap --- # BasicSwap Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Map (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates. The basic mapper is a minimum effort to insert swap gates to map the DAG onto a coupling map. When a cx is not in the coupling map possibilities, it inserts one or more swaps in front to make it compatible. BasicSwap initializer. **Parameters** * **coupling\_map** (*Union\[*[*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")*,* [*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")*]*) – Directed graph represented a coupling map. * **fake\_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if true, it will only pretend to do routing, i.e., no swap is effectively added. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the BasicSwap pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to map. **Returns** A mapped DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the coupling map or the layout are not * **compatible with the DAG**\*\*, or \*\***if the coupling\_map=None.** – ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.BasicSwap.mdx "--- title: BasisTranslator description: API reference for qiskit.transpiler.passes.BasisTranslator in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.BasisTranslator --- # BasisTranslator Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Translates gates to a target basis by searching for a set of translations from a given EquivalenceLibrary. This pass operates in several steps: * Determine the source basis from the input circuit. * Perform a Dijkstra search over basis sets, starting from the device’s target\_basis new gates are being generated using the rules from the provided EquivalenceLibrary and the search stops if all gates in the source basis have been generated. * The found path, as a set of rules from the EquivalenceLibrary, is composed into a set of gate replacement rules. * The composed replacement rules are applied in-place to each op node which is not already in the target\_basis. If the target keyword argument is specified and that [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") objects contains operations which are non-global (i.e. they are defined only for a subset of qubits), as calculated by [`get_non_global_operation_names()`](qiskit.transpiler.Target#get_non_global_operation_names ""qiskit.transpiler.Target.get_non_global_operation_names""), this pass will attempt to match the output translation to those constraints. For 1 qubit operations this is straightforward, the pass will perform a search using the union of the set of global operations with the set of operations defined solely on that qubit. For multi-qubit gates this is a bit more involved, while the behavior is initially similar to the single qubit case, just using all the qubits the operation is run on (where order is not significant) isn’t sufficient. We also need to consider any potential local qubits defined on subsets of the quantum arguments for the multi-qubit operation. This means the target used for the search of a non-global multi-qubit gate is the union of global operations, non-global multi-qubit gates sharing the same qubits, and any non-global gates defined on any subset of the qubits used. In the case of non-global operations it is possible for a single execution of this pass to output an incomplete translation if any non-global gates are defined on qubits that are a subset of a larger multi-qubit gate. For example, if you have a `u` gate only defined on qubit 0 and an `x` gate only on qubit 1 it is possible when translating a 2 qubit operation on qubit 0 and 1 that the output might have `u` on qubit 1 and `x` on qubit 0. Typically running this pass a second time will correct these issues. ## Translation Errors This pass will error if there is no path to translate an input gate to the specified basis. However, during a typical/default preset passmanager this pass gets run multiple times at different stages of the compilation pipeline. This means that potentially the input gates that are getting translated were not in the input circuit to [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") as they were generated by an intermediate transform in the circuit. When this error occurs it typically means that either the target basis is not universal or there are additional equivalence rules needed in the :clas:\~.EquivalenceLibrary\` instance being used by the :class:\~.BasisTranslator\` pass. You can refer to [Custom Basis Gates](providers#custom-basis-gates) for details on adding custom equivalence rules. Initialize a BasisTranslator instance. **param equivalence\_library** The equivalence library which will be used by the BasisTranslator pass. (Instructions in this library will not be unrolled by this pass.) **type equivalence\_library** EquivalenceLibrary **param target\_basis** Target basis names to unroll to, e.g. `['u3', 'cx']`. **type target\_basis** list\[str] **param target** The backend compilation target **type target** Target **param min\_qubits** The minimum number of qubits for operations in the input dag to translate. **type min\_qubits** int ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Translate an input DAGCircuit to the target basis. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – input dag **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the target basis cannot be reached **Returns** translated circuit. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.BasisTranslator.mdx "--- title: CheckGateDirection description: API reference for qiskit.transpiler.passes.CheckGateDirection in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CheckGateDirection --- # CheckGateDirection Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Check if the two-qubit gates follow the right direction with respect to the coupling map. CheckGateDirection initializer. **Parameters** * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")) – Directed graph representing a coupling map. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The backend target to use for this pass. If this is specified it will be used instead of the coupling map ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CheckGateDirection pass on dag. If dag is mapped and the direction is correct the property is\_direction\_mapped is set to True (or to False otherwise). **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to check. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CheckGateDirection.mdx "--- title: CheckMap description: API reference for qiskit.transpiler.passes.CheckMap in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CheckMap --- # CheckMap Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Check if a DAG circuit is already mapped to a coupling map. Check if a DAGCircuit is mapped to `coupling_map` by checking that all 2-qubit interactions are laid out to be on adjacent qubits in the global coupling map of the device, setting the property set field (either specified with `property_set_field` or the default `is_swap_mapped`) to `True` or `False` accordingly. Note this does not validate directionality of the connectivity between qubits. If you need to check gates are implemented in a native direction for a target use the [`CheckGateDirection`](qiskit.transpiler.passes.CheckGateDirection ""qiskit.transpiler.passes.CheckGateDirection"") pass instead. CheckMap initializer. **Parameters** * **coupling\_map** (*Union\[*[*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")*,* [*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")*]*) – Directed graph representing a coupling map. * **property\_set\_field** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – An optional string to specify the property set field to store the result of the check. If not default the result is stored in `""is_swap_mapped""`. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CheckMap pass on dag. If dag is mapped to coupling\_map, the property is\_swap\_mapped is set to True (or to False otherwise). **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to map. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CheckMap.mdx "--- title: Collect1qRuns description: API reference for qiskit.transpiler.passes.Collect1qRuns in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Collect1qRuns --- # Collect1qRuns Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Collect one-qubit subcircuits. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the Collect1qBlocks pass on dag. The blocks contain “op” nodes in topological order such that all gates in a block act on the same qubits and are adjacent in the circuit. After the execution, `property_set['run_list']` is set to a list of tuples of “op” node. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Collect1qRuns.mdx "--- title: Collect2qBlocks description: API reference for qiskit.transpiler.passes.Collect2qBlocks in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Collect2qBlocks --- # Collect2qBlocks Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Collect two-qubit subcircuits. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the Collect2qBlocks pass on dag. The blocks contain “op” nodes in topological order such that all gates in a block act on the same qubits and are adjacent in the circuit. After the execution, `property_set['block_list']` is set to a list of tuples of “op” node. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Collect2qBlocks.mdx "--- title: CollectCliffords description: API reference for qiskit.transpiler.passes.CollectCliffords in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CollectCliffords --- # CollectCliffords Bases: `CollectAndCollapse` Collects blocks of Clifford gates and replaces them by a [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") object. CollectCliffords initializer. **Parameters** * **do\_commutative\_analysis** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, exploits commutativity relations between nodes. * **split\_blocks** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, splits collected blocks into sub-blocks over disjoint qubit subsets. * **min\_block\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – specifies the minimum number of gates in the block for the block to be collected. * **split\_layers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, splits collected blocks into sub-blocks over disjoint qubit subsets. * **collect\_from\_back** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – specifies if blocks should be collected started from the end of the circuit. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CollectLinearFunctions pass on dag. :param dag: the DAG to be optimized. :type dag: DAGCircuit **Returns** the optimized DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CollectCliffords.mdx "--- title: CollectLinearFunctions description: API reference for qiskit.transpiler.passes.CollectLinearFunctions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CollectLinearFunctions --- # CollectLinearFunctions Bases: `CollectAndCollapse` Collect blocks of linear gates ([`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"") and [`SwapGate`](qiskit.circuit.library.SwapGate ""qiskit.circuit.library.SwapGate"") gates) and replaces them by linear functions ([`LinearFunction`](qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.LinearFunction"")). CollectLinearFunctions initializer. **Parameters** * **do\_commutative\_analysis** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, exploits commutativity relations between nodes. * **split\_blocks** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, splits collected blocks into sub-blocks over disjoint qubit subsets. * **min\_block\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – specifies the minimum number of gates in the block for the block to be collected. * **split\_layers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, splits collected blocks into sub-blocks over disjoint qubit subsets. * **collect\_from\_back** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – specifies if blocks should be collected started from the end of the circuit. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CollectLinearFunctions pass on dag. :param dag: the DAG to be optimized. :type dag: DAGCircuit **Returns** the optimized DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CollectLinearFunctions.mdx "--- title: CollectMultiQBlocks description: API reference for qiskit.transpiler.passes.CollectMultiQBlocks in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CollectMultiQBlocks --- # CollectMultiQBlocks Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Collect sequences of uninterrupted gates acting on groups of qubits. `max_block_size` specifies the maximum number of qubits that can be acted upon by any single group of gates Traverse the DAG and find blocks of gates that act consecutively on groups of qubits. Write the blocks to `property_set` as a list of blocks of the form: ```python [[g0, g1, g2], [g4, g5]] ``` Blocks are reported in a valid topological order. Further, the gates within each block are also reported in topological order Some gates may not be present in any block (e.g. if the number of operands is greater than `max_block_size`) A Disjoint Set Union data structure (DSU) is used to maintain blocks as gates are processed. This data structure points each qubit to a set at all times and the sets correspond to current blocks. These change over time and the data structure allows these changes to be done quickly. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### find\_set DSU function for finding root of set of items If my parent is myself, I am the root. Otherwise we recursively find the root for my parent. After that, we assign my parent to be my root, saving recursion in the future. ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CollectMultiQBlocks pass on dag. The blocks contain “op” nodes in topological sort order such that all gates in a block act on the same set of qubits and are adjacent in the circuit. The blocks are built by examining predecessors and successors of “cx” gates in the circuit. u1, u2, u3, cx, id gates will be included. After the execution, `property_set['block_list']` is set to a list of tuples of `DAGNode` objects ### union\_set DSU function for unioning two sets together Find the roots of each set. Then assign one to have the other as its parent, thus liking the sets. Merges smaller set into larger set in order to have better runtime ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CollectMultiQBlocks.mdx "--- title: CommutationAnalysis description: API reference for qiskit.transpiler.passes.CommutationAnalysis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CommutationAnalysis --- # CommutationAnalysis Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Analysis pass to find commutation relations between DAG nodes. `property_set['commutation_set']` is a dictionary that describes the commutation relations on a given wire, all the gates on a wire are grouped into a set of gates that commute. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CommutationAnalysis pass on dag. Run the pass on the DAG, and write the discovered commutation relations into the `property_set`. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CommutationAnalysis.mdx "--- title: CommutativeCancellation description: API reference for qiskit.transpiler.passes.CommutativeCancellation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CommutativeCancellation --- # CommutativeCancellation Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Cancel the redundant (self-adjoint) gates through commutation relations. Pass for cancelling self-inverse gates/rotations. The cancellation utilizes the commutation relations in the circuit. Gates considered include: ```python H, X, Y, Z, CX, CY, CZ ``` CommutativeCancellation initializer. **Parameters** * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – Basis gates to consider, e.g. `['u3', 'cx']`. For the effects of this pass, the basis is the set intersection between the `basis_gates` parameter and the gates in the dag. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend, if both `basis_gates` and `target` are specified then this argument will take precedence and `basis_gates` will be ignored. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CommutativeCancellation pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the DAG to be optimized. **Returns** the optimized DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – when the 1-qubit rotation gates are not found ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CommutativeCancellation.mdx "--- title: CommutativeInverseCancellation description: API reference for qiskit.transpiler.passes.CommutativeInverseCancellation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CommutativeInverseCancellation --- # CommutativeInverseCancellation Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Cancel pairs of inverse gates exploiting commutation relations. **Parameters** * **matrix\_based** – If `True`, uses matrix representations to check whether two operations are inverse of each other. This makes the checks more powerful, and, in addition, allows canceling pairs of operations that are inverse up to a phase, while updating the global phase of the circuit accordingly. Generally this leads to more reductions at the expense of increased runtime. * **max\_qubits** – Limits the number of qubits in matrix-based commutativity and inverse checks. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CommutativeInverseCancellation pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – the directed acyclic graph to run on. **Returns** Transformed DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CommutativeInverseCancellation.mdx "--- title: Commuting2qGateRouter description: API reference for qiskit.transpiler.passes.Commuting2qGateRouter in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Commuting2qGateRouter --- # Commuting2qGateRouter Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") A class to swap route one or more commuting gates to the coupling map. This pass routes blocks of commuting two-qubit gates encapsulated as `Commuting2qBlock` instructions. This pass will not apply to other instructions. The mapping to the coupling map is done using swap strategies, see `SwapStrategy`. The swap strategy should suit the problem and the coupling map. This transpiler pass should ideally be executed before the quantum circuit is enlarged with any idle ancilla qubits. Otherwise, we may swap qubits outside the portion of the chip we want to use. Therefore, the swap strategy and its associated coupling map do not represent physical qubits. Instead, they represent an intermediate mapping that corresponds to the physical qubits once the initial layout is applied. The example below shows how to map a four qubit [`PauliEvolutionGate`](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate"") to qubits 0, 1, 3, and 4 of the five qubit device with the coupling map ```python 0 -- 1 -- 2 | 3 | 4 ``` To do this we use a line swap strategy for qubits 0, 1, 3, and 4 defined it in terms of virtual qubits 0, 1, 2, and 3. ```python from qiskit import QuantumCircuit from qiskit.circuit.library import PauliEvolutionGate from qiskit.quantum_info import SparsePauliOp from qiskit.transpiler import Layout, CouplingMap, PassManager from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import ApplyLayout from qiskit.transpiler.passes import SetLayout from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import ( SwapStrategy, FindCommutingPauliEvolutions, Commuting2qGateRouter, ) # Define the circuit on virtual qubits op = SparsePauliOp.from_list([(""IZZI"", 1), (""ZIIZ"", 2), (""ZIZI"", 3)]) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) # Define the swap strategy on qubits before the initial_layout is applied. swap_strat = SwapStrategy.from_line([0, 1, 2, 3]) # Chose qubits 0, 1, 3, and 4 from the backend coupling map shown above. backend_cmap = CouplingMap(couplinglist=[(0, 1), (1, 2), (1, 3), (3, 4)]) initial_layout = Layout.from_intlist([0, 1, 3, 4], *circ.qregs) pm_pre = PassManager( [ FindCommutingPauliEvolutions(), Commuting2qGateRouter(swap_strat), SetLayout(initial_layout), FullAncillaAllocation(backend_cmap), EnlargeWithAncilla(), ApplyLayout(), ] ) # Insert swap gates, map to initial_layout and finally enlarge with ancilla. pm_pre.run(circ).draw(""mpl"") ``` This pass manager relies on the `current_layout` which corresponds to the qubit layout as swap gates are applied. The pass will traverse all nodes in the dag. If a node should be routed using a swap strategy then it will be decomposed into sub-instructions with swap layers in between and the `current_layout` will be modified. Nodes that should not be routed using swap strategies will be added back to the dag taking the `current_layout` into account. **Parameters** * **swap\_strategy** – An instance of a `SwapStrategy` that holds the swap layers that are used, and the order in which to apply them, to map the instruction to the hardware. If this field is not given, it should be contained in the property set of the pass. This allows other passes to determine the most appropriate swap strategy at run-time. * **edge\_coloring** – An optional edge coloring of the coupling map (I.e. no two edges that share a node have the same color). If the edge coloring is given then the commuting gates that can be simultaneously applied given the current qubit permutation are grouped according to the edge coloring and applied according to this edge coloring. Here, a color is an int which is used as the index to define and access the groups of commuting gates that can be applied simultaneously. If the edge coloring is not given then the sets will be built-up using a greedy algorithm. The edge coloring is useful to position gates such as `RZZGate`s next to swap gates to exploit CX cancellations. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the pass by decomposing the nodes it applies on. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – The dag to which we will add swaps. **Returns** A dag where swaps have been added for the intended gate type. **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If the swap strategy was not given at init time and there is no swap strategy in the property set. * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If the quantum circuit contains more than one qubit register. * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If there are qubits that are not contained in the quantum register. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### swap\_decompose Take an instance of `Commuting2qBlock` and map it to the coupling map. The mapping is done with the swap strategy. **Parameters** * **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – The dag which contains the `Commuting2qBlock` we route. * **node** ([*DAGOpNode*](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.dagnode.DAGOpNode"")) – A node whose operation is a `Commuting2qBlock`. * **current\_layout** ([*Layout*](qiskit.transpiler.Layout ""qiskit.transpiler.layout.Layout"")) – The layout before the swaps are applied. This function will modify the layout so that subsequent gates can be properly composed on the dag. * **swap\_strategy** (*SwapStrategy*) – The swap strategy used to decompose the node. **Returns** A dag that is compatible with the coupling map where swap gates have been added to map the gates in the `Commuting2qBlock` to the hardware. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Commuting2qGateRouter.mdx "--- title: ConsolidateBlocks description: API reference for qiskit.transpiler.passes.ConsolidateBlocks in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.ConsolidateBlocks --- # ConsolidateBlocks Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Replace each block of consecutive gates by a single Unitary node. Pass to consolidate sequences of uninterrupted gates acting on the same qubits into a Unitary node, to be resynthesized later, to a potentially more optimal subcircuit. **Notes** This pass assumes that the ‘blocks\_list’ property that it reads is given such that blocks are in topological order. The blocks are collected by a previous pass, such as Collect2qBlocks. ConsolidateBlocks initializer. If `kak_basis_gate` is not `None` it will be used as the basis gate for KAK decomposition. Otherwise, if `basis_gates` is not `None` a basis gate will be chosen from this list. Otherwise, the basis gate will be [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate""). **Parameters** * **kak\_basis\_gate** ([*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"")) – Basis gate for KAK decomposition. * **force\_consolidate** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Force block consolidation. * **basis\_gates** (*List(*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*)*) – Basis gates from which to choose a KAK gate. * **approximation\_degree** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – a float between $[0.0, 1.0]$. Lower approximates more. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The target object for the compilation target backend. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the ConsolidateBlocks pass on dag. Iterate over each block and replace it with an equivalent Unitary on the same wires. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.ConsolidateBlocks.mdx "--- title: ConstrainedReschedule description: API reference for qiskit.transpiler.passes.ConstrainedReschedule in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.ConstrainedReschedule --- # ConstrainedReschedule Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Rescheduler pass that updates node start times to conform to the hardware alignments. This pass shifts DAG node start times previously scheduled with one of the scheduling passes, e.g. [`ASAPScheduleAnalysis`](qiskit.transpiler.passes.ASAPScheduleAnalysis ""qiskit.transpiler.passes.ASAPScheduleAnalysis"") or [`ALAPScheduleAnalysis`](qiskit.transpiler.passes.ALAPScheduleAnalysis ""qiskit.transpiler.passes.ALAPScheduleAnalysis""), so that every instruction start time satisfies alignment constraints. **Examples** We assume executing the following circuit on a backend with 16 dt of acquire alignment. ```python ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├ └───┘└────────────────┘└╥┘ c: 1/════════════════════════╩═ 0 ``` Note that delay of 100 dt induces a misalignment of 4 dt at the measurement. This pass appends an extra 12 dt time shift to the input circuit. ```python ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├ └───┘└────────────────┘└╥┘ c: 1/════════════════════════╩═ 0 ``` **Notes** Your backend may execute circuits violating these alignment constraints. However, you may obtain erroneous measurement result because of the untracked phase originating in the instruction misalignment. Create new rescheduler pass. The alignment values depend on the control electronics of your quantum processor. **Parameters** * **acquire\_alignment** – Integer number representing the minimum time resolution to trigger acquisition instruction in units of `dt`. * **pulse\_alignment** – Integer number representing the minimum time resolution to trigger gate instruction in units of `dt`. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run rescheduler. This pass should perform rescheduling to satisfy: > * All DAGOpNode nodes (except for compiler directives) are placed at start time satisfying hardware alignment constraints. > * The end time of a node does not overlap with the start time of successor nodes. Assumptions: > * Topological order and absolute time order of DAGOpNode are consistent. > * All bits in either qargs or cargs associated with node synchronously start. > * Start time of qargs and cargs may different due to I/O latency. Based on the configurations above, the rescheduler pass takes the following strategy: 1. **The nodes are processed in the topological order, from the beginning of** the circuit (i.e. from left to right). For every node (including compiler directives), the function `_push_node_back` performs steps 2 and 3. 2. **If the start time of the node violates the alignment constraint,** the start time is increased to satisfy the constraint. 3. **Each immediate successor whose start\_time overlaps the node’s end\_time is** pushed backwards (towards the end of the wire). Note that at this point the shifted successor does not need to satisfy the constraints, but this will be taken care of when that successor node itself is processed. 4. **After every node is processed, all misalignment constraints will be resolved,** and there will be no overlap between the nodes. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – DAG circuit to be rescheduled with constraints. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If circuit is not scheduled. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.ConstrainedReschedule.mdx "--- title: ContainsInstruction description: API reference for qiskit.transpiler.passes.ContainsInstruction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.ContainsInstruction --- # ContainsInstruction Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") An analysis pass to detect if the DAG contains a specific instruction. This pass takes in a single instruction name for example `'delay'` and will set the property set `contains_delay` to `True` if the DAG contains that instruction and `False` if it does not. ContainsInstruction initializer. **Parameters** * **instruction\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| Iterable\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – The instruction or instructions to check are in the DAG. The output in the property set is set to `contains_` prefixed on each value for this parameter. * **recurse** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if `True` (default), then recurse into control-flow operations. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the ContainsInstruction pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.ContainsInstruction.mdx "--- title: ConvertConditionsToIfOps description: API reference for qiskit.transpiler.passes.ConvertConditionsToIfOps in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.ConvertConditionsToIfOps --- # ConvertConditionsToIfOps Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Convert instructions whose `condition` attribute is set to a non-`None` value into the equivalent single-statement `IfElseBlock`. This is a simple pass aimed at easing the conversion from the old style of using [`InstructionSet.c_if()`](qiskit.circuit.InstructionSet#c_if ""qiskit.circuit.InstructionSet.c_if"") into the new style of using more complex conditional logic. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run a pass on the DAGCircuit. This is implemented by the pass developer. **Parameters** **dag** – the dag on which the pass is run. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – when this is left unimplemented for a pass. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.ConvertConditionsToIfOps.mdx "--- title: CountOps description: API reference for qiskit.transpiler.passes.CountOps in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CountOps --- # CountOps Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Count the operations in a DAG circuit. The result is saved in `property_set['count_ops']` as an integer. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CountOps pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CountOps.mdx "--- title: CountOpsLongestPath description: API reference for qiskit.transpiler.passes.CountOpsLongestPath in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CountOpsLongestPath --- # CountOpsLongestPath Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Count the operations on the longest path in a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit""). The result is saved in `property_set['count_ops_longest_path']` as an integer. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CountOpsLongestPath pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CountOpsLongestPath.mdx "--- title: CSPLayout description: API reference for qiskit.transpiler.passes.CSPLayout in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CSPLayout --- # CSPLayout Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") If possible, chooses a Layout as a CSP, using backtracking. If possible, chooses a Layout as a CSP, using backtracking. If not possible, does not set the layout property. In all the cases, the property CSPLayout\_stop\_reason will be added with one of the following values: * solution found: If a perfect layout was found. * nonexistent solution: If no perfect layout was found and every combination was checked. * call limit reached: If no perfect layout was found and the call limit was reached. * time limit reached: If no perfect layout was found and the time limit was reached. **Parameters** * **coupling\_map** (*Union\[*[*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")*,* [*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")*]*) – Directed graph representing a coupling map. * **strict\_direction** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, considers the direction of the coupling map. Default is False. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Sets the seed of the PRNG. * **call\_limit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Amount of times that `constraint.RecursiveBacktrackingSolver.recursiveBacktracking` will be called. None means no call limit. Default: 1000. * **time\_limit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Amount of seconds that the pass will try to find a solution. None means no time limit. Default: 10 seconds. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run run the layout method ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CSPLayout.mdx "--- title: CXCancellation description: API reference for qiskit.transpiler.passes.CXCancellation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.CXCancellation --- # CXCancellation Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Cancel back-to-back `cx` gates in dag. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CXCancellation pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the directed acyclic graph to run on. **Returns** Transformed DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.CXCancellation.mdx "--- title: DAGFixedPoint description: API reference for qiskit.transpiler.passes.DAGFixedPoint in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.DAGFixedPoint --- # DAGFixedPoint Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Check if the DAG has reached a fixed point. A dummy analysis pass that checks if the DAG a fixed point (the DAG is not modified anymore). The result is saved in `property_set['dag_fixed_point']` as a boolean. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the DAGFixedPoint pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.DAGFixedPoint.mdx "--- title: DAGLongestPath description: API reference for qiskit.transpiler.passes.DAGLongestPath in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.DAGLongestPath --- # DAGLongestPath Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Return the longest path in a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") as a list of [`DAGOpNode`](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")s, [`DAGInNode`](qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")s, and [`DAGOutNode`](qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")s. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the DAGLongestPath pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.DAGLongestPath.mdx "--- title: Decompose description: API reference for qiskit.transpiler.passes.Decompose in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Decompose --- # Decompose Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Expand a gate in a circuit using its decomposition rules. Decompose initializer. **Parameters** **gates\_to\_decompose** – optional subset of gates to be decomposed, identified by gate label, name or type. Defaults to all gates. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the Decompose pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – input dag. **Returns** output dag where `gate` was expanded. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Decompose.mdx "--- title: DenseLayout description: API reference for qiskit.transpiler.passes.DenseLayout in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.DenseLayout --- # DenseLayout Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Choose a Layout by finding the most connected subset of qubits. This pass associates a physical qubit (int) to each virtual qubit of the circuit (Qubit). Even though a `'layout'` is not strictly a property of the DAG, in the transpiler architecture it is best passed around between passes by being set in `property_set`. DenseLayout initializer. **Parameters** * **coupling\_map** (*Coupling*) – directed graph representing a coupling map. * **backend\_prop** ([*BackendProperties*](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"")) – backend properties object * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – A target representing the target backend. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the DenseLayout pass on dag. Pick a convenient layout depending on the best matching qubit connectivity, and set the property layout. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to find layout for. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if dag wider than self.coupling\_map ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.DenseLayout.mdx "--- title: Depth description: API reference for qiskit.transpiler.passes.Depth in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Depth --- # Depth Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Calculate the depth of a DAG circuit. **Parameters** **recurse** – whether to allow recursion into control flow. If this is `False` (default), the pass will throw an error when control flow is present, to avoid returning a number with little meaning. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the Depth pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Depth.mdx "--- title: DynamicalDecoupling description: API reference for qiskit.transpiler.passes.DynamicalDecoupling in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.DynamicalDecoupling --- # DynamicalDecoupling Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Dynamical decoupling insertion pass. This pass works on a scheduled, physical circuit. It scans the circuit for idle periods of time (i.e. those containing delay instructions) and inserts a DD sequence of gates in those spots. These gates amount to the identity, so do not alter the logical action of the circuit, but have the effect of mitigating decoherence in those idle periods. As a special case, the pass allows a length-1 sequence (e.g. \[XGate()]). In this case the DD insertion happens only when the gate inverse can be absorbed into a neighboring gate in the circuit (so we would still be replacing Delay with something that is equivalent to the identity). This can be used, for instance, as a Hahn echo. This pass ensures that the inserted sequence preserves the circuit exactly (including global phase). ```python import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import XGate from qiskit.transpiler import PassManager, InstructionDurations from qiskit.transpiler.passes import ALAPSchedule, DynamicalDecoupling from qiskit.visualization import timeline_drawer # Because the legacy passes do not propagate the scheduling information correctly, it is # necessary to run a no-op ""re-schedule"" before the output circuits can be drawn. def draw(circuit): from qiskit import transpile scheduled = transpile( circuit, optimization_level=0, instruction_durations=InstructionDurations(), scheduling_method=""alap"", ) return timeline_drawer(scheduled) circ = QuantumCircuit(4) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.cx(2, 3) circ.measure_all() durations = InstructionDurations( [(""h"", 0, 50), (""cx"", [0, 1], 700), (""reset"", None, 10), (""cx"", [1, 2], 200), (""cx"", [2, 3], 300), (""x"", None, 50), (""measure"", None, 1000)] ) # balanced X-X sequence on all qubits dd_sequence = [XGate(), XGate()] pm = PassManager([ALAPSchedule(durations), DynamicalDecoupling(durations, dd_sequence)]) circ_dd = pm.run(circ) draw(circ_dd) # Uhrig sequence on qubit 0 n = 8 dd_sequence = [XGate()] * n def uhrig_pulse_location(k): return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2 spacing = [] for k in range(n): spacing.append(uhrig_pulse_location(k) - sum(spacing)) spacing.append(1 - sum(spacing)) pm = PassManager( [ ALAPSchedule(durations), DynamicalDecoupling(durations, dd_sequence, qubits=[0], spacing=spacing), ] ) circ_dd = pm.run(circ) draw(circ_dd) ``` ![../\_images/qiskit-transpiler-passes-DynamicalDecoupling-1\_00.png](/images/api/qiskit/1.0/qiskit-transpiler-passes-DynamicalDecoupling-1_00.png) ![../\_images/qiskit-transpiler-passes-DynamicalDecoupling-1\_01.png](/images/api/qiskit/1.0/qiskit-transpiler-passes-DynamicalDecoupling-1_01.png) Dynamical decoupling initializer. The class `qiskit.transpiler.passes.scheduling.dynamical_decoupling.DynamicalDecoupling` is pending deprecation as of qiskit 0.21.0. It will be marked deprecated in a future release, and then removed no earlier than 3 months after the release date. Instead, use [`PadDynamicalDecoupling`](qiskit.transpiler.passes.PadDynamicalDecoupling ""qiskit.transpiler.passes.PadDynamicalDecoupling""), which performs the same function but requires scheduling and alignment analysis passes to run prior to it. **Parameters** * **durations** ([*InstructionDurations*](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"")) – Durations of instructions to be used in scheduling. * **dd\_sequence** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"")*]*) – sequence of gates to apply in idle spots. * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – physical qubits on which to apply DD. If None, all qubits will undergo DD (when possible). * **spacing** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – a list of spacings between the DD gates. The available slack will be divided according to this. The list length must be one more than the length of dd\_sequence, and the elements must sum to 1. If None, a balanced spacing will be used \[d/2, d, d, …, d, d, d/2]. * **skip\_reset\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, does not insert DD on idle periods that immediately follow initialized/reset qubits (as qubits in the ground state are less susceptile to decoherence). * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend, if both `durations` and this are specified then this argument will take precedence and `durations` will be ignored. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the DynamicalDecoupling pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – a scheduled DAG. **Returns** **equivalent circuit with delays interrupted by DD,** where possible. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the circuit is not mapped on physical qubits. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.DynamicalDecoupling.mdx "--- title: EchoRZXWeylDecomposition description: API reference for qiskit.transpiler.passes.EchoRZXWeylDecomposition in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.EchoRZXWeylDecomposition --- # EchoRZXWeylDecomposition Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Rewrite two-qubit gates using the Weyl decomposition. This transpiler pass rewrites two-qubit gates in terms of echoed cross-resonance gates according to the Weyl decomposition. A two-qubit gate will be replaced with at most six non-echoed RZXGates. Each pair of RZXGates forms an echoed RZXGate. EchoRZXWeylDecomposition pass. **Parameters** * **instruction\_schedule\_map** ([*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"")) – the mapping from circuit [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") names and arguments to [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"")s. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend, if both `instruction_schedule_map` and `target` are specified then this argument will take precedence and `instruction_schedule_map` will be ignored. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the EchoRZXWeylDecomposition pass on dag. Rewrites two-qubit gates in an arbitrary circuit in terms of echoed cross-resonance gates by computing the Weyl decomposition of the corresponding unitary. Modifies the input dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to rewrite. **Returns** The modified dag. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If the circuit cannot be rewritten. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.EchoRZXWeylDecomposition.mdx "--- title: EnlargeWithAncilla description: API reference for qiskit.transpiler.passes.EnlargeWithAncilla in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.EnlargeWithAncilla --- # EnlargeWithAncilla Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Extend the dag with virtual qubits that are in layout but not in the circuit yet. Extend the DAG circuit with new virtual qubits (ancilla) that are specified in the layout, but not present in the circuit. Which qubits to add are previously allocated in the `layout` property, by a previous pass. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the EnlargeWithAncilla pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to extend. **Returns** An extended DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If there is no layout in the property set or not set at init time. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.EnlargeWithAncilla.mdx "--- title: FilterOpNodes description: API reference for qiskit.transpiler.passes.FilterOpNodes in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.FilterOpNodes --- # FilterOpNodes Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Remove all operations that match a filter function This transformation pass is used to remove any operations that matches a the provided filter function. **Parameters** **predicate** – A given callable that will be passed the [`DAGOpNode`](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"") for each node in the [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit""). If the callable returns `True` the [`DAGOpNode`](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"") is retained in the circuit and if it returns `False` it is removed from the circuit. **Example** Filter out operations that are labelled `""foo""` ```python from qiskit import QuantumCircuit from qiskit.transpiler.passes import FilterOpNodes circuit = QuantumCircuit(1) circuit.x(0, label='foo') circuit.barrier() circuit.h(0) circuit = FilterOpNodes( lambda node: getattr(node.op, ""label"") != ""foo"" )(circuit) circuit.draw('mpl') ``` ![../\_images/qiskit-transpiler-passes-FilterOpNodes-1.png](/images/api/qiskit/1.0/qiskit-transpiler-passes-FilterOpNodes-1.png) ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the RemoveBarriers pass on dag. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.FilterOpNodes.mdx "--- title: FixedPoint description: API reference for qiskit.transpiler.passes.FixedPoint in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.FixedPoint --- # FixedPoint Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Check if a property reached a fixed point. A dummy analysis pass that checks if a property reached a fixed point. The result is saved in `property_set['_fixed_point']` as a boolean. FixedPoint initializer. **Parameters** **property\_to\_check** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The property to check if a fixed point was reached. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the FixedPoint pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.FixedPoint.mdx "--- title: FullAncillaAllocation description: API reference for qiskit.transpiler.passes.FullAncillaAllocation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.FullAncillaAllocation --- # FullAncillaAllocation Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Allocate all idle nodes from the coupling map or target as ancilla on the layout. A pass for allocating all idle physical qubits (those that exist in coupling map or target but not the dag circuit) as ancilla. It will also choose new virtual qubits to correspond to those physical ancilla. This is an analysis pass, and only responsible for choosing physical ancilla locations and their corresponding virtual qubits. A separate transformation pass must add those virtual qubits to the circuit. FullAncillaAllocation initializer. **Parameters** **coupling\_map** (*Union\[*[*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")*,* [*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")*]*) – directed graph representing a coupling map. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the FullAncillaAllocation pass on dag. Extend the layout with new (physical qubit, virtual qubit) pairs. The dag signals which virtual qubits are already in the circuit. This pass will allocate new virtual qubits such that no collision occurs (i.e. Layout bijectivity is preserved) The coupling\_map and layout together determine which physical qubits are free. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – circuit to analyze **Returns** returns the same dag circuit, unmodified **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If there is not layout in the property set or not set at init time. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ### validate\_layout Checks if all the qregs in `layout_qregs` already exist in `dag_qregs`. Otherwise, raise. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.FullAncillaAllocation.mdx "--- title: GateDirection description: API reference for qiskit.transpiler.passes.GateDirection in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.GateDirection --- # GateDirection Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Modify asymmetric gates to match the hardware coupling direction. This pass makes use of the following identities: ```python ┌───┐┌───┐┌───┐ q_0: ──■── q_0: ┤ H ├┤ X ├┤ H ├ ┌─┴─┐ = ├───┤└─┬─┘├───┤ q_1: ┤ X ├ q_1: ┤ H ├──■──┤ H ├ └───┘ └───┘ └───┘ global phase: 3π/2 ┌──────┐ ┌───┐ ┌────┐┌─────┐┌──────┐┌───┐ q_0: ┤0 ├ q_0: ─┤ S ├─┤ √X ├┤ Sdg ├┤1 ├┤ H ├ │ ECR │ = ┌┴───┴┐├────┤└┬───┬┘│ Ecr │├───┤ q_1: ┤1 ├ q_1: ┤ Sdg ├┤ √X ├─┤ S ├─┤0 ├┤ H ├ └──────┘ └─────┘└────┘ └───┘ └──────┘└───┘ ┌──────┐ ┌───┐┌──────┐┌───┐ q_0: ┤0 ├ q_0: ┤ H ├┤1 ├┤ H ├ │ RZX │ = ├───┤│ RZX │├───┤ q_1: ┤1 ├ q_1: ┤ H ├┤0 ├┤ H ├ └──────┘ └───┘└──────┘└───┘ ``` This pass assumes that the positions of the qubits in the `DAGCircuit.qubits` attribute are the physical qubit indicies. For example if `dag.qubits[0]` is qubit 0 in the [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") or [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target""). GateDirection pass. **Parameters** * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")) – Directed graph represented a coupling map. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The backend target to use for this pass. If this is specified it will be used instead of the coupling map ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the GateDirection pass on dag. Flips the cx nodes to match the directed coupling map. Modifies the input dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to map. **Returns** The rearranged dag for the coupling map **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If the circuit cannot be mapped just by flipping the cx nodes. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.GateDirection.mdx "--- title: GatesInBasis description: API reference for qiskit.transpiler.passes.GatesInBasis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.GatesInBasis --- # GatesInBasis Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Check if all gates in a DAG are in a given set of gates Initialize the GatesInBasis pass. **Parameters** * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The list of strings representing the set of basis gates. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The target representing the backend. If specified this will be used instead of the `basis_gates` parameter ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the GatesInBasis pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.GatesInBasis.mdx "--- title: HighLevelSynthesis description: API reference for qiskit.transpiler.passes.HighLevelSynthesis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.HighLevelSynthesis --- # HighLevelSynthesis Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Synthesize higher-level objects and unroll custom definitions. The input to this pass is a DAG that may contain higher-level objects, including abstract mathematical objects (e.g., objects of type [`LinearFunction`](qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.LinearFunction"")), annotated operations (objects of type [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"")), and custom gates. In the most common use-case when either `basis_gates` or `target` is specified, all higher-level objects are synthesized, so the output is a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") without such objects. More precisely, every gate in the output DAG is either directly supported by the target, or is in `equivalence_library`. The abstract mathematical objects are synthesized using synthesis plugins, applying synthesis methods specified in the high-level-synthesis config (refer to the documentation for [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.HLSConfig"")). As an example, let us assume that `op_a` and `op_b` are names of two higher-level objects, that `op_a`-objects have two synthesis methods `default` which does require any additional parameters and `other` with two optional integer parameters `option_1` and `option_2`, that `op_b`-objects have a single synthesis method `default`, and `qc` is a quantum circuit containing `op_a` and `op_b` objects. The following code snippet: ```python hls_config = HLSConfig(op_b=[(""other"", {""option_1"": 7, ""option_2"": 4})]) pm = PassManager([HighLevelSynthesis(hls_config=hls_config)]) transpiled_qc = pm.run(qc) ``` shows how to run the alternative synthesis method `other` for `op_b`-objects, while using the `default` methods for all other high-level objects, including `op_a`-objects. The annotated operations (consisting of a base operation and a list of inverse, control and power modifiers) are synthesizing recursively, first synthesizing the base operation, and then applying synthesis methods for creating inverted, controlled, or powered versions of that). The custom gates are synthesized by recursively unrolling their definitions, until every gate is either supported by the target or is in the equivalence library. When neither `basis_gates` nor `target` is specified, the pass synthesizes only the top-level abstract mathematical objects and annotated operations, without descending into the gate `definitions`. This is consistent with the older behavior of the pass, allowing to synthesize some higher-level objects using plugins and leaving the other gates untouched. HighLevelSynthesis initializer. **Parameters** * **hls\_config** – Optional, the high-level-synthesis config that specifies synthesis methods and parameters for various high-level-objects in the circuit. If it is not specified, the default synthesis methods and parameters will be used. * **coupling\_map** – Optional, directed graph represented as a coupling map. * **target** – Optional, the backend target to use for this pass. If it is specified, it will be used instead of the coupling map. * **use\_qubit\_indices** – a flag indicating whether this synthesis pass is running before or after the layout is set, that is, whether the qubit indices of higher-level-objects correspond to qubit indices on the target backend. * **equivalence\_library** – The equivalence library used (instructions in this library will not be unrolled by this pass). * **basis\_gates** – Optional, target basis names to unroll to, e.g. \[‘u3’, ‘cx’]. Ignored if `target` is also specified. * **min\_qubits** – The minimum number of qubits for operations in the input dag to translate. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the HighLevelSynthesis pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – input dag. **Returns** Output dag with higher-level operations synthesized. **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – when the transpiler is unable to synthesize the given DAG * **(****for instance****, ****when the specified synthesis method is not available****)\*\*\*\*.** – **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.HighLevelSynthesis.mdx "--- title: HLSConfig description: API reference for qiskit.transpiler.passes.HLSConfig in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.HLSConfig --- # HLSConfig Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") The high-level-synthesis config allows to specify a list of “methods” used by [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.HighLevelSynthesis"") transformation pass to synthesize different types of higher-level objects. A higher-level object is an object of type [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation"") (e.g., [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") or [`LinearFunction`](qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.LinearFunction"")). Each object is referred to by its [`name`](qiskit.circuit.Operation#name ""qiskit.circuit.Operation.name"") field (e.g., `""clifford""` for [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") objects), and the applicable synthesis methods are tied to this name. In the config, each method is specified in one of several ways: 1. a tuple consisting of the name of a known synthesis plugin and a dictionary providing additional arguments for the algorithm. 2. a tuple consisting of an instance of [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") and additional arguments for the algorithm. 3. a single string of a known synthesis plugin 4. a single instance of [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin""). The following example illustrates different ways how a config file can be created: ```python from qiskit.transpiler.passes.synthesis.high_level_synthesis import HLSConfig from qiskit.transpiler.passes.synthesis.high_level_synthesis import ACGSynthesisPermutation # All the ways to specify hls_config are equivalent hls_config = HLSConfig(permutation=[(""acg"", {})]) hls_config = HLSConfig(permutation=[""acg""]) hls_config = HLSConfig(permutation=[(ACGSynthesisPermutation(), {})]) hls_config = HLSConfig(permutation=[ACGSynthesisPermutation()]) ``` The names of the synthesis plugins should be declared in `entry-points` table for `qiskit.synthesis` in `pyproject.toml`, in the form \.\. The standard higher-level-objects are recommended to have a synthesis method called “default”, which would be called automatically when synthesizing these objects, without having to explicitly set these methods in the config. To avoid synthesizing a given higher-level-object, one can give it an empty list of methods. For an explicit example of using such config files, refer to the documentation for [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.HighLevelSynthesis""). For an overview of the complete process of using high-level synthesis, see [High-level Synthesis Plugins](transpiler_synthesis_plugins#using-high-level-synthesis-plugins). Creates a high-level-synthesis config. **Parameters** * **use\_default\_on\_unspecified** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if True, every higher-level-object without an explicitly specified list of methods will be synthesized using the “default” algorithm if it exists. * **kwargs** – a dictionary mapping higher-level-objects to lists of synthesis methods. ## Methods ### set\_methods Sets the list of synthesis methods for a given higher-level-object. This overwrites the lists of methods if also set previously. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.HLSConfig.mdx "--- title: HoareOptimizer description: API reference for qiskit.transpiler.passes.HoareOptimizer in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.HoareOptimizer --- # HoareOptimizer Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") This is a transpiler pass using Hoare logic circuit optimization. The inner workings of this are detailed in: [https://arxiv.org/abs/1810.00375](https://arxiv.org/abs/1810.00375) **Parameters** **size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – size of gate cache, in number of gates **Raises** [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – if unable to import z3 solver ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the directed acyclic graph to run on. **Returns** Transformed DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.HoareOptimizer.mdx "--- title: InstructionDurationCheck description: API reference for qiskit.transpiler.passes.InstructionDurationCheck in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.InstructionDurationCheck --- # InstructionDurationCheck Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Duration validation pass for reschedule. This pass investigates the input quantum circuit and checks if the circuit requires rescheduling for execution. Note that this pass can be triggered without scheduling. This pass only checks the duration of delay instructions and user defined pulse gates, which report duration values without pre-scheduling. This pass assumes backend supported instructions, i.e. basis gates, have no violation of the hardware alignment constraints, which is true in general. Create new duration validation pass. The alignment values depend on the control electronics of your quantum processor. **Parameters** * **acquire\_alignment** – Integer number representing the minimum time resolution to trigger acquisition instruction in units of `dt`. * **pulse\_alignment** – Integer number representing the minimum time resolution to trigger gate instruction in units of `dt`. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run duration validation passes. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – DAG circuit to check instruction durations. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.InstructionDurationCheck.mdx "--- title: InverseCancellation description: API reference for qiskit.transpiler.passes.InverseCancellation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.InverseCancellation --- # InverseCancellation Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Cancel specific Gates which are inverses of each other when they occur back-to- back. Initialize InverseCancellation pass. **Parameters** **gates\_to\_cancel** – List describing the gates to cancel. Each element of the list is either a single gate or a pair of gates. If a single gate, then it should be self-inverse. If a pair of gates, then the gates in the pair should be inverses of each other. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – Input is not a self-inverse gate or a pair of inverse gates. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the InverseCancellation pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – the directed acyclic graph to run on. **Returns** Transformed DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.InverseCancellation.mdx "--- title: Layout2qDistance description: API reference for qiskit.transpiler.passes.Layout2qDistance in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Layout2qDistance --- # Layout2qDistance Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Evaluate how good the layout selection was. Saves in `property_set['layout_score']` (or the property name in property\_name) the sum of distances for each circuit CX. The lower the number, the better the selection. Therefore, 0 is a perfect layout selection. No CX direction is considered. Layout2qDistance initializer. **Parameters** * **coupling\_map** (*Union\[*[*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")*,* [*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")*]*) – Directed graph represented a coupling map. * **property\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The property name to save the score. Default: layout\_score ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the Layout2qDistance pass on dag. :param dag: DAG to evaluate. :type dag: DAGCircuit ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Layout2qDistance.mdx "--- title: LinearFunctionsToPermutations description: API reference for qiskit.transpiler.passes.LinearFunctionsToPermutations in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.LinearFunctionsToPermutations --- # LinearFunctionsToPermutations Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Promotes linear functions to permutations when possible. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the LinearFunctionsToPermutations pass on dag. :param dag: input dag. **Returns** Output dag with LinearFunctions synthesized. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.LinearFunctionsToPermutations.mdx "--- title: LookaheadSwap description: API reference for qiskit.transpiler.passes.LookaheadSwap in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.LookaheadSwap --- # LookaheadSwap Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Map input circuit onto a backend topology via insertion of SWAPs. Implementation of Sven Jandura’s swap mapper submission for the 2018 Qiskit Developer Challenge, adapted to integrate into the transpiler architecture. The role of the swapper pass is to modify the starting circuit to be compatible with the target device’s topology (the set of two-qubit gates available on the hardware.) To do this, the pass will insert SWAP gates to relocate the virtual qubits for each upcoming gate onto a set of coupled physical qubits. However, as SWAP gates are particularly lossy, the goal is to accomplish this remapping while introducing the fewest possible additional SWAPs. This algorithm searches through the available combinations of SWAP gates by means of a narrowed best first/beam search, described as follows: * Start with a layout of virtual qubits onto physical qubits. * Find any gates in the input circuit which can be performed with the current layout and mark them as mapped. * For all possible SWAP gates, calculate the layout that would result from their application and rank them according to the distance of the resulting layout over upcoming gates (see \_calc\_layout\_distance.) * For the four (search\_width) highest-ranking SWAPs, repeat the above process on the layout that would be generated if they were applied. * Repeat this process down to a depth of four (search\_depth) SWAPs away from the initial layout, for a total of 256 (search\_width^search\_depth) prospective layouts. * Choose the layout which maximizes the number of two-qubit which could be performed. Add its mapped gates, including the SWAPs generated, to the output circuit. * Repeat the above until all gates from the initial circuit are mapped. For more details on the algorithm, see Sven’s blog post: [https://medium.com/qiskit/improving-a-quantum-compiler-48410d7a7084](https://medium.com/qiskit/improving-a-quantum-compiler-48410d7a7084) LookaheadSwap initializer. **Parameters** * **coupling\_map** (*Union\[*[*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")*,* [*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")*]*) – CouplingMap of the target backend. * **search\_depth** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – lookahead tree depth when ranking best SWAP options. * **search\_width** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – lookahead tree width when ranking best SWAP options. * **fake\_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if true, it will only pretend to do routing, i.e., no swap is effectively added. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the LookaheadSwap pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the directed acyclic graph to be mapped **Returns** **A dag mapped to be compatible with the coupling\_map in** the property\_set. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the coupling map or the layout are not * **compatible with the DAG**\*\*, or \*\***if the coupling\_map=None** – ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.LookaheadSwap.mdx "--- title: MergeAdjacentBarriers description: API reference for qiskit.transpiler.passes.MergeAdjacentBarriers in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.MergeAdjacentBarriers --- # MergeAdjacentBarriers Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Return a circuit with any adjacent barriers merged together. Only barriers which can be merged without affecting the barrier structure of the DAG will be merged. Not all redundant barriers will necessarily be merged, only adjacent barriers are merged. For example, the circuit: ```python qr = QuantumRegister(3, 'q') circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.barrier(qr[1]) circuit.barrier(qr) ``` Will be transformed into a circuit corresponding to: ```python circuit.barrier(qr[0]) circuit.barrier(qr) ``` i.e, ```python ░ ░ ░ ░ q_0: ─░──░─ q_0: ─░──░─ ░ ░ ░ ░ q_1: ─░──░─ => q_1: ────░─ ░ ░ ░ q_2: ────░─ q_2: ────░─ ░ ``` after one iteration of the pass. These two barriers were not merged by the first pass as they are not adjacent in the initial circuit. The pass then can be reapplied to merge the newly adjacent barriers. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the MergeAdjacentBarriers pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.MergeAdjacentBarriers.mdx "--- title: MinimumPoint description: API reference for qiskit.transpiler.passes.MinimumPoint in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.MinimumPoint --- # MinimumPoint Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Check if the DAG has reached a relative semi-stable point over previous runs This pass is similar to the [`FixedPoint`](qiskit.transpiler.passes.FixedPoint ""qiskit.transpiler.passes.FixedPoint"") transpiler pass and is intended primarily to be used to set a loop break condition in the property set. However, unlike the [`FixedPoint`](qiskit.transpiler.passes.FixedPoint ""qiskit.transpiler.passes.FixedPoint"") class which only sets the condition if 2 consecutive runs have the same value property set value this pass is designed to find a local minimum and use that instead. This pass is designed for an optimization loop where a fixed point may never get reached (for example if synthesis is used and there are multiple equivalent outputs for some cases). This pass will track the state of fields in the property set over its past executions and set a boolean field when either a fixed point is reached over the backtracking depth or selecting the minimum value found if the backtracking depth is reached. To do this it stores a deep copy of the current minimum DAG in the property set and when `backtrack_depth` number of executions is reached since the last minimum the output dag is set to that copy of the earlier minimum. Fields used by this pass in the property set are (all relative to the `prefix` argument): * `{prefix}_minimum_point_state` - Used to track the state of the minimum point search * **`{prefix}_minimum_point` - This value gets set to `True` when either a fixed point** is reached over the `backtrack_depth` executions, or `backtrack_depth` was exceeded and an earlier minimum is restored. Initialize an instance of this pass **Parameters** * **property\_set\_list** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of property set keys that will be used to evaluate the local minimum. The values of these property set keys will be used as a tuple for comparison * **prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The prefix to use for the property set key that is used for tracking previous evaluations * **backtrack\_depth** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of entries to store. If this number is reached and the next iteration doesn’t have a decrease in the number of values the minimum of the previous n will be set as the output dag and `minimum_point` will be set to `True` in the property set ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the MinimumPoint pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.MinimumPoint.mdx "--- title: NormalizeRXAngle description: API reference for qiskit.transpiler.passes.NormalizeRXAngle in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.NormalizeRXAngle --- # NormalizeRXAngle Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Normalize theta parameter of RXGate instruction. The parameter normalization is performed with following steps. 1\) Wrap RX Gate theta into \[0, pi]. When theta is negative value, the gate is decomposed into the following sequence. ```python ┌───────┐┌─────────┐┌────────┐ q: ┤ Rz(π) ├┤ Rx(|θ|) ├┤ Rz(-π) ├ └───────┘└─────────┘└────────┘ ``` 2. If the operation is supported by target, convert RX(pi/2) to SX, and RX(pi) to X. 3. Quantize theta value according to the user-specified resolution. This will help reduce the size of calibration data sent over the wire, and allow us to exploit the more accurate, hardware-calibrated pulses. Note that pulse calibration might be attached per each rotation angle. NormalizeRXAngle initializer. **Parameters** * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend. If the target contains SX and X calibrations, this pass will replace the corresponding RX gates with SX and X gates. * **resolution\_in\_radian** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Resolution for RX rotation angle quantization. If set to zero, this pass won’t modify the rotation angles in the given DAG. (=Provides arbitrary-angle RX) ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### quantize\_angles Quantize the RX rotation angles by assigning the same value for the angles that differ within a resolution provided by the user. **Parameters** * **qubit** ([*qiskit.circuit.Qubit*](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"")) – This will be the dict key to access the list of quantized rotation angles. * **original\_angle** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Original rotation angle, before quantization. **Returns** Quantized angle. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### run Run the NormalizeRXAngle pass on `dag`. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – The DAG to be optimized. **Returns** A DAG with RX gate calibration. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.NormalizeRXAngle.mdx "--- title: NumTensorFactors description: API reference for qiskit.transpiler.passes.NumTensorFactors in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.NumTensorFactors --- # NumTensorFactors Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Calculate the number of tensor factors of a DAG circuit. The result is saved in `property_set['num_tensor_factors']` as an integer. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the NumTensorFactors pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.NumTensorFactors.mdx "--- title: Optimize1qGates description: API reference for qiskit.transpiler.passes.Optimize1qGates in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Optimize1qGates --- # Optimize1qGates Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Optimize chains of single-qubit u1, u2, u3 gates by combining them into a single gate. Optimize1qGates initializer. **Parameters** * **basis** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – Basis gates to consider, e.g. \[‘u3’, ‘cx’]. For the effects of this pass, the basis is the set intersection between the basis parameter and the set \{‘u1’,’u2’,’u3’, ‘u’, ‘p’}. * **eps** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – EPS to check against * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend, if both `basis` and `target` are specified then this argument will take precedence and `basis` will be ignored. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### compose\_u3 Return a triple theta, phi, lambda for the product. **u3(theta, phi, lambda)** \= u3(theta1, phi1, lambda1).u3(theta2, phi2, lambda2) = Rz(phi1).Ry(theta1).Rz(lambda1+phi2).Ry(theta2).Rz(lambda2) = Rz(phi1).Rz(phi’).Ry(theta’).Rz(lambda’).Rz(lambda2) = u3(theta’, phi1 + phi’, lambda2 + lambda’) Return theta, phi, lambda. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the Optimize1qGates pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the DAG to be optimized. **Returns** the optimized DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if `YZY` and `ZYZ` angles do not give same rotation matrix. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ### yzy\_to\_zyz Express a Y.Z.Y single qubit gate as a Z.Y.Z gate. Solve the equation $$ $$ Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda) for theta, phi, and lambda. Return a solution theta, phi, and lambda. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Optimize1qGates.mdx "--- title: Optimize1qGatesDecomposition description: API reference for qiskit.transpiler.passes.Optimize1qGatesDecomposition in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Optimize1qGatesDecomposition --- # Optimize1qGatesDecomposition Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Optimize chains of single-qubit gates by combining them into a single gate. **The decision to replace the original chain with a new re-synthesis depends on:** * whether the original chain was out of basis: replace * whether the original chain was in basis but re-synthesis is lower error: replace * whether the original chain contains a pulse gate: do not replace * whether the original chain amounts to identity: replace with null Error is computed as a multiplication of the errors of individual gates on that qubit. Optimize1qGatesDecomposition initializer. **Parameters** * **basis** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – Basis gates to consider, e.g. \[‘u3’, ‘cx’]. For the effects of this pass, the basis is the set intersection between the basis parameter and the Euler basis. Ignored if `target` is also specified. * **target** (*Optional\[*[*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")*]*) – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object corresponding to the compilation target. When specified, any argument specified for `basis_gates` is ignored. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the Optimize1qGatesDecomposition pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the DAG to be optimized. **Returns** the optimized DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Optimize1qGatesDecomposition.mdx "--- title: Optimize1qGatesSimpleCommutation description: API reference for qiskit.transpiler.passes.Optimize1qGatesSimpleCommutation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Optimize1qGatesSimpleCommutation --- # Optimize1qGatesSimpleCommutation Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Optimizes 1Q gate strings interrupted by 2Q gates by commuting the components and resynthesizing the results. The commutation rules are stored in `commutation_table`. **NOTE: In addition to those mentioned in `commutation_table`, this pass has some limitations:** * Does not handle multiple commutations in a row without intermediate progress. * Can only commute into positions where there are pre-existing runs. * Does not exhaustively test all the different ways commuting gates can be assigned to either side of a barrier to try to find low-depth configurations. (This is particularly evident if all the gates in a run commute with both the predecessor and the successor barriers.) **Parameters** * **basis** (*List\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – See also Optimize1qGatesDecomposition. * **run\_to\_completion** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, this pass retries until it is unable to do any more work. If False, it finds and performs one optimization, and for full optimization the user is obligated to re-call the pass until the output stabilizes. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend, if both `basis` and this are specified then this argument will take precedence and `basis` will be ignored. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the DAG to be optimized. **Returns** the optimized DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Optimize1qGatesSimpleCommutation.mdx "--- title: OptimizeAnnotated description: API reference for qiskit.transpiler.passes.OptimizeAnnotated in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.OptimizeAnnotated --- # OptimizeAnnotated Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Optimization pass on circuits with annotated operations. Implemented optimizations: * For each annotated operation, converting the list of its modifiers to a canonical form. For example, consecutively applying `inverse()`, `control(2)` and `inverse()` is equivalent to applying `control(2)`. * Removing annotations when possible. For example, `AnnotatedOperation(SwapGate(), [InverseModifier(), InverseModifier()])` is equivalent to `SwapGate()`. * Recursively combining annotations. For example, if `g1 = AnnotatedOperation(SwapGate(), InverseModifier())` and `g2 = AnnotatedOperation(g1, ControlModifier(2))`, then `g2` can be replaced with `AnnotatedOperation(SwapGate(), [InverseModifier(), ControlModifier(2)])`. OptimizeAnnotated initializer. **Parameters** * **target** – Optional, the backend target to use for this pass. * **equivalence\_library** – The equivalence library used (instructions in this library will not be optimized by this pass). * **basis\_gates** – Optional, target basis names to unroll to, e.g. \[‘u3’, ‘cx’] (instructions in this list will not be optimized by this pass). Ignored if `target` is also specified. * **recurse** – By default, when either `target` or `basis_gates` is specified, the pass recursively descends into gate definitions (and the recursion is not applied when neither is specified since such objects do not need to be synthesized). Setting this value to `False` precludes the recursion in every case. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the OptimizeAnnotated pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – input dag. **Returns** Output dag with higher-level operations optimized. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – when something goes wrong. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.OptimizeAnnotated.mdx "--- title: OptimizeCliffords description: API reference for qiskit.transpiler.passes.OptimizeCliffords in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.OptimizeCliffords --- # OptimizeCliffords Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Combine consecutive Cliffords over the same qubits. This serves as an example of extra capabilities enabled by storing Cliffords natively on the circuit. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the OptimizeCliffords pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the DAG to be optimized. **Returns** the optimized DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.OptimizeCliffords.mdx "--- title: PadDelay description: API reference for qiskit.transpiler.passes.PadDelay in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.PadDelay --- # PadDelay Bases: `BasePadding` Padding idle time with Delay instructions. Consecutive delays will be merged in the output of this pass. ```python durations = InstructionDurations([(""x"", None, 160), (""cx"", None, 800)]) qc = QuantumCircuit(2) qc.delay(100, 0) qc.x(1) qc.cx(0, 1) ``` The ASAP-scheduled circuit output may become ```python ┌────────────────┐ q_0: ┤ Delay(160[dt]) ├──■── └─────┬───┬──────┘┌─┴─┐ q_1: ──────┤ X ├───────┤ X ├ └───┘ └───┘ ``` Note that the additional idle time of 60dt on the `q_0` wire coming from the duration difference between `Delay` of 100dt (`q_0`) and `XGate` of 160 dt (`q_1`) is absorbed in the delay instruction on the `q_0` wire, i.e. in total 160 dt. See `BasePadding` pass for details. Create new padding delay pass. **Parameters** * **fill\_very\_end** – Set `True` to fill the end of circuit with delay. * **target** – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend. If it is supplied and does not support delay instruction on a qubit, padding passes do not pad any idle time of the qubit. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the padding pass on `dag`. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – DAG to be checked. **Returns** DAG with idle time filled with instructions. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – When a particular node is not scheduled, likely some transform pass is inserted before this node is called. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.PadDelay.mdx "--- title: PadDynamicalDecoupling description: API reference for qiskit.transpiler.passes.PadDynamicalDecoupling in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.PadDynamicalDecoupling --- # PadDynamicalDecoupling Bases: `BasePadding` Dynamical decoupling insertion pass. This pass works on a scheduled, physical circuit. It scans the circuit for idle periods of time (i.e. those containing delay instructions) and inserts a DD sequence of gates in those spots. These gates amount to the identity, so do not alter the logical action of the circuit, but have the effect of mitigating decoherence in those idle periods. As a special case, the pass allows a length-1 sequence (e.g. `[XGate()]`). In this case the DD insertion happens only when the gate inverse can be absorbed into a neighboring gate in the circuit (so we would still be replacing Delay with something that is equivalent to the identity). This can be used, for instance, as a Hahn echo. This pass ensures that the inserted sequence preserves the circuit exactly (including global phase). ```python import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import XGate from qiskit.transpiler import PassManager, InstructionDurations from qiskit.transpiler.passes import ALAPScheduleAnalysis, PadDynamicalDecoupling from qiskit.visualization import timeline_drawer circ = QuantumCircuit(4) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.cx(2, 3) circ.measure_all() durations = InstructionDurations( [(""h"", 0, 50), (""cx"", [0, 1], 700), (""reset"", None, 10), (""cx"", [1, 2], 200), (""cx"", [2, 3], 300), (""x"", None, 50), (""measure"", None, 1000)] ) # balanced X-X sequence on all qubits dd_sequence = [XGate(), XGate()] pm = PassManager([ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence)]) circ_dd = pm.run(circ) timeline_drawer(circ_dd) # Uhrig sequence on qubit 0 n = 8 dd_sequence = [XGate()] * n def uhrig_pulse_location(k): return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2 spacing = [] for k in range(n): spacing.append(uhrig_pulse_location(k) - sum(spacing)) spacing.append(1 - sum(spacing)) pm = PassManager( [ ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence, qubits=[0], spacing=spacing), ] ) circ_dd = pm.run(circ) timeline_drawer(circ_dd) ``` ![../\_images/qiskit-transpiler-passes-PadDynamicalDecoupling-1\_00.png](/images/api/qiskit/1.0/qiskit-transpiler-passes-PadDynamicalDecoupling-1_00.png) ![../\_images/qiskit-transpiler-passes-PadDynamicalDecoupling-1\_01.png](/images/api/qiskit/1.0/qiskit-transpiler-passes-PadDynamicalDecoupling-1_01.png) You may need to call alignment pass before running dynamical decoupling to guarantee your circuit satisfies acquisition alignment constraints. Dynamical decoupling initializer. **Parameters** * **durations** – Durations of instructions to be used in scheduling. * **dd\_sequence** – Sequence of gates to apply in idle spots. * **qubits** – Physical qubits on which to apply DD. If None, all qubits will undergo DD (when possible). * **spacing** – A list of spacings between the DD gates. The available slack will be divided according to this. The list length must be one more than the length of dd\_sequence, and the elements must sum to 1. If None, a balanced spacing will be used \[d/2, d, d, …, d, d, d/2]. * **skip\_reset\_qubits** – If True, does not insert DD on idle periods that immediately follow initialized/reset qubits (as qubits in the ground state are less susceptile to decoherence). * **pulse\_alignment** – The hardware constraints for gate timing allocation. This is usually provided from `backend.configuration().timing_constraints`. If provided, the delay length, i.e. `spacing`, is implicitly adjusted to satisfy this constraint. * **extra\_slack\_distribution** – The option to control the behavior of DD sequence generation. The duration of the DD sequence should be identical to an idle time in the scheduled quantum circuit, however, the delay in between gates comprising the sequence should be integer number in units of dt, and it might be further truncated when `pulse_alignment` is specified. This sometimes results in the duration of the created sequence being shorter than the idle time that you want to fill with the sequence, i.e. extra slack. This option takes following values. > * ”middle”: Put the extra slack to the interval at the middle of the sequence. > * ”edges”: Divide the extra slack as evenly as possible into intervals at beginning and end of the sequence. * **target** – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend. Target takes precedence over other arguments when they can be inferred from target. Therefore specifying target as well as other arguments like `durations` or `pulse_alignment` will cause those other arguments to be ignored. **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – When invalid DD sequence is specified. * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – When pulse gate with the duration which is non-multiple of the alignment constraint value is found. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – If `dd_sequence` is not specified ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the padding pass on `dag`. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – DAG to be checked. **Returns** DAG with idle time filled with instructions. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – When a particular node is not scheduled, likely some transform pass is inserted before this node is called. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.PadDynamicalDecoupling.mdx "--- title: PulseGates description: API reference for qiskit.transpiler.passes.PulseGates in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.PulseGates --- # PulseGates Bases: `CalibrationBuilder` Pulse gate adding pass. This pass adds gate calibrations from the supplied `InstructionScheduleMap` to a quantum circuit. This pass checks each DAG circuit node and acquires a corresponding schedule from the instruction schedule map object that may be provided by the target backend. Because this map is a mutable object, the end-user can provide a configured backend to execute the circuit with customized gate implementations. This mapping object returns a schedule with “publisher” metadata which is an integer Enum value representing who created the gate schedule. If the gate schedule is provided by end-users, this pass attaches the schedule to the DAG circuit as a calibration. This pass allows users to easily override quantum circuit with custom gate definitions without directly dealing with those schedules. **References** * \[1] OpenQASM 3: A broader and deeper quantum assembly language [https://arxiv.org/abs/2104.14722](https://arxiv.org/abs/2104.14722) Create new pass. **Parameters** * **inst\_map** – Instruction schedule map that user may override. * **target** – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend, if both `inst_map` and `target` are specified then it updates instructions in the `target` with `inst_map`. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### get\_calibration Gets the calibrated schedule for the given instruction and qubits. **Parameters** * **node\_op** ([*Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – Target instruction object. * **qubits** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")) – Integer qubit indices to check. **Returns** Return Schedule of target gate instruction. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – When node is parameterized and calibration is raw schedule object. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") | [*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"") ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the calibration adder pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – DAG to schedule. **Returns** A DAG with calibrations added to it. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### supported Determine if a given node supports the calibration. **Parameters** * **node\_op** ([*Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – Target instruction object. * **qubits** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")) – Integer qubit indices to check. **Returns** Return `True` is calibration can be provided. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.PulseGates.mdx "--- title: RemoveBarriers description: API reference for qiskit.transpiler.passes.RemoveBarriers in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.RemoveBarriers --- # RemoveBarriers Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Return a circuit with any barrier removed. This transformation is not semantics preserving. **Example** ```python from qiskit import QuantumCircuit from qiskit.transpiler.passes import RemoveBarriers circuit = QuantumCircuit(1) circuit.x(0) circuit.barrier() circuit.h(0) circuit = RemoveBarriers()(circuit) circuit.draw('mpl') ``` ![../\_images/qiskit-transpiler-passes-RemoveBarriers-1.png](/images/api/qiskit/1.0/qiskit-transpiler-passes-RemoveBarriers-1.png) ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the RemoveBarriers pass on dag. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.RemoveBarriers.mdx "--- title: RemoveDiagonalGatesBeforeMeasure description: API reference for qiskit.transpiler.passes.RemoveDiagonalGatesBeforeMeasure in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.RemoveDiagonalGatesBeforeMeasure --- # RemoveDiagonalGatesBeforeMeasure Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Remove diagonal gates (including diagonal 2Q gates) before a measurement. Transpiler pass to remove diagonal gates (like RZ, T, Z, etc) before a measurement. Including diagonal 2Q gates. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the RemoveDiagonalGatesBeforeMeasure pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the DAG to be optimized. **Returns** the optimized DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.RemoveDiagonalGatesBeforeMeasure.mdx "--- title: RemoveFinalMeasurements description: API reference for qiskit.transpiler.passes.RemoveFinalMeasurements in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.RemoveFinalMeasurements --- # RemoveFinalMeasurements Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Remove final measurements and barriers at the end of a circuit. This pass removes final barriers and final measurements, as well as all unused classical registers and bits they are connected to. Measurements and barriers are considered final if they are followed by no other operations (aside from other measurements or barriers.) Classical registers are removed iff they reference at least one bit that has become unused by the circuit as a result of the operation, and all of their other bits are also unused. Separately, classical bits are removed iff they have become unused by the circuit as a result of the operation, or they appear in a removed classical register, but do not appear in a classical register that will remain. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the RemoveFinalMeasurements pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the DAG to be optimized. **Returns** the optimized DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.RemoveFinalMeasurements.mdx "--- title: RemoveResetInZeroState description: API reference for qiskit.transpiler.passes.RemoveResetInZeroState in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.RemoveResetInZeroState --- # RemoveResetInZeroState Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Remove reset gate when the qubit is in zero state. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the RemoveResetInZeroState pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the DAG to be optimized. **Returns** the optimized DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.RemoveResetInZeroState.mdx "--- title: ResetAfterMeasureSimplification description: API reference for qiskit.transpiler.passes.ResetAfterMeasureSimplification in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.ResetAfterMeasureSimplification --- # ResetAfterMeasureSimplification Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") This pass replaces reset after measure with a conditional X gate. This optimization is suitable for use on IBM Quantum systems where the reset operation is performed by a measurement followed by a conditional x-gate. It might not be desirable on other backends if reset is implemented differently. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the pass on a dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.ResetAfterMeasureSimplification.mdx "--- title: RXCalibrationBuilder description: API reference for qiskit.transpiler.passes.RXCalibrationBuilder in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.RXCalibrationBuilder --- # RXCalibrationBuilder Bases: `CalibrationBuilder` Add single-pulse RX calibrations that are bootstrapped from the SX calibration. Requirement: NormalizeRXAngles pass (one of the optimization passes). It is recommended to place this pass in the post-optimization stage of a passmanager. A simple demo: ```python from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler import PassManager, PassManagerConfig from qiskit.transpiler.preset_passmanagers import level_1_pass_manager from qiskit.circuit import Parameter from qiskit.circuit.library import QuantumVolume from qiskit.circuit.library.standard_gates import RXGate from calibration.rx_builder import RXCalibrationBuilder qv = QuantumVolume(4, 4, seed=1004) # Transpiling with single pulse RX gates enabled backend_with_single_pulse_rx = GenericBackendV2(5) rx_inst_props = {} for i in range(backend_with_single_pulse_rx.num_qubits): rx_inst_props[(i,)] = None backend_with_single_pulse_rx.target.add_instruction(RXGate(Parameter(""theta"")), rx_inst_props) config_with_rx = PassManagerConfig.from_backend(backend=backend_with_single_pulse_rx) pm_with_rx = level_1_pass_manager(pass_manager_config=config_with_rx) rx_builder = RXCalibrationBuilder(target=backend_with_single_pulse_rx.target) pm_with_rx.post_optimization = PassManager([rx_builder]) transpiled_circ_with_single_pulse_rx = pm_with_rx.run(qv) transpiled_circ_with_single_pulse_rx.count_ops() # Conventional transpilation: each RX gate is decomposed into a sequence with two SX gates original_backend = GenericBackendV2(5) original_config = PassManagerConfig.from_backend(backend=original_backend) original_pm = level_1_pass_manager(pass_manager_config=original_config) original_transpiled_circ = original_pm.run(qv) original_transpiled_circ.count_ops() ``` **References** * \[1]: Gokhale et al. (2020), Optimized Quantum Compilation for Near-Term Algorithms with OpenPulse. arXiv:2004.11205 \<[https://arxiv.org/abs/2004.11205](https://arxiv.org/abs/2004.11205)> Bootstrap single-pulse RX gate calibrations from the (hardware-calibrated) SX gate calibration. **Parameters** * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – Should contain a SX calibration that will be * **calibrations.** (*used for bootstrapping RX*) – ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### get\_calibration Generate RX calibration for the rotation angle specified in node\_op. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") | [*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"") ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the calibration adder pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – DAG to schedule. **Returns** A DAG with calibrations added to it. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### supported Check if the calibration for SX gate exists and it’s a single DRAG pulse. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.RXCalibrationBuilder.mdx "--- title: RZXCalibrationBuilder description: API reference for qiskit.transpiler.passes.RZXCalibrationBuilder in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.RZXCalibrationBuilder --- # RZXCalibrationBuilder Bases: `CalibrationBuilder` Creates calibrations for RZXGate(theta) by stretching and compressing Gaussian square pulses in the CX gate. This is done by retrieving (for a given pair of qubits) the CX schedule in the instruction schedule map of the backend defaults. The CX schedule must be an echoed cross-resonance gate optionally with rotary tones. The cross-resonance drive tones and rotary pulses must be Gaussian square pulses. The width of the Gaussian square pulse is adjusted so as to match the desired rotation angle. If the rotation angle is small such that the width disappears then the amplitude of the zero width Gaussian square pulse (i.e. a Gaussian) is reduced to reach the target rotation angle. Additional details can be found in [https://arxiv.org/abs/2012.11660](https://arxiv.org/abs/2012.11660). Initializes a RZXGate calibration builder. **Parameters** * **instruction\_schedule\_map** – The `InstructionScheduleMap` object representing the default pulse calibrations for the target backend * **verbose** – Set True to raise a user warning when RZX schedule cannot be built. * **target** – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend, if both `instruction_schedule_map` and this are specified then this argument will take precedence and `instruction_schedule_map` will be ignored. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – Instruction schedule map is not provided. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### get\_calibration Builds the calibration schedule for the RZXGate(theta) with echos. **Parameters** * **node\_op** (*CircuitInst*) – Instruction of the RZXGate(theta). I.e. params\[0] is theta. * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of qubits for which to get the schedules. The first qubit is the control and the second is the target. **Returns** The calibration schedule for the RZXGate(theta). **Return type** schedule **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if rotation angle is not assigned. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If the control and target qubits cannot be identified. * **CalibrationNotAvailable** – RZX schedule cannot be built for input node. ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### rescale\_cr\_inst A builder macro to play stretched pulse. **Parameters** * **instruction** ([*Play*](qiskit.pulse.instructions.Play ""qiskit.pulse.instructions.play.Play"")) – The instruction from which to create a new shortened or lengthened pulse. * **theta** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – desired angle, pi/2 is assumed to be the angle that the pulse in the given play instruction implements. * **sample\_mult** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – All pulses must be a multiple of sample\_mult. **Returns** Duration of stretched pulse. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if rotation angle is not assigned. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### run Run the calibration adder pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – DAG to schedule. **Returns** A DAG with calibrations added to it. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### supported Determine if a given node supports the calibration. **Parameters** * **node\_op** ([*Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – Target instruction object. * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – Integer qubit indices to check. **Returns** Return `True` is calibration can be provided. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.RZXCalibrationBuilder.mdx "--- title: RZXCalibrationBuilderNoEcho description: API reference for qiskit.transpiler.passes.RZXCalibrationBuilderNoEcho in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.RZXCalibrationBuilderNoEcho --- # RZXCalibrationBuilderNoEcho Bases: [`RZXCalibrationBuilder`](qiskit.transpiler.passes.RZXCalibrationBuilder ""qiskit.transpiler.passes.calibration.rzx_builder.RZXCalibrationBuilder"") Creates calibrations for RZXGate(theta) by stretching and compressing Gaussian square pulses in the CX gate. The `RZXCalibrationBuilderNoEcho` is a variation of the [`RZXCalibrationBuilder`](qiskit.transpiler.passes.RZXCalibrationBuilder ""qiskit.transpiler.passes.RZXCalibrationBuilder"") pass that creates calibrations for the cross-resonance pulses without inserting the echo pulses in the pulse schedule. This enables exposing the echo in the cross-resonance sequence as gates so that the transpiler can simplify them. The `RZXCalibrationBuilderNoEcho` only supports the hardware-native direction of the CX gate. Initializes a RZXGate calibration builder. **Parameters** * **instruction\_schedule\_map** – The `InstructionScheduleMap` object representing the default pulse calibrations for the target backend * **verbose** – Set True to raise a user warning when RZX schedule cannot be built. * **target** – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend, if both `instruction_schedule_map` and this are specified then this argument will take precedence and `instruction_schedule_map` will be ignored. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – Instruction schedule map is not provided. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### get\_calibration Builds the calibration schedule for the RZXGate(theta) without echos. **Parameters** * **node\_op** (*CircuitInst*) – Instruction of the RZXGate(theta). I.e. params\[0] is theta. * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of qubits for which to get the schedules. The first qubit is the control and the second is the target. **Returns** The calibration schedule for the RZXGate(theta). **Return type** schedule **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if rotation angle is not assigned. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If the control and target qubits cannot be identified, or the backend does not natively support the specified direction of the cx. * **CalibrationNotAvailable** – RZX schedule cannot be built for input node. ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### rescale\_cr\_inst A builder macro to play stretched pulse. **Parameters** * **instruction** ([*Play*](qiskit.pulse.instructions.Play ""qiskit.pulse.instructions.play.Play"")) – The instruction from which to create a new shortened or lengthened pulse. * **theta** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – desired angle, pi/2 is assumed to be the angle that the pulse in the given play instruction implements. * **sample\_mult** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – All pulses must be a multiple of sample\_mult. **Returns** Duration of stretched pulse. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if rotation angle is not assigned. **Return type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### run Run the calibration adder pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – DAG to schedule. **Returns** A DAG with calibrations added to it. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### supported Determine if a given node supports the calibration. **Parameters** * **node\_op** ([*Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.instruction.Instruction"")) – Target instruction object. * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – Integer qubit indices to check. **Returns** Return `True` is calibration can be provided. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.RZXCalibrationBuilderNoEcho.mdx "--- title: SabreLayout description: API reference for qiskit.transpiler.passes.SabreLayout in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.SabreLayout --- # SabreLayout Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Choose a Layout via iterative bidirectional routing of the input circuit. Starting with a random initial Layout, the algorithm does a full routing of the circuit (via the routing\_pass method) to end up with a final\_layout. This final\_layout is then used as the initial\_layout for routing the reverse circuit. The algorithm iterates a number of times until it finds an initial\_layout that reduces full routing cost. This method exploits the reversibility of quantum circuits, and tries to include global circuit information in the choice of initial\_layout. By default, this pass will run both layout and routing and will transform the circuit so that the layout is applied to the input dag (meaning that the output circuit will have ancilla qubits allocated for unused qubits on the coupling map and the qubits will be reordered to match the mapped physical qubits) and then routing will be applied (inserting `AnalysisPass` objects and just find an initial layout and set that on the property set. This is done because by default the pass will run parallel seed trials with different random seeds for selecting the random initial layout and then selecting the routed output which results in the least number of swap gates needed. You can use the `routing_pass` argument to have this pass operate as a typical layout pass. When specified this will use the specified routing pass to select an initial layout only and will not run multiple seed trials. In addition to starting with a random initial Layout the pass can also take in an additional list of starting layouts which will be used for additional trials. If the `sabre_starting_layouts` is present in the property set when this pass is run, that will be used for additional trials. There will still be `layout_trials` of full random starting layouts run and the contents of `sabre_starting_layouts` will be run in addition to those. The output which results in the lowest amount of swap gates (whether from the random trials or the property set starting point) will be used. The value for this property set field should be a list of [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") objects representing the starting layouts to use. If a virtual qubit is missing from an [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") object in the list a random qubit will be selected. ## Property Set Fields Read **`sabre_starting_layouts` (`list[Layout]`)** An optional list of [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") objects to use for additional layout trials. This is in addition to the full random trials specified with the `layout_trials` argument. ## Property Set Values Written **`layout` ([`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout""))** The chosen initial mapping of virtual to physical qubits, including the ancilla allocation. **`final_layout` ([`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout""))** A permutation of how swaps have been applied to the input qubits at the end of the circuit. **References:** \[1] Li, Gushu, Yufei Ding, and Yuan Xie. “Tackling the qubit mapping problem for NISQ-era quantum devices.” ASPLOS 2019. [arXiv:1809.02573](https://arxiv.org/pdf/1809.02573.pdf) SabreLayout initializer. **param coupling\_map** directed graph representing a coupling map. **type coupling\_map** Union\[CouplingMap, Target] **param routing\_pass** the routing pass to use while iterating. If specified this pass operates as an [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.AnalysisPass"") and will only populate the `layout` field in the property set and the input dag is returned unmodified. This argument is mutually exclusive with the `swap_trials` and the `layout_trials` arguments and if this is specified at the same time as either argument an error will be raised. **type routing\_pass** BasePass **param seed** seed for setting a random first trial layout. **type seed** int **param max\_iterations** number of forward-backward iterations. **type max\_iterations** int **param swap\_trials** The number of trials to run of [`SabreSwap`](qiskit.transpiler.passes.SabreSwap ""qiskit.transpiler.passes.SabreSwap"") for each iteration. This is equivalent to the `trials` argument on [`SabreSwap`](qiskit.transpiler.passes.SabreSwap ""qiskit.transpiler.passes.SabreSwap""). If this is not specified (and `routing_pass` isn’t set) by default the number of physical CPUs on your local system will be used. For reproducibility between environments it is best to set this to an explicit number because the output will potentially depend on the number of trials run. This option is mutually exclusive with the `routing_pass` argument and an error will be raised if both are used. **type swap\_trials** int **param layout\_trials** The number of random seed trials to run layout with. When > 1 the trial that resuls in the output with the fewest swap gates will be selected. If this is not specified (and `routing_pass` is not set) then the number of local physical CPUs will be used as the default value. This option is mutually exclusive with the `routing_pass` argument and an error will be raised if both are used. **type layout\_trials** int **param skip\_routing** If this is set `True` and `routing_pass` is not used then routing will not be applied to the output circuit. Only the layout will be set in the property set. This is a tradeoff to run custom routing with multiple layout trials, as using this option will cause SabreLayout to run the routing stage internally but not use that result. **type skip\_routing** bool **raises TranspilerError** If both `routing_pass` and `swap_trials` or **raises both `routing_pass` and `layout_trials` are specified** ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the SabreLayout pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to find layout for. **Returns** **The output dag if swap mapping was run** (otherwise the input dag is returned unmodified). **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if dag wider than self.coupling\_map ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.SabreLayout.mdx "--- title: SabrePreLayout description: API reference for qiskit.transpiler.passes.SabrePreLayout in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.SabrePreLayout --- # SabrePreLayout Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Choose a starting layout to use for additional Sabre layout trials. ## Property Set Values Written **`sabre_starting_layouts` (`list[Layout]`)** An optional list of [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") objects to use for additional Sabre layout trials. SabrePreLayout initializer. The pass works by augmenting the coupling map with more and more “extra” edges until VF2 succeeds to find a perfect graph isomorphism. More precisely, the augmented coupling map contains edges between nodes that are within a given distance `d` in the original coupling map, and the value of `d` is increased until an isomorphism is found. Intuitively, a better layout involves fewer extra edges. The pass also optionally minimizes the number of extra edges involved in the layout until a local minimum is found. This involves removing extra edges and running VF2 to see if an isomorphism still exists. **param coupling\_map** directed graph representing the original coupling map or a target modelling the backend (including its connectivity). **type coupling\_map** Union\[CouplingMap, Target] **param max\_distance** the maximum distance to consider for augmented coupling maps. **type max\_distance** int **param error\_rate** the error rate to assign to the “extra” edges. A non-zero error rate prioritizes VF2 to choose original edges over extra edges. **type error\_rate** float **param max\_trials\_vf2** specifies the maximum number of VF2 trials. A larger number allows VF2 to explore more layouts, eventually choosing the one with the smallest error rate. **type max\_trials\_vf2** int **param call\_limit\_vf2** limits each call to VF2 by bounding the number of VF2 state visits. **type call\_limit\_vf2** int **param improve\_layout** whether to improve the layout by minimizing the number of extra edges involved. This might be time-consuming as this requires additional VF2 calls. **type improve\_layout** bool **raises TranspilerError** At runtime, if neither `coupling_map` or `target` are provided. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the SabrePreLayout pass on dag. The discovered starting layout is written to the property set value `sabre_starting_layouts`. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to create starting layout for. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.SabrePreLayout.mdx "--- title: SabreSwap description: API reference for qiskit.transpiler.passes.SabreSwap in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.SabreSwap --- # SabreSwap Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Map input circuit onto a backend topology via insertion of SWAPs. Implementation of the SWAP-based heuristic search from the SABRE qubit mapping paper \[1] (Algorithm 1). The heuristic aims to minimize the number of lossy SWAPs inserted and the depth of the circuit. This algorithm starts from an initial layout of virtual qubits onto physical qubits, and iterates over the circuit DAG until all gates are exhausted, inserting SWAPs along the way. It only considers 2-qubit gates as only those are germane for the mapping problem (it is assumed that 3+ qubit gates are already decomposed). In each iteration, it will first check if there are any gates in the `front_layer` that can be directly applied. If so, it will apply them and remove them from `front_layer`, and replenish that layer with new gates if possible. Otherwise, it will try to search for SWAPs, insert the SWAPs, and update the mapping. The search for SWAPs is restricted, in the sense that we only consider physical qubits in the neighborhood of those qubits involved in `front_layer`. These give rise to a `swap_candidate_list` which is scored according to some heuristic cost function. The best SWAP is implemented and `current_layout` updated. This transpiler pass adds onto the SABRE algorithm in that it will run multiple trials of the algorithm with different seeds. The best output, determined by the trial with the least amount of SWAPed inserted, will be selected from the random trials. **References:** \[1] Li, Gushu, Yufei Ding, and Yuan Xie. “Tackling the qubit mapping problem for NISQ-era quantum devices.” ASPLOS 2019. [arXiv:1809.02573](https://arxiv.org/pdf/1809.02573.pdf) SabreSwap initializer. **Parameters** * **coupling\_map** (*Union\[*[*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")*,* [*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")*]*) – CouplingMap of the target backend. * **heuristic** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The type of heuristic to use when deciding best swap strategy (‘basic’ or ‘lookahead’ or ‘decay’). * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – random seed used to tie-break among candidate swaps. * **fake\_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if true, it only pretend to do routing, i.e., no swap is effectively added. * **trials** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of seed trials to run sabre with. These will be run in parallel (unless the PassManager is already running in parallel). If not specified this defaults to the number of physical CPUs on the local system. For reproducible results it is recommended that you set this explicitly, as the output will be deterministic for a fixed number of trials. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If the specified heuristic is not valid. Additional Information: > The search space of possible SWAPs on physical qubits is explored by assigning a score to the layout that would result from each SWAP. The goodness of a layout is evaluated based on how viable it makes the remaining virtual gates that must be applied. A few heuristic cost functions are supported > > * ‘basic’: > > The sum of distances for corresponding physical qubits of interacting virtual qubits in the front\_layer. > > $$ > H_{basic} = \sum_{gate \in F} D[\pi(gate.q_1)][\pi(gate.q2)] > $$ > > * ‘lookahead’: > > This is the sum of two costs: first is the same as the basic cost. Second is the basic cost but now evaluated for the extended set as well (i.e. $|E|$ number of upcoming successors to gates in front\_layer F). This is weighted by some amount EXTENDED\_SET\_WEIGHT (W) to signify that upcoming gates are less important that the front\_layer. > > $$ > H_{decay}=\frac{1}{\left|{F}\right|}\sum_{gate \in F} D[\pi(gate.q_1)][\pi(gate.q2)] > + W*\frac{1}{\left|{E}\right|} \sum_{gate \in E} D[\pi(gate.q_1)][\pi(gate.q2)] > $$ > > * ‘decay’: > > This is the same as ‘lookahead’, but the whole cost is multiplied by a decay factor. This increases the cost if the SWAP that generated the trial layout was recently used (i.e. it penalizes increase in depth). > > $$ > H_{decay} = max(decay(SWAP.q_1), decay(SWAP.q_2)) { > \frac{1}{\left|{F}\right|} \sum_{gate \in F} D[\pi(gate.q_1)][\pi(gate.q2)]\\ > + W *\frac{1}{\left|{E}\right|} \sum_{gate \in E} D[\pi(gate.q_1)][\pi(gate.q2)] > } > $$ ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the SabreSwap pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the directed acyclic graph to be mapped. **Returns** A dag mapped to be compatible with the coupling\_map. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the coupling map or the layout are not * **compatible with the DAG**\*\*, or \*\***if the coupling\_map=None** – ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.SabreSwap.mdx "--- title: SetIOLatency description: API reference for qiskit.transpiler.passes.SetIOLatency in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.SetIOLatency --- # SetIOLatency Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Set IOLatency information to the input circuit. The `clbit_write_latency` and `conditional_latency` are added to the property set of pass manager. This information can be shared among the passes that perform scheduling on instructions acting on classical registers. Once these latencies are added to the property set, this information is also copied to the output circuit object as protected attributes, so that it can be utilized outside the transpilation, for example, the timeline visualization can use latency to accurately show time occupation by instructions on the classical registers. Create pass with latency information. **Parameters** * **clbit\_write\_latency** – A control flow constraints. Because standard superconducting quantum processor implement dispersive QND readout, the actual data transfer to the clbit happens after the round-trip stimulus signal is buffered and discriminated into quantum state. The interval `[t0, t0 + clbit_write_latency]` is regarded as idle time for clbits associated with the measure instruction. This defaults to 0 dt which is identical to Qiskit Pulse scheduler. * **conditional\_latency** – A control flow constraints. This value represents a latency of reading a classical register for the conditional operation. The gate operation occurs after this latency. This appears as a delay in front of the DAGOpNode of the gate. This defaults to 0 dt. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Add IO latency information. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – Input DAG circuit. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.SetIOLatency.mdx "--- title: SetLayout description: API reference for qiskit.transpiler.passes.SetLayout in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.SetLayout --- # SetLayout Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Set the `layout` property to the given layout. This pass associates a physical qubit (int) to each virtual qubit of the circuit (Qubit) in increasing order. SetLayout initializer. **Parameters** **layout** ([*Layout*](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") *or List\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – the layout to set. It can be: * a `Layout` instance: sets that layout. * a list of integers: takes the index in the list as the physical position in which the virtual qubit is going to be mapped. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the SetLayout pass on `dag`. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to map. **Returns** the original DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.SetLayout.mdx "--- title: Size description: API reference for qiskit.transpiler.passes.Size in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Size --- # Size Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Calculate the size of a DAG circuit. The result is saved in `property_set['size']` as an integer. **Parameters** **recurse** – whether to allow recursion into control flow. If this is `False` (default), the pass will throw an error when control flow is present, to avoid returning a number with little meaning. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the Size pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Size.mdx "--- title: SolovayKitaev description: API reference for qiskit.transpiler.passes.SolovayKitaev in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.SolovayKitaev --- # SolovayKitaev Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Approximately decompose 1q gates to a discrete basis using the Solovay-Kitaev algorithm. The Solovay-Kitaev theorem \[1] states that any single qubit gate can be approximated to arbitrary precision by a set of fixed single-qubit gates, if the set generates a dense subset in $SU(2)$. This is an important result, since it means that any single-qubit gate can be expressed in terms of a discrete, universal gate set that we know how to implement fault-tolerantly. Therefore, the Solovay-Kitaev algorithm allows us to take any non-fault tolerant circuit and rephrase it in a fault-tolerant manner. This implementation of the Solovay-Kitaev algorithm is based on \[2]. For example, the following circuit ```python ┌─────────┐ q_0: ┤ RX(0.8) ├ └─────────┘ ``` can be decomposed into ```python global phase: 7π/8 ┌───┐┌───┐┌───┐ q_0: ┤ H ├┤ T ├┤ H ├ └───┘└───┘└───┘ ``` with an L2-error of approximately 0.01. **Examples** Per default, the basis gate set is `[""t"", ""tdg"", ""h""]`: ```python import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.transpiler.passes.synthesis import SolovayKitaev from qiskit.quantum_info import Operator circuit = QuantumCircuit(1) circuit.rx(0.8, 0) print(""Original circuit:"") print(circuit.draw()) skd = SolovayKitaev(recursion_degree=2) discretized = skd(circuit) print(""Discretized circuit:"") print(discretized.draw()) print(""Error:"", np.linalg.norm(Operator(circuit).data - Operator(discretized).data)) ``` ```python Original circuit: ┌─────────┐ q: ┤ Rx(0.8) ├ └─────────┘ Discretized circuit: global phase: 7π/8 ┌───┐┌───┐┌───┐ q: ┤ H ├┤ T ├┤ H ├ └───┘└───┘└───┘ Error: 2.828408279166474 ``` For individual basis gate sets, the `generate_basic_approximations` function can be used: ```python from qiskit.synthesis import generate_basic_approximations from qiskit.transpiler.passes import SolovayKitaev basis = [""s"", ""sdg"", ""t"", ""tdg"", ""z"", ""h""] approx = generate_basic_approximations(basis, depth=3) skd = SolovayKitaev(recursion_degree=2, basic_approximations=approx) ``` **References** **\[1]: Kitaev, A Yu (1997). Quantum computations: algorithms and error correction.** Russian Mathematical Surveys. 52 (6): 1191–1249. [Online](https://iopscience.iop.org/article/10.1070/RM1997v052n06ABEH002155). **\[2]: Dawson, Christopher M.; Nielsen, Michael A. (2005) The Solovay-Kitaev Algorithm.** [arXiv:quant-ph/0505030](https://arxiv.org/abs/quant-ph/0505030). **Parameters** * **recursion\_degree** – The recursion depth for the Solovay-Kitaev algorithm. A larger recursion depth increases the accuracy and length of the decomposition. * **basic\_approximations** – The basic approximations for the finding the best discrete decomposition at the root of the recursion. If a string, it specifies the `.npy` file to load the approximations from. If a dictionary, it contains `{label: SO(3)-matrix}` pairs. If None, a default based on the H, T and Tdg gates up to combinations of depth 10 is generated. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the `SolovayKitaev` pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – The input dag. **Returns** Output dag with 1q gates synthesized in the discrete target basis. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if a gates does not have to\_matrix **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.SolovayKitaev.mdx "--- title: StochasticSwap description: API reference for qiskit.transpiler.passes.StochasticSwap in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.StochasticSwap --- # StochasticSwap Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Map a DAGCircuit onto a coupling\_map adding swap gates. Uses a randomized algorithm. **Notes** 1. Measurements may occur and be followed by swaps that result in repeated measurement of the same qubit. Near-term experiments cannot implement these circuits, so some care is required when using this mapper with experimental backend targets. 2. We do not use the fact that the input state is zero to simplify the circuit. StochasticSwap initializer. The coupling map is a connected graph If these are not satisfied, the behavior is undefined. **Parameters** * **coupling\_map** (*Union\[*[*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")*,* [*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")*]*) – Directed graph representing a coupling map. * **trials** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – maximum number of iterations to attempt * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – seed for random number generator * **fake\_run** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – if true, it will only pretend to do routing, i.e., no swap is effectively added. * **initial\_layout** ([*Layout*](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"")) – starting layout at beginning of pass. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the StochasticSwap pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to map. **Returns** A mapped DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the coupling map or the layout are not * **compatible with the DAG**\*\*, or \*\***if the coupling\_map=None** – ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.StochasticSwap.mdx "--- title: AQCSynthesisPlugin description: API reference for qiskit.transpiler.passes.synthesis.aqc_plugin.AQCSynthesisPlugin in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.aqc_plugin.AQCSynthesisPlugin --- # AQCSynthesisPlugin Bases: [`UnitarySynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin"") An AQC-based Qiskit unitary synthesis plugin. This plugin is invoked by [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") when the `unitary_synthesis_method` parameter is set to `""aqc""`. This plugin supports customization and additional parameters can be passed to the plugin by passing a dictionary as the `unitary_synthesis_plugin_config` parameter of the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") function. Supported parameters in the dictionary: **network\_layout (str)** Type of network geometry, one of \{`""sequ""`, `""spin""`, `""cart""`, `""cyclic_spin""`, `""cyclic_line""`}. Default value is `""spin""`. **connectivity\_type (str)** type of inter-qubit connectivity, \{`""full""`, `""line""`, `""star""`}. Default value is `""full""`. **depth (int)** depth of the CNOT-network, i.e. the number of layers, where each layer consists of a single CNOT-block. **optimizer (`Minimizer`)** An implementation of the `Minimizer` protocol to be used in the optimization process. **seed (int)** A random seed. **initial\_point ([`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)""))** Initial values of angles/parameters to start the optimization process from. ## Attributes ### max\_qubits Maximum number of supported qubits is `14`. ### min\_qubits Minimum number of supported qubits is `3`. ### supported\_bases The plugin does not support bases for synthesis. ### supports\_basis\_gates The plugin does not support basis gates and by default it synthesizes a circuit using `[""rx"", ""ry"", ""rz"", ""cx""]` gate basis. ### supports\_coupling\_map The plugin does not support coupling maps. ### supports\_gate\_errors The plugin does not support gate errors. ### supports\_gate\_errors\_by\_qubit Return whether the plugin supports taking `gate_errors_by_qubit` This differs from `supports_gate_errors`/`gate_errors` by using a different view of the same data. Instead of being keyed by gate name this is keyed by qubit and uses [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") instances to represent gates (instead of gate names). `gate_errors_by_qubit` will be a dictionary in the form of `{(qubits,): [Gate, error]}`. For example: ```python { (0,): [SXGate(): 0.0006149355812506126, RZGate(): 0.0], (0, 1): [CXGate(): 0.012012477900732316] } ``` Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate errors on every gate for each qubit. The gate error rates reported in `gate_errors` are provided by the target device `Backend` object and the exact meaning might be different depending on the backend. This defaults to False ### supports\_gate\_lengths The plugin does not support gate lengths. ### supports\_gate\_lengths\_by\_qubit Return whether the plugin supports taking `gate_lengths_by_qubit` This differs from `supports_gate_lengths`/`gate_lengths` by using a different view of the same data. Instead of being keyed by gate name this is keyed by qubit and uses [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") instances to represent gates (instead of gate names) `gate_lengths_by_qubit` will be a dictionary in the form of `{(qubits,): [Gate, length]}`. For example: ```python { (0,): [SXGate(): 0.0006149355812506126, RZGate(): 0.0], (0, 1): [CXGate(): 0.012012477900732316] } ``` where the `length` value is in units of seconds. Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate lengths on every gate for each qubit. This defaults to False ### supports\_natural\_direction The plugin does not support natural direction, it assumes bidirectional two qubit gates. ### supports\_pulse\_optimize The plugin does not support optimization of pulses. ### supports\_target Whether the plugin supports taking `target` as an option `target` will be a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object representing the target device for the output of the synthesis pass. By default this will be `False` since the plugin interface predates the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") class. If a plugin returns `True` for this attribute, it is expected that the plugin will use the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") instead of the values passed if any of `supports_gate_lengths`, `supports_gate_errors`, `supports_coupling_map`, and `supports_basis_gates` are set (although ideally all those parameters should contain duplicate information). ## Methods ### run Run synthesis for the given unitary matrix **Parameters** * **unitary** ([*numpy.ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – The unitary matrix to synthesize to a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") object * **options** – The optional kwargs that are passed based on the output the `support_*` methods on the class. Refer to the documentation for these methods on [`UnitarySynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin"") to see what the keys and values are. **Returns** The dag circuit representation of the unitary. Alternatively, you can return a tuple of the form `(dag, wires)` where `dag` is the dag circuit representation of the circuit representation of the unitary and `wires` is the mapping wires to use for [`qiskit.dagcircuit.DAGCircuit.substitute_node_with_dag()`](qiskit.dagcircuit.DAGCircuit#substitute_node_with_dag ""qiskit.dagcircuit.DAGCircuit.substitute_node_with_dag""). If you return a tuple and `wires` is `None` this will behave just as if only a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") was returned. Additionally if this returns `None` no substitution will be made. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.aqc_plugin.AQCSynthesisPlugin.mdx "--- title: ACGSynthesisPermutation description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.ACGSynthesisPermutation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.ACGSynthesisPermutation --- # ACGSynthesisPermutation Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") The permutation synthesis plugin based on the Alon, Chung, Graham method. This plugin name is :`permutation.acg` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given Permutation. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.ACGSynthesisPermutation.mdx "--- title: AGSynthesisClifford description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.AGSynthesisClifford in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.AGSynthesisClifford --- # AGSynthesisClifford Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") Clifford synthesis plugin based on the Aaronson-Gottesman method. This plugin name is :`clifford.ag` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given Clifford. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.AGSynthesisClifford.mdx "--- title: BasicSynthesisPermutation description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.BasicSynthesisPermutation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.BasicSynthesisPermutation --- # BasicSynthesisPermutation Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") The permutation synthesis plugin based on sorting. This plugin name is :`permutation.basic` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given Permutation. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.BasicSynthesisPermutation.mdx "--- title: BMSynthesisClifford description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.BMSynthesisClifford in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.BMSynthesisClifford --- # BMSynthesisClifford Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") Clifford synthesis plugin based on the Bravyi-Maslov method. The method only works on Cliffords with at most 3 qubits, for which it constructs the optimal CX cost decomposition. This plugin name is :`clifford.bm` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given Clifford. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.BMSynthesisClifford.mdx "--- title: DefaultSynthesisClifford description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisClifford in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisClifford --- # DefaultSynthesisClifford Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") The default clifford synthesis plugin. For N \<= 3 qubits this is the optimal CX cost decomposition by Bravyi, Maslov. For N > 3 qubits this is done using the general non-optimal greedy compilation routine from reference by Bravyi, Hu, Maslov, Shaydulin. This plugin name is :`clifford.default` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given Clifford. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisClifford.mdx "--- title: DefaultSynthesisLinearFunction description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisLinearFunction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisLinearFunction --- # DefaultSynthesisLinearFunction Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") The default linear function synthesis plugin. This plugin name is :`linear_function.default` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given LinearFunction. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisLinearFunction.mdx "--- title: GreedySynthesisClifford description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.GreedySynthesisClifford in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.GreedySynthesisClifford --- # GreedySynthesisClifford Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") Clifford synthesis plugin based on the greedy synthesis Bravyi-Hu-Maslov-Shaydulin method. This plugin name is :`clifford.greedy` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given Clifford. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.GreedySynthesisClifford.mdx "--- title: KMSSynthesisLinearFunction description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisLinearFunction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisLinearFunction --- # KMSSynthesisLinearFunction Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") Linear function synthesis plugin based on the Kutin-Moulton-Smithline method. This plugin name is :`linear_function.kms` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given LinearFunction. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisLinearFunction.mdx "--- title: KMSSynthesisPermutation description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisPermutation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisPermutation --- # KMSSynthesisPermutation Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") The permutation synthesis plugin based on the Kutin, Moulton, Smithline method. This plugin name is :`permutation.kms` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given Permutation. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisPermutation.mdx "--- title: LayerLnnSynthesisClifford description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerLnnSynthesisClifford in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerLnnSynthesisClifford --- # LayerLnnSynthesisClifford Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") Clifford synthesis plugin based on the Bravyi-Maslov method to synthesize Cliffords into layers, with each layer synthesized adhering to LNN connectivity. This plugin name is :`clifford.lnn` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given Clifford. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerLnnSynthesisClifford.mdx "--- title: LayerSynthesisClifford description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerSynthesisClifford in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerSynthesisClifford --- # LayerSynthesisClifford Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") Clifford synthesis plugin based on the Bravyi-Maslov method to synthesize Cliffords into layers. This plugin name is :`clifford.layers` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given Clifford. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerSynthesisClifford.mdx "--- title: PMHSynthesisLinearFunction description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.PMHSynthesisLinearFunction in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.PMHSynthesisLinearFunction --- # PMHSynthesisLinearFunction Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") Linear function synthesis plugin based on the Patel-Markov-Hayes method. This plugin name is :`linear_function.pmh` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). ## Methods ### run Run synthesis for the given LinearFunction. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.PMHSynthesisLinearFunction.mdx "--- title: TokenSwapperSynthesisPermutation description: API reference for qiskit.transpiler.passes.synthesis.high_level_synthesis.TokenSwapperSynthesisPermutation in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.high_level_synthesis.TokenSwapperSynthesisPermutation --- # TokenSwapperSynthesisPermutation Bases: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") The permutation synthesis plugin based on the token swapper algorithm. This plugin name is :`permutation.token_swapper` which can be used as the key on an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HLSConfig"") object to use this method with [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis""). In more detail, this plugin is used to synthesize objects of type PermutationGate. When synthesis succeeds, the plugin outputs a quantum circuit consisting only of swap gates. When synthesis does not succeed, the plugin outputs None. If either coupling\_map or qubits is None, then the synthesized circuit is not required to adhere to connectivity constraints, as is the case when the synthesis is done before layout/routing. On the other hand, if both coupling\_map and qubits are specified, the synthesized circuit is supposed to adhere to connectivity constraints. At the moment, the plugin only creates swap gates between qubits in qubits, i.e. it does not use any other qubits in the coupling map (if such synthesis is not possible, the plugin outputs None). The plugin supports the following plugin-specific options: * trials: The number of trials for the token swapper to perform the mapping. The circuit with the smallest number of SWAPs is returned. * seed: The argument to the token swapper specifying the seed for random trials. * parallel\_threshold: The argument to the token swapper specifying the number of nodes in the graph beyond which the algorithm will use parallel processing. For more details on the token swapper algorithm, see to the paper: [arXiv:1902.09102](https://arxiv.org/abs/1902.09102). ## Methods ### run Run synthesis for the given Permutation. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.high_level_synthesis.TokenSwapperSynthesisPermutation.mdx "--- title: HighLevelSynthesisPlugin description: API reference for qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin --- # HighLevelSynthesisPlugin Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Abstract high-level synthesis plugin class. This abstract class defines the interface for high-level synthesis plugins. ## Methods ### run Run synthesis for the given Operation. **Parameters** * **high\_level\_object** ([*Operation*](qiskit.circuit.Operation ""qiskit.circuit.Operation"")) – The Operation to synthesize to a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") object. * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")) – The coupling map of the backend in case synthesis is done on a physical circuit. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – A target representing the target backend. * **qubits** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of qubits over which the operation is defined in case synthesis is done on a physical circuit. * **options** – Additional method-specific optional kwargs. **Returns** **The quantum circuit representation of the Operation** when successful, and `None` otherwise. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin.mdx "--- title: HighLevelSynthesisPluginManager description: API reference for qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPluginManager in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPluginManager --- # HighLevelSynthesisPluginManager Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Class tracking the installed high-level-synthesis plugins. ## Methods ### method Returns the plugin for `op_name` and `method_name`. ### method\_names Returns plugin methods for op\_name. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPluginManager.mdx "--- title: high_level_synthesis_plugin_names description: API reference for qiskit.transpiler.passes.synthesis.plugin.high_level_synthesis_plugin_names in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.transpiler.passes.synthesis.plugin.high_level_synthesis_plugin_names --- # qiskit.transpiler.passes.synthesis.plugin.high\_level\_synthesis\_plugin\_names Return a list of plugin names installed for a given high level object name **Parameters** **op\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The operation name to find the installed plugins for. For example, if you provide `""clifford""` as the input it will find all the installed clifford synthesis plugins that can synthesize [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") objects. The name refers to the [`Operation.name`](qiskit.circuit.Operation#name ""qiskit.circuit.Operation.name"") attribute of the relevant objects. **Returns** A list of installed plugin names for the specified high level operation **Return type** [*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)"")] ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.plugin.high_level_synthesis_plugin_names.mdx "--- title: UnitarySynthesisPlugin description: API reference for qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin --- # UnitarySynthesisPlugin Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") Abstract unitary synthesis plugin class This abstract class defines the interface for unitary synthesis plugins. ## Attributes ### max\_qubits Return the maximum number of qubits the unitary synthesis plugin supports. If the size of the unitary to be synthesized exceeds this value the `default` plugin will be used. If there is no upper bound return `None` and all unitaries (`>= min_qubits` if it’s defined) will be passed to this plugin when it’s enabled. ### min\_qubits Return the minimum number of qubits the unitary synthesis plugin supports. If the size of the unitary to be synthesized is below this value the `default` plugin will be used. If there is no lower bound return `None` and all unitaries (`<= max_qubits` if it’s defined) will be passed to this plugin when it’s enabled. ### supported\_bases Returns a dictionary of supported bases for synthesis This is expected to return a dictionary where the key is a string basis and the value is a list of gate names that the basis works in. If the synthesis method doesn’t support multiple bases this should return `None`. For example: ```python { ""XZX"": [""rz"", ""rx""], ""XYX"": [""rx"", ""ry""], } ``` If a dictionary is returned by this method the run kwargs will be passed a parameter `matched_basis` which contains a list of the basis strings (i.e. keys in the dictionary) which match the target basis gate set for the transpilation. If no entry in the dictionary matches the target basis gate set then the `matched_basis` kwarg will be set to an empty list, and a plugin can choose how to deal with the target basis gate set not matching the plugin’s capabilities. ### supports\_basis\_gates Return whether the plugin supports taking `basis_gates` If this returns `True` the plugin’s `run()` method will be passed a `basis_gates` kwarg with a list of gate names the target backend supports. For example, `['sx', 'x', 'cx', 'id', 'rz']`. ### supports\_coupling\_map Return whether the plugin supports taking `coupling_map` If this returns `True` the plugin’s `run()` method will receive one kwarg `coupling_map`. The `coupling_map` kwarg will be set to a tuple with the first element being a [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") object representing the qubit connectivity of the target backend, the second element will be a list of integers that represent the qubit indices in the coupling map that unitary is on. Note that if the target backend doesn’t have a coupling map set, the `coupling_map` kwarg’s value will be `(None, qubit_indices)`. ### supports\_gate\_errors Return whether the plugin supports taking `gate_errors` `gate_errors` will be a dictionary in the form of `{gate_name: {(qubit_1, qubit_2): error}}`. For example: ```python { 'sx': {(0,): 0.0006149355812506126, (1,): 0.0006149355812506126}, 'cx': {(0, 1): 0.012012477900732316, (1, 0): 5.191111111111111e-07} } ``` Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate errors on every gate for each qubit. The gate error rates reported in `gate_errors` are provided by the target device `Backend` object and the exact meaning might be different depending on the backend. ### supports\_gate\_errors\_by\_qubit Return whether the plugin supports taking `gate_errors_by_qubit` This differs from `supports_gate_errors`/`gate_errors` by using a different view of the same data. Instead of being keyed by gate name this is keyed by qubit and uses [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") instances to represent gates (instead of gate names). `gate_errors_by_qubit` will be a dictionary in the form of `{(qubits,): [Gate, error]}`. For example: ```python { (0,): [SXGate(): 0.0006149355812506126, RZGate(): 0.0], (0, 1): [CXGate(): 0.012012477900732316] } ``` Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate errors on every gate for each qubit. The gate error rates reported in `gate_errors` are provided by the target device `Backend` object and the exact meaning might be different depending on the backend. This defaults to False ### supports\_gate\_lengths Return whether the plugin supports taking `gate_lengths` `gate_lengths` will be a dictionary in the form of `{gate_name: {(qubit_1, qubit_2): length}}`. For example: ```python { 'sx': {(0,): 0.0006149355812506126, (1,): 0.0006149355812506126}, 'cx': {(0, 1): 0.012012477900732316, (1, 0): 5.191111111111111e-07} } ``` where the `length` value is in units of seconds. Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate lengths on every gate for each qubit. ### supports\_gate\_lengths\_by\_qubit Return whether the plugin supports taking `gate_lengths_by_qubit` This differs from `supports_gate_lengths`/`gate_lengths` by using a different view of the same data. Instead of being keyed by gate name this is keyed by qubit and uses [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") instances to represent gates (instead of gate names) `gate_lengths_by_qubit` will be a dictionary in the form of `{(qubits,): [Gate, length]}`. For example: ```python { (0,): [SXGate(): 0.0006149355812506126, RZGate(): 0.0], (0, 1): [CXGate(): 0.012012477900732316] } ``` where the `length` value is in units of seconds. Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate lengths on every gate for each qubit. This defaults to False ### supports\_natural\_direction Return whether the plugin supports a toggle for considering directionality of 2-qubit gates as `natural_direction`. Refer to the documentation for [`UnitarySynthesis`](qiskit.transpiler.passes.UnitarySynthesis ""qiskit.transpiler.passes.UnitarySynthesis"") for the possible values and meaning of these values. ### supports\_pulse\_optimize Return whether the plugin supports a toggle to optimize pulses during synthesis as `pulse_optimize`. Refer to the documentation for [`UnitarySynthesis`](qiskit.transpiler.passes.UnitarySynthesis ""qiskit.transpiler.passes.UnitarySynthesis"") for the possible values and meaning of these values. ### supports\_target Whether the plugin supports taking `target` as an option `target` will be a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object representing the target device for the output of the synthesis pass. By default this will be `False` since the plugin interface predates the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") class. If a plugin returns `True` for this attribute, it is expected that the plugin will use the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") instead of the values passed if any of `supports_gate_lengths`, `supports_gate_errors`, `supports_coupling_map`, and `supports_basis_gates` are set (although ideally all those parameters should contain duplicate information). ## Methods ### run Run synthesis for the given unitary matrix **Parameters** * **unitary** ([*numpy.ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – The unitary matrix to synthesize to a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") object * **options** – The optional kwargs that are passed based on the output the `support_*` methods on the class. Refer to the documentation for these methods on [`UnitarySynthesisPlugin`](#qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin"") to see what the keys and values are. **Returns** The dag circuit representation of the unitary. Alternatively, you can return a tuple of the form `(dag, wires)` where `dag` is the dag circuit representation of the circuit representation of the unitary and `wires` is the mapping wires to use for [`qiskit.dagcircuit.DAGCircuit.substitute_node_with_dag()`](qiskit.dagcircuit.DAGCircuit#substitute_node_with_dag ""qiskit.dagcircuit.DAGCircuit.substitute_node_with_dag""). If you return a tuple and `wires` is `None` this will behave just as if only a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") was returned. Additionally if this returns `None` no substitution will be made. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin.mdx "--- title: UnitarySynthesisPluginManager description: API reference for qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPluginManager in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPluginManager --- # UnitarySynthesisPluginManager Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Unitary Synthesis plugin manager class This class tracks the installed plugins, it has a single property, `ext_plugins` which contains a list of stevedore plugin objects. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPluginManager.mdx "--- title: unitary_synthesis_plugin_names description: API reference for qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names --- # qiskit.transpiler.passes.synthesis.plugin.unitary\_synthesis\_plugin\_names Return a list of installed unitary synthesis plugin names **Returns** A list of the installed unitary synthesis plugin names. The plugin names are valid values for the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") kwarg `unitary_synthesis_method`. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names.mdx "--- title: SolovayKitaevSynthesis description: API reference for qiskit.transpiler.passes.synthesis.solovay_kitaev_synthesis.SolovayKitaevSynthesis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.solovay_kitaev_synthesis.SolovayKitaevSynthesis --- # SolovayKitaevSynthesis Bases: [`UnitarySynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin"") A Solovay-Kitaev Qiskit unitary synthesis plugin. This plugin is invoked by [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") when the `unitary_synthesis_method` parameter is set to `""sk""`. This plugin supports customization and additional parameters can be passed to the plugin by passing a dictionary as the `unitary_synthesis_plugin_config` parameter of the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") function. Supported parameters in the dictionary: **basis\_approximations (str | dict):** The basic approximations for the finding the best discrete decomposition at the root of the recursion. If a string, it specifies the `.npy` file to load the approximations from. If a dictionary, it contains `{label: SO(3)-matrix}` pairs. If None, a default based on the specified `basis_gates` and `depth` is generated. **basis\_gates (list):** A list of strings specifying the discrete basis gates to decompose to. If None, defaults to `[""h"", ""t"", ""tdg""]`. **depth (int):** The gate-depth of the basic approximations. All possible, unique combinations of the basis gates up to length `depth` are considered. If None, defaults to 10. **recursion\_degree (int):** The number of times the decomposition is recursively improved. If None, defaults to 3. ## Attributes ### max\_qubits Maximum number of supported qubits is `1`. ### min\_qubits Minimum number of supported qubits is `1`. ### supported\_bases The plugin does not support bases for synthesis. ### supports\_basis\_gates The plugin does not support basis gates. By default it synthesis to the `[""h"", ""t"", ""tdg""]` gate basis. ### supports\_coupling\_map The plugin does not support coupling maps. ### supports\_gate\_errors The plugin does not support gate errors. ### supports\_gate\_errors\_by\_qubit Return whether the plugin supports taking `gate_errors_by_qubit` This differs from `supports_gate_errors`/`gate_errors` by using a different view of the same data. Instead of being keyed by gate name this is keyed by qubit and uses [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") instances to represent gates (instead of gate names). `gate_errors_by_qubit` will be a dictionary in the form of `{(qubits,): [Gate, error]}`. For example: ```python { (0,): [SXGate(): 0.0006149355812506126, RZGate(): 0.0], (0, 1): [CXGate(): 0.012012477900732316] } ``` Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate errors on every gate for each qubit. The gate error rates reported in `gate_errors` are provided by the target device `Backend` object and the exact meaning might be different depending on the backend. This defaults to False ### supports\_gate\_lengths The plugin does not support gate lengths. ### supports\_gate\_lengths\_by\_qubit Return whether the plugin supports taking `gate_lengths_by_qubit` This differs from `supports_gate_lengths`/`gate_lengths` by using a different view of the same data. Instead of being keyed by gate name this is keyed by qubit and uses [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") instances to represent gates (instead of gate names) `gate_lengths_by_qubit` will be a dictionary in the form of `{(qubits,): [Gate, length]}`. For example: ```python { (0,): [SXGate(): 0.0006149355812506126, RZGate(): 0.0], (0, 1): [CXGate(): 0.012012477900732316] } ``` where the `length` value is in units of seconds. Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate lengths on every gate for each qubit. This defaults to False ### supports\_natural\_direction The plugin does not support natural direction, it does not assume bidirectional two qubit gates. ### supports\_pulse\_optimize The plugin does not support optimization of pulses. ### supports\_target Whether the plugin supports taking `target` as an option `target` will be a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object representing the target device for the output of the synthesis pass. By default this will be `False` since the plugin interface predates the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") class. If a plugin returns `True` for this attribute, it is expected that the plugin will use the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") instead of the values passed if any of `supports_gate_lengths`, `supports_gate_errors`, `supports_coupling_map`, and `supports_basis_gates` are set (although ideally all those parameters should contain duplicate information). ## Methods ### run Run synthesis for the given unitary matrix **Parameters** * **unitary** ([*numpy.ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – The unitary matrix to synthesize to a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") object * **options** – The optional kwargs that are passed based on the output the `support_*` methods on the class. Refer to the documentation for these methods on [`UnitarySynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin"") to see what the keys and values are. **Returns** The dag circuit representation of the unitary. Alternatively, you can return a tuple of the form `(dag, wires)` where `dag` is the dag circuit representation of the circuit representation of the unitary and `wires` is the mapping wires to use for [`qiskit.dagcircuit.DAGCircuit.substitute_node_with_dag()`](qiskit.dagcircuit.DAGCircuit#substitute_node_with_dag ""qiskit.dagcircuit.DAGCircuit.substitute_node_with_dag""). If you return a tuple and `wires` is `None` this will behave just as if only a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") was returned. Additionally if this returns `None` no substitution will be made. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.solovay_kitaev_synthesis.SolovayKitaevSynthesis.mdx "--- title: DefaultUnitarySynthesis description: API reference for qiskit.transpiler.passes.synthesis.unitary_synthesis.DefaultUnitarySynthesis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.synthesis.unitary_synthesis.DefaultUnitarySynthesis --- # DefaultUnitarySynthesis Bases: [`UnitarySynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin"") The default unitary synthesis plugin. ## Attributes ### max\_qubits ### min\_qubits ### supported\_bases ### supports\_basis\_gates ### supports\_coupling\_map ### supports\_gate\_errors ### supports\_gate\_errors\_by\_qubit ### supports\_gate\_lengths ### supports\_gate\_lengths\_by\_qubit ### supports\_natural\_direction ### supports\_pulse\_optimize ### supports\_target ## Methods ### run Run synthesis for the given unitary matrix **Parameters** * **unitary** ([*numpy.ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – The unitary matrix to synthesize to a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") object * **options** – The optional kwargs that are passed based on the output the `support_*` methods on the class. Refer to the documentation for these methods on [`UnitarySynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin"") to see what the keys and values are. **Returns** The dag circuit representation of the unitary. Alternatively, you can return a tuple of the form `(dag, wires)` where `dag` is the dag circuit representation of the circuit representation of the unitary and `wires` is the mapping wires to use for [`qiskit.dagcircuit.DAGCircuit.substitute_node_with_dag()`](qiskit.dagcircuit.DAGCircuit#substitute_node_with_dag ""qiskit.dagcircuit.DAGCircuit.substitute_node_with_dag""). If you return a tuple and `wires` is `None` this will behave just as if only a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") was returned. Additionally if this returns `None` no substitution will be made. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.synthesis.unitary_synthesis.DefaultUnitarySynthesis.mdx "--- title: TemplateOptimization description: API reference for qiskit.transpiler.passes.TemplateOptimization in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.TemplateOptimization --- # TemplateOptimization Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Class for the template optimization pass. **Parameters** * **template\_list** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*()]*) – list of the different template circuit to apply. * **heuristics\_backward\_param** ([*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)"")*]*) – \[length, survivor] Those are the parameters for applying heuristics on the backward part of the algorithm. This part of the algorithm creates a tree of matching scenario. This tree grows exponentially. The heuristics evaluate which scenarios have the longest match and keep only those. The length is the interval in the tree for cutting it and survivor is the number of scenarios that are kept. We advise to use l=3 and s=1 to have serious time advantage. We remind that the heuristics implies losing a part of the maximal matches. Check reference for more details. * **heuristics\_qubits\_param** ([*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)"")*]*) – \[length] The heuristics for the qubit choice make guesses from the dag dependency of the circuit in order to limit the number of qubit configurations to explore. The length is the number of successors or not predecessors that will be explored in the dag dependency of the circuit, each qubits of the nodes are added to the set of authorized qubits. We advise to use length=1. Check reference for more details. * **user\_cost\_dict** (*Dict\[*[*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)"")*]*) – quantum cost dictionary passed to TemplateSubstitution to configure its behavior. This will override any default values if None is not given. The key is the name of the gate and the value its quantum cost. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG circuit. **Returns** optimized DAG circuit. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If the template has not the right form or if the output circuit acts differently as the input circuit. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.TemplateOptimization.mdx "--- title: TimeUnitConversion description: API reference for qiskit.transpiler.passes.TimeUnitConversion in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.TimeUnitConversion --- # TimeUnitConversion Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Choose a time unit to be used in the following time-aware passes, and make all circuit time units consistent with that. This pass will add a [`Instruction.duration`](qiskit.circuit.Instruction#duration ""qiskit.circuit.Instruction.duration"") metadata to each op whose duration is known which will be used by subsequent scheduling passes for scheduling. If `dt` (in seconds) is known to transpiler, the unit `'dt'` is chosen. Otherwise, the unit to be selected depends on what units are used in delays and instruction durations: * `'s'`: if they are all in SI units. * `'dt'`: if they are all in the unit `'dt'`. * raise error: if they are a mix of SI units and `'dt'`. TimeUnitAnalysis initializer. **Parameters** * **inst\_durations** ([*InstructionDurations*](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"")) – A dictionary of durations of instructions. * **target** – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing the target backend, if both `inst_durations` and `target` are specified then this argument will take precedence and `inst_durations` will be ignored. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the TimeUnitAnalysis pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to be checked. **Returns** DAG with consistent timing and op nodes annotated with duration. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the units are not unifiable ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.TimeUnitConversion.mdx "--- title: TranslateParameterizedGates description: API reference for qiskit.transpiler.passes.TranslateParameterizedGates in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.TranslateParameterizedGates --- # TranslateParameterizedGates Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Translate parameterized gates to a supported basis set. Once a parameterized instruction is found that is not in the `supported_gates` list, the instruction is decomposed one level and the parameterized sub-blocks are recursively decomposed. The recursion is stopped once all parameterized gates are in `supported_gates`, or if a gate has no definition and a translation to the basis is attempted (this might happen e.g. for the `UGate` if it’s not in the specified gate list). **Example** The following, multiply nested circuit: ```python from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.transpiler.passes import TranslateParameterizedGates x = ParameterVector(""x"", 4) block1 = QuantumCircuit(1) block1.rx(x[0], 0) sub_block = QuantumCircuit(2) sub_block.cx(0, 1) sub_block.rz(x[2], 0) block2 = QuantumCircuit(2) block2.ry(x[1], 0) block2.append(sub_block.to_gate(), [0, 1]) block3 = QuantumCircuit(3) block3.ccx(0, 1, 2) circuit = QuantumCircuit(3) circuit.append(block1.to_gate(), [1]) circuit.append(block2.to_gate(), [0, 1]) circuit.append(block3.to_gate(), [0, 1, 2]) circuit.cry(x[3], 0, 2) supported_gates = [""rx"", ""ry"", ""rz"", ""cp"", ""crx"", ""cry"", ""crz""] unrolled = TranslateParameterizedGates(supported_gates)(circuit) ``` is decomposed to: ```python ┌──────────┐ ┌──────────┐┌─────────────┐ q_0: ┤ Ry(x[1]) ├──■──┤ Rz(x[2]) ├┤0 ├─────■────── ├──────────┤┌─┴─┐└──────────┘│ │ │ q_1: ┤ Rx(x[0]) ├┤ X ├────────────┤1 circuit-92 ├─────┼────── └──────────┘└───┘ │ │┌────┴─────┐ q_2: ─────────────────────────────┤2 ├┤ Ry(x[3]) ├ └─────────────┘└──────────┘ ``` **Parameters** * **supported\_gates** – A list of suppported basis gates specified as string. If `None`, a `target` must be provided. * **equivalence\_library** – The equivalence library to translate the gates. Defaults to the equivalence library of all Qiskit standard gates. * **target** – A [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") containing the supported operations. If `None`, `supported_gates` must be set. Note that this argument takes precedence over `supported_gates`, if both are set. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If neither of `supported_gates` and `target` are passed. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the transpiler pass. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – The DAG circuit in which the parameterized gates should be unrolled. **Returns** A DAG where the parameterized gates have been unrolled. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If the circuit cannot be unrolled. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.TranslateParameterizedGates.mdx "--- title: TrivialLayout description: API reference for qiskit.transpiler.passes.TrivialLayout in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.TrivialLayout --- # TrivialLayout Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Choose a Layout by assigning `n` circuit qubits to device qubits `0, .., n-1`. A pass for choosing a Layout of a circuit onto a Coupling graph, using a simple round-robin order. This pass associates a physical qubit (int) to each virtual qubit of the circuit (Qubit) in increasing order. Does not assume any ancilla. TrivialLayout initializer. **Parameters** **coupling\_map** (*Union\[*[*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")*,* [*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")*]*) – directed graph representing a coupling map. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if invalid options ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the TrivialLayout pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – DAG to find layout for. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if dag wider than the target backend ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.TrivialLayout.mdx "--- title: UnitarySynthesis description: API reference for qiskit.transpiler.passes.UnitarySynthesis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.UnitarySynthesis --- # UnitarySynthesis Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Synthesize gates according to their basis gates. Synthesize unitaries over some basis gates. This pass can approximate 2-qubit unitaries given some gate fidelities (either via `backend_props` or `target`). More approximation can be forced by setting a heuristic dial `approximation_degree`. **Parameters** * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – List of gate names to target. If this is not specified the `target` argument must be used. If both this and the `target` are specified the value of `target` will be used and this will be ignored. * **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). Approximation can make the synthesized circuit cheaper at the cost of straying from the original unitary. If None, approximation is done based on gate fidelities. * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")) – the coupling map of the backend in case synthesis is done on a physical circuit. The directionality of the coupling\_map will be taken into account if `pulse_optimize` is `True`/`None` and `natural_direction` is `True`/`None`. * **backend\_props** ([*BackendProperties*](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"")) – Properties of a backend to synthesize for (e.g. gate fidelities). * **pulse\_optimize** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to optimize pulses during synthesis. A value of `None` will attempt it but fall back if it does not succeed. A value of `True` will raise an error if pulse-optimized synthesis does not succeed. * **natural\_direction** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to apply synthesis considering directionality of 2-qubit gates. Only applies when `pulse_optimize` is `True` or `None`. The natural direction is determined by first checking to see whether the coupling map is unidirectional. If there is no coupling map or the coupling map is bidirectional, the gate direction with the shorter duration from the backend properties will be used. If set to True, and a natural direction can not be determined, raises [`TranspilerError`](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError""). If set to None, no exception will be raised if a natural direction can not be determined. * **synth\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – List of gates to synthesize. If None and `pulse_optimize` is False or None, default to `['unitary']`. If `None` and `pulse_optimize == True`, default to `['unitary', 'swap']` * **method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The unitary synthesis method plugin to use. * **min\_qubits** – The minimum number of qubits in the unitary to synthesize. If this is set and the unitary is less than the specified number of qubits it will not be synthesized. * **plugin\_config** – Optional extra configuration arguments (as a `dict`) which are passed directly to the specified unitary synthesis plugin. By default, this will have no effect as the default plugin has no extra arguments. Refer to the documentation of your unitary synthesis plugin on how to use this. * **target** – The optional [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") for the target device the pass is compiling for. If specified this will supersede the values set for `basis_gates`, `coupling_map`, and `backend_props`. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if `method` was specified but is not found in the installed plugins list. The list of installed plugins can be queried with [`unitary_synthesis_plugin_names()`](qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names ""qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names"") ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the UnitarySynthesis pass on `dag`. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – input dag. **Returns** Output dag with UnitaryGates synthesized to target basis. **Return type** [*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.UnitarySynthesis.mdx "--- title: Unroll3qOrMore description: API reference for qiskit.transpiler.passes.Unroll3qOrMore in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Unroll3qOrMore --- # Unroll3qOrMore Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Recursively expands 3q+ gates until the circuit only contains 2q or 1q gates. Initialize the Unroll3qOrMore pass **Parameters** * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The target object representing the compilation target. If specified any multi-qubit instructions in the circuit when the pass is run that are supported by the target device will be left in place. If both this and `basis_gates` are specified only the target will be checked. * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of basis gate names that the target device supports. If specified any gate names in the circuit which are present in this list will not be unrolled. If both this and `target` are specified only the target will be used for checking which gates are supported. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the Unroll3qOrMore pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – input dag **Returns** output dag with maximum node degrees of 2 **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if a 3q+ gate is not decomposable ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Unroll3qOrMore.mdx "--- title: UnrollCustomDefinitions description: API reference for qiskit.transpiler.passes.UnrollCustomDefinitions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.UnrollCustomDefinitions --- # UnrollCustomDefinitions Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") Unrolls instructions with custom definitions. Unrolls instructions with custom definitions. **Parameters** * **equivalence\_library** ([*EquivalenceLibrary*](qiskit.circuit.EquivalenceLibrary ""qiskit.circuit.EquivalenceLibrary"")) – The equivalence library which will be used by the BasisTranslator pass. (Instructions in this library will not be unrolled by this pass.) * **basis\_gates** (*Optional\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]]*) – Target basis names to unroll to, e.g. `['u3', 'cx']`. Ignored if `target` is also specified. * **target** (*Optional\[*[*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")*]*) – **The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object corresponding to the compilation** target. When specified, any argument specified for `basis_gates` is ignored. **min\_qubits (int): The minimum number of qubits for operations in the input** dag to translate. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the UnrollCustomDefinitions pass on dag. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – input dag **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if unable to unroll given the basis due to undefined * **decomposition rules**\*\* (****such as a bad basis****) or \*\***excessive recursion.** – **Returns** output unrolled dag **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.UnrollCustomDefinitions.mdx "--- title: UnrollForLoops description: API reference for qiskit.transpiler.passes.UnrollForLoops in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.UnrollForLoops --- # UnrollForLoops Bases: [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.basepasses.TransformationPass"") `UnrollForLoops` transpilation pass unrolls for-loops when possible. Things like `for x in {0, 3, 4} {rx(x) qr[1];}` will turn into `rx(0) qr[1]; rx(3) qr[1]; rx(4) qr[1];`. The `UnrollForLoops` unrolls only one level of block depth. No inner loop will be considered by `max_target_depth`. **Parameters** **max\_target\_depth** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional. Checks if the unrolled block is over a particular subcircuit depth. To disable the check, use `-1` (Default). ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the UnrollForLoops pass on `dag`. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – the directed acyclic graph to run on. **Returns** Transformed DAG. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.UnrollForLoops.mdx "--- title: ValidatePulseGates description: API reference for qiskit.transpiler.passes.ValidatePulseGates in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.ValidatePulseGates --- # ValidatePulseGates Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Check custom gate length. This is a control electronics aware analysis pass. Quantum gates (instructions) are often implemented with shaped analog stimulus signals. These signals may be digitally stored in the waveform memory of the control electronics and converted into analog voltage signals by electronic components known as digital to analog converters (DAC). In Qiskit SDK, we can define the pulse-level implementation of custom quantum gate instructions, as a [pulse gate](/build/pulse), thus user gates should satisfy all waveform memory constraints imposed by the backend. This pass validates all attached calibration entries and raises `TranspilerError` to kill the transpilation process if any invalid calibration entry is found. This pass saves users from waiting until job execution time to get an invalid pulse error from the backend control electronics. Create new pass. **Parameters** * **granularity** – Integer number representing the minimum time resolution to define the pulse gate length in units of `dt`. This value depends on the control electronics of your quantum processor. * **min\_length** – Integer number representing the minimum data point length to define the pulse gate in units of `dt`. This value depends on the control electronics of your quantum processor. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the pulse gate validation attached to `dag`. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – DAG to be validated. **Returns** DAG with consistent timing and op nodes annotated with duration. **Return type** [DAGCircuit](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – When pulse gate violate pulse controller constraints. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.ValidatePulseGates.mdx "--- title: VF2Layout description: API reference for qiskit.transpiler.passes.VF2Layout in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.VF2Layout --- # VF2Layout Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") A pass for choosing a Layout of a circuit onto a Coupling graph, as a subgraph isomorphism problem, solved by VF2++. If a solution is found that means there is a “perfect layout” and that no further swap mapping or routing is needed. If a solution is found the layout will be set in the property set as `property_set['layout']`. However, if no solution is found, no `property_set['layout']` is set. The stopping reason is set in `property_set['VF2Layout_stop_reason']` in all the cases and will be one of the values enumerated in `VF2LayoutStopReason` which has the following values: > * `""solution found""`: If a perfect layout was found. > * `""nonexistent solution""`: If no perfect layout was found. > * `"">2q gates in basis""`: If VF2Layout can’t work with basis By default, this pass will construct a heuristic scoring map based on the error rates in the provided `target` (or `properties` if `target` is not provided). However, analysis passes can be run prior to this pass and set `vf2_avg_error_map` in the property set with a `ErrorMap` instance. If a value is `NaN` that is treated as an ideal edge For example if an error map is created as: ```python from qiskit.transpiler.passes.layout.vf2_utils import ErrorMap error_map = ErrorMap(3) error_map.add_error((0, 0), 0.0024) error_map.add_error((0, 1), 0.01) error_map.add_error((1, 1), 0.0032) ``` that represents the error map for a 2 qubit target, where the avg 1q error rate is `0.0024` on qubit 0 and `0.0032` on qubit 1. Then the avg 2q error rate for gates that operate on (0, 1) is 0.01 and (1, 0) is not supported by the target. This will be used for scoring if it’s set as the `vf2_avg_error_map` key in the property set when [`VF2Layout`](#qiskit.transpiler.passes.VF2Layout ""qiskit.transpiler.passes.VF2Layout"") is run. Initialize a `VF2Layout` pass instance **Parameters** * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")) – Directed graph representing a coupling map. * **strict\_direction** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, considers the direction of the coupling map. Default is False. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Sets the seed of the PRNG. -1 Means no node shuffling. * **call\_limit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of state visits to attempt in each execution of VF2. * **time\_limit** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The total time limit in seconds to run `VF2Layout` * **properties** ([*BackendProperties*](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"")) – The backend properties for the backend. If [`readout_error()`](qiskit.providers.models.BackendProperties#readout_error ""qiskit.providers.models.BackendProperties.readout_error"") is available it is used to score the layout. * **max\_trials** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of trials to run VF2 to find a layout. If this is not specified the number of trials will be limited based on the number of edges in the interaction graph or the coupling graph (whichever is larger) if no other limits are set. If set to a value \<= 0 no limit on the number of trials will be set. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – A target representing the backend device to run `VF2Layout` on. If specified it will supersede a set value for `properties` and `coupling_map`. **Raises** [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – At runtime, if neither `coupling_map` or `target` are provided. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run run the layout method ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.VF2Layout.mdx "--- title: VF2PostLayout description: API reference for qiskit.transpiler.passes.VF2PostLayout in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.VF2PostLayout --- # VF2PostLayout Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") A pass for improving an existing Layout after transpilation of a circuit onto a Coupling graph, as a subgraph isomorphism problem, solved by VF2++. Unlike the [`VF2Layout`](qiskit.transpiler.passes.VF2Layout ""qiskit.transpiler.passes.VF2Layout"") transpiler pass which is designed to find an initial layout for a circuit early in the transpilation pipeline this transpiler pass is designed to try and find a better layout after transpilation is complete. The initial layout phase of the transpiler doesn’t have as much information available as we do after transpilation. This pass is designed to be paired in a similar pipeline as the layout passes. This pass will strip any idle wires from the circuit, use VF2 to find a subgraph in the coupling graph for the circuit to run on with better fidelity and then update the circuit layout to use the new qubits. The algorithm used in this pass is described in [arXiv:2209.15512](https://arxiv.org/abs/2209.15512). If a solution is found that means there is a lower error layout available for the circuit. If a solution is found the layout will be set in the property set as `property_set['post_layout']`. However, if no solution or no better solution is found, no `property_set['post_layout']` is set. The stopping reason is set in `property_set['VF2PostLayout_stop_reason']` in all the cases and will be one of the values enumerated in `VF2PostLayoutStopReason` which has the following values: > * `""solution found""`: If a solution was found. > * `""no better solution found""`: If the initial layout of the circuit is the best solution. > * `""nonexistent solution""`: If no solution was found. > * `"">2q gates in basis""`: If VF2PostLayout can’t work with the basis of the circuit. By default, this pass will construct a heuristic scoring map based on the error rates in the provided `target` (or `properties` if `target` is not provided). However, analysis passes can be run prior to this pass and set `vf2_avg_error_map` in the property set with a `ErrorMap` instance. If a value is `NaN` that is treated as an ideal edge For example if an error map is created as: ```python from qiskit.transpiler.passes.layout.vf2_utils import ErrorMap error_map = ErrorMap(3) error_map.add_error((0, 0), 0.0024) error_map.add_error((0, 1), 0.01) error_map.add_error((1, 1), 0.0032) ``` that represents the error map for a 2 qubit target, where the avg 1q error rate is `0.0024` on qubit 0 and `0.0032` on qubit 1. Then the avg 2q error rate for gates that operate on (0, 1) is 0.01 and (1, 0) is not supported by the target. This will be used for scoring if it’s set as the `vf2_avg_error_map` key in the property set when [`VF2PostLayout`](#qiskit.transpiler.passes.VF2PostLayout ""qiskit.transpiler.passes.VF2PostLayout"") is run. Initialize a `VF2PostLayout` pass instance **Parameters** * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – A target representing the backend device to run `VF2PostLayout` on. If specified it will supersede a set value for `properties` and `coupling_map`. * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")) – Directed graph representing a coupling map. * **properties** ([*BackendProperties*](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"")) – The backend properties for the backend. If [`readout_error()`](qiskit.providers.models.BackendProperties#readout_error ""qiskit.providers.models.BackendProperties.readout_error"") is available it is used to score the layout. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Sets the seed of the PRNG. -1 Means no node shuffling. * **call\_limit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of state visits to attempt in each execution of VF2. * **time\_limit** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The total time limit in seconds to run `VF2PostLayout` * **strict\_direction** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether the pass is configured to follow the strict direction in the coupling graph. If this is set to false, the pass will treat any edge in the coupling graph as a weak edge and the interaction graph will be undirected. For the purposes of evaluating layouts the avg error rate for each qubit and 2q link will be used. This enables the pass to be run prior to basis translation and work with any 1q and 2q operations. However, if `strict_direction=True` the pass expects the input [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") object to [`run()`](#qiskit.transpiler.passes.VF2PostLayout.run ""qiskit.transpiler.passes.VF2PostLayout.run"") to be in the target set of instructions. * **max\_trials** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of trials to run VF2 to find a layout. A value of `0` (the default) means ‘unlimited’. **Raises** [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – At runtime, if neither `coupling_map` or `target` are provided. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run run the layout method ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.VF2PostLayout.mdx "--- title: Width description: API reference for qiskit.transpiler.passes.Width in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.passes.Width --- # Width Bases: [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.basepasses.AnalysisPass"") Calculate the width of a DAG circuit. The result is saved in `property_set['width']` as an integer that contains the number of qubits + the number of clbits. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the Width pass on dag. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.passes.Width.mdx "--- title: PassManager description: API reference for qiskit.transpiler.PassManager in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.PassManager --- # PassManager Bases: [`BasePassManager`](qiskit.passmanager.BasePassManager ""qiskit.passmanager.passmanager.BasePassManager"") Manager for a set of Passes and their scheduling during transpilation. Initialize an empty pass manager object. **Parameters** * **passes** (*Task |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[Task]*) – A pass set to be added to the pass manager schedule. * **max\_iteration** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of iterations the schedule will be looped if the condition is not met. ## Methods ### append Append a Pass Set to the schedule of passes. **Parameters** **passes** (*Task |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[Task]*) – A set of transpiler passes to be added to schedule. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if a pass in passes is not a proper pass. ### draw Draw the pass manager. This function needs [pydot](https://github.com/erocarrera/pydot), which in turn needs [Graphviz](https://www.graphviz.org/) to be installed. **Parameters** * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – file path to save image to. * **style** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – keys are the pass classes and the values are the colors to make them. An example can be seen in the DEFAULT\_STYLE. An ordered dict can be used to ensure a priority coloring when pass falls into multiple categories. Any values not included in the provided dict will be filled in from the default dict. * **raw** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True`, save the raw Dot output instead of the image. **Returns** an in-memory representation of the pass manager, or `None` if no image was generated or [Pillow](https://pypi.org/project/Pillow/) is not installed. **Return type** Optional\[[PassManager](#qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"")] **Raises** [**ImportError**](https://docs.python.org/3/library/exceptions.html#ImportError ""(in Python v3.12)"") – when nxpd or pydot not installed. ### remove Removes a particular pass in the scheduler. **Parameters** **index** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Pass index to remove, based on the position in [`passes()`](transpiler_passes#module-qiskit.transpiler.passes ""qiskit.transpiler.passes""). **Raises** [**PassManagerError**](passmanager#qiskit.passmanager.PassManagerError ""qiskit.passmanager.PassManagerError"") – If the index is not found. ### replace Replace a particular pass in the scheduler. **Parameters** * **index** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Pass index to replace, based on the position in passes(). * **passes** (*Task |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[Task]*) – A pass set to be added to the pass manager schedule. ### run Run all the passes on the specified `circuits`. **Parameters** * **circuits** (*\_CircuitsT*) – Circuit(s) to transform via all the registered passes. * **output\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The output circuit name. If `None`, it will be set to the same as the input circuit name. * **callback** (*Callable*) – A callback function that will be called after each pass execution. The function will be called with 5 keyword arguments: ```python pass_ (Pass): the pass being run dag (DAGCircuit): the dag output of the pass time (float): the time to execute the pass property_set (PropertySet): the property set count (int): the index for the pass execution ``` Beware that the keyword arguments here are different to those used by the generic [`BasePassManager`](qiskit.passmanager.BasePassManager ""qiskit.passmanager.BasePassManager""). This pass manager will translate those arguments into the form described above. The exact arguments pass 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 you 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'] ... ``` * **num\_processes** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of parallel processes to launch 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 transformed circuit(s). **Return type** \_CircuitsT ### to\_flow\_controller Linearize this manager into a single [`FlowControllerLinear`](qiskit.passmanager.FlowControllerLinear ""qiskit.passmanager.FlowControllerLinear""), so that it can be nested inside another pass manager. **Returns** A linearized pass manager. **Return type** [*FlowControllerLinear*](qiskit.passmanager.FlowControllerLinear ""qiskit.passmanager.flow_controllers.FlowControllerLinear"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.PassManager.mdx "--- title: PassManagerConfig description: API reference for qiskit.transpiler.PassManagerConfig in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.PassManagerConfig --- # PassManagerConfig Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Pass Manager Configuration. Initialize a PassManagerConfig object **Parameters** * **initial\_layout** ([*Layout*](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"")) – Initial position of virtual qubits on physical qubits. * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of basis gate names to unroll to. * **inst\_map** ([*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"")) – Mapping object that maps gate to schedule. * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")) – Directed graph represented a coupling map. * **layout\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – the pass to use for choosing initial qubit placement. This will be the plugin name if an external layout stage plugin is being used. * **routing\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – the pass to use for routing qubits on the architecture. This will be a plugin name if an external routing stage plugin is being used. * **translation\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – the pass to use for translating gates to basis\_gates. This will be a plugin name if an external translation stage plugin is being used. * **scheduling\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – the pass to use for scheduling instructions. This will be a plugin name if an external scheduling stage plugin is being used. * **instruction\_durations** ([*InstructionDurations*](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"")) – Dictionary of duration (in dt) for each instruction. * **backend\_properties** ([*BackendProperties*](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"")) – Properties returned by a backend, including information on gate errors, readout errors, qubit coherence times, etc. * **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) * **seed\_transpiler** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Sets random seed for the stochastic parts of the transpiler. * **timing\_constraints** (*TimingConstraints*) – Hardware time alignment restrictions. * **unitary\_synthesis\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The string method to use for the [`UnitarySynthesis`](qiskit.transpiler.passes.UnitarySynthesis ""qiskit.transpiler.passes.UnitarySynthesis"") pass. Will search installed plugins for a valid method. 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""). * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The backend target * **hls\_config** ([*HLSConfig*](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.HLSConfig"")) – An optional configuration class to use for [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.HighLevelSynthesis"") pass. Specifies how to synthesize various high-level objects. * **init\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The plugin name for the init stage plugin to use * **optimization\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The plugin name for the optimization stage plugin to use. ## Methods ### from\_backend Construct a configuration based on a backend and user input. This method automatically gererates a PassManagerConfig object based on the backend’s features. User options can be used to overwrite the configuration. **Parameters** * **backend** ([*BackendV1*](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"")) – The backend that provides the configuration. * **pass\_manager\_options** – User-defined option-value pairs. **Returns** The configuration generated based on the arguments. **Return type** [PassManagerConfig](#qiskit.transpiler.PassManagerConfig ""qiskit.transpiler.PassManagerConfig"") **Raises** [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If the backend does not support a configuration() method. ",repo/docs/api/qiskit/1.0\qiskit.transpiler.PassManagerConfig.mdx "--- title: PassManagerStagePlugin description: API reference for qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePlugin in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePlugin --- # PassManagerStagePlugin Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC ""(in Python v3.12)"") A `PassManagerStagePlugin` is a plugin interface object for using custom stages in [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile""). A `PassManagerStagePlugin` object can be added to an external package and integrated into the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") function with an entry point. This will enable users to use the output of [`pass_manager()`](#qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePlugin.pass_manager ""qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePlugin.pass_manager"") to implement a stage in the compilation process. ## Methods ### pass\_manager This method is designed to return a [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") for the stage this implements **Parameters** * **pass\_manager\_config** ([*PassManagerConfig*](qiskit.transpiler.PassManagerConfig ""qiskit.transpiler.passmanager_config.PassManagerConfig"")) – A configuration object that defines all the target device specifications and any user specified options to [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") or [`generate_preset_pass_manager()`](transpiler_preset#qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager ""qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager"") * **optimization\_level** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The optimization level of the transpilation, if set this should be used to set values for any tunable parameters to trade off runtime for potential optimization. Valid values should be `0`, `1`, `2`, or `3` and the higher the number the more optimization is expected. **Return type** [*PassManager*](qiskit.transpiler.PassManager ""qiskit.transpiler.passmanager.PassManager"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePlugin.mdx "--- title: PassManagerStagePluginManager description: API reference for qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePluginManager in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePluginManager --- # PassManagerStagePluginManager Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Manager class for preset pass manager stage plugins. ## Methods ### get\_passmanager\_stage Get a stage **Return type** [*PassManager*](qiskit.transpiler.PassManager ""qiskit.transpiler.passmanager.PassManager"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePluginManager.mdx "--- title: StagedPassManager description: API reference for qiskit.transpiler.StagedPassManager in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.StagedPassManager --- # StagedPassManager Bases: [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.passmanager.PassManager"") A pass manager pipeline built from individual stages. This class enables building a compilation pipeline out of fixed stages. Each `StagedPassManager` defines a list of stages which are executed in a fixed order, and each stage is defined as a standalone [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") instance. There are also `pre_` and `post_` stages for each defined stage. This enables easily composing and replacing different stages and also adding hook points to enable programmatic modifications to a pipeline. When using a staged pass manager you are not able to modify the individual passes and are only able to modify stages. By default, instances of `StagedPassManager` define a typical full compilation pipeline from an abstract virtual circuit to one that is optimized and capable of running on the specified backend. The default pre-defined stages are: 1. `init` - Initial passes to run before embedding the circuit to the backend. 2. `layout` - Maps the virtual qubits in the circuit to the physical qubits on the backend. 3. `routing` - Inserts gates as needed to move the qubit states around until the circuit can be run with the chosen layout on the backend’s coupling map. 4. `translation` - Translates the gates in the circuit to the target backend’s basis gate set. 5. `optimization` - Optimizes the circuit to reduce the cost of executing it. These passes will typically run in a loop until a convergence criteria is met. For example, the convergence criteria might be that the circuit depth does not decrease in successive iterations. 6. `scheduling` - Hardware-aware passes that schedule the operations in the circuit. For backwards compatibility the relative positioning of these default stages will remain stable moving forward. However, new stages may be added to the default stage list in between current stages. For example, in a future release a new phase, something like `logical_optimization`, could be added immediately after the existing `init` stage in the default stage list. This would preserve compatibility for pre-existing `StagedPassManager` users as the relative positions of the stage are preserved so the behavior will not change between releases. These stages will be executed in order and any stage set to `None` will be skipped. If a stage is provided multiple times (i.e. at diferent relative positions), the associated passes, including pre and post, will run once per declaration. If a [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") input is being used for more than 1 stage here (for example in the case of a `Pass` that covers both Layout and Routing) you will want to set that to the earliest stage in sequence that it covers. Initialize a new StagedPassManager object **Parameters** * **stages** (*Iterable\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – An optional list of stages to use for this instance. If this is not specified the default stages list `['init', 'layout', 'routing', 'translation', 'optimization', 'scheduling']` is used. After instantiation, the final list will be immutable and stored as tuple. If a stage is provided multiple times (i.e. at diferent relative positions), the associated passes, including pre and post, will run once per declaration. * **kwargs** – The initial [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") values for any stages defined in `stages`. If a argument is not defined the stages will default to `None` indicating an empty/undefined stage. **Raises** * [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If a stage in the input keyword arguments is not defined. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If an invalid stage name is specified. ## Attributes ### expanded\_stages Expanded Pass manager stages including `pre_` and `post_` phases. ### invalid\_stage\_regex |\\@|\\!|\\~|\\^|\\&|\\:|\\[|\\]|\\{|\\}|\\(|\\)')"" /> ### stages Pass manager stages ## Methods ### append Append a Pass Set to the schedule of passes. **Parameters** **passes** (*Task |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[Task]*) – A set of transpiler passes to be added to schedule. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if a pass in passes is not a proper pass. ### draw Draw the staged pass manager. ### remove Removes a particular pass in the scheduler. **Parameters** **index** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Pass index to remove, based on the position in [`passes()`](transpiler_passes#module-qiskit.transpiler.passes ""qiskit.transpiler.passes""). **Raises** [**PassManagerError**](passmanager#qiskit.passmanager.PassManagerError ""qiskit.passmanager.PassManagerError"") – If the index is not found. ### replace Replace a particular pass in the scheduler. **Parameters** * **index** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Pass index to replace, based on the position in passes(). * **passes** (*BasePass |* [*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[BasePass]*) – A pass set to be added to the pass manager schedule. ### run Run all the passes on the specified `circuits`. **Parameters** * **circuits** (*\_CircuitsT*) – Circuit(s) to transform via all the registered passes. * **output\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The output circuit name. If `None`, it will be set to the same as the input circuit name. * **callback** (*Callable | None*) – A callback function that will be called after each pass execution. The function will be called with 5 keyword arguments: ```python pass_ (Pass): the pass being run dag (DAGCircuit): the dag output of the pass time (float): the time to execute the pass property_set (PropertySet): the property set count (int): the index for the pass execution ``` Beware that the keyword arguments here are different to those used by the generic [`BasePassManager`](qiskit.passmanager.BasePassManager ""qiskit.passmanager.BasePassManager""). This pass manager will translate those arguments into the form described above. The exact arguments pass 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 you 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'] ... ``` * **num\_processes** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of parallel processes to launch 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 transformed circuit(s). **Return type** \_CircuitsT ### to\_flow\_controller Linearize this manager into a single [`FlowControllerLinear`](qiskit.passmanager.FlowControllerLinear ""qiskit.passmanager.FlowControllerLinear""), so that it can be nested inside another pass manager. **Returns** A linearized pass manager. **Return type** [*FlowControllerLinear*](qiskit.passmanager.FlowControllerLinear ""qiskit.passmanager.flow_controllers.FlowControllerLinear"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.StagedPassManager.mdx "--- title: Target description: API reference for qiskit.transpiler.Target in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.Target --- # Target Bases: [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping ""(in Python v3.12)"") The intent of the `Target` object is to inform Qiskit’s compiler about the constraints of a particular backend so the compiler can compile an input circuit to something that works and is optimized for a device. It currently contains a description of instructions on a backend and their properties as well as some timing information. However, this exact interface may evolve over time as the needs of the compiler change. These changes will be done in a backwards compatible and controlled manner when they are made (either through versioning, subclassing, or mixins) to add on to the set of information exposed by a target. As a basic example, let’s assume backend has two qubits, supports [`UGate`](qiskit.circuit.library.UGate ""qiskit.circuit.library.UGate"") on both qubits and [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"") in both directions. To model this you would create the target like: ```python from qiskit.transpiler import Target, InstructionProperties from qiskit.circuit.library import UGate, CXGate from qiskit.circuit import Parameter gmap = Target() theta = Parameter('theta') phi = Parameter('phi') lam = Parameter('lambda') u_props = { (0,): InstructionProperties(duration=5.23e-8, error=0.00038115), (1,): InstructionProperties(duration=4.52e-8, error=0.00032115), } gmap.add_instruction(UGate(theta, phi, lam), u_props) cx_props = { (0,1): InstructionProperties(duration=5.23e-7, error=0.00098115), (1,0): InstructionProperties(duration=4.52e-7, error=0.00132115), } gmap.add_instruction(CXGate(), cx_props) ``` Each instruction in the `Target` is indexed by a unique string name that uniquely identifies that instance of an [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") object in the Target. There is a 1:1 mapping between a name and an [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") instance in the target and each name must be unique. By default, the name is the [`name`](qiskit.circuit.Instruction#name ""qiskit.circuit.Instruction.name"") attribute of the instruction, but can be set to anything. This lets a single target have multiple instances of the same instruction class with different parameters. For example, if a backend target has two instances of an [`RXGate`](qiskit.circuit.library.RXGate ""qiskit.circuit.library.RXGate"") one is parameterized over any theta while the other is tuned up for a theta of pi/6 you can add these by doing something like: ```python import math from qiskit.transpiler import Target, InstructionProperties from qiskit.circuit.library import RXGate from qiskit.circuit import Parameter target = Target() theta = Parameter('theta') rx_props = { (0,): InstructionProperties(duration=5.23e-8, error=0.00038115), } target.add_instruction(RXGate(theta), rx_props) rx_30_props = { (0,): InstructionProperties(duration=1.74e-6, error=.00012) } target.add_instruction(RXGate(math.pi / 6), rx_30_props, name='rx_30') ``` Then in the `target` object accessing by `rx_30` will get the fixed angle [`RXGate`](qiskit.circuit.library.RXGate ""qiskit.circuit.library.RXGate"") while `rx` will get the parameterized [`RXGate`](qiskit.circuit.library.RXGate ""qiskit.circuit.library.RXGate""). This class assumes that qubit indices start at 0 and are a contiguous set if you want a submapping the bits will need to be reindexed in a new\`\`Target\`\` object. This class only supports additions of gates, qargs, and qubits. If you need to remove one of these the best option is to iterate over an existing object and create a new subset (or use one of the methods to do this). The object internally caches different views and these would potentially be invalidated by removals. Create a new `Target` object **Parameters** * **description** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – An optional string to describe the Target. * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – An optional int to specify the number of qubits the backend target has. If not set it will be implicitly set based on the qargs when `add_instruction()` is called. Note this must be set if the backend target is for a noiseless simulator that doesn’t have constraints on the instructions so the transpiler knows how many qubits are available. * **dt** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The system time resolution of input signals in seconds * **granularity** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – 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** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – 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** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – 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** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – 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. * **qubit\_properties** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of [`QubitProperties`](qiskit.providers.QubitProperties ""qiskit.providers.QubitProperties"") objects defining the characteristics of each qubit on the target device. If specified the length of this list must match the number of qubits in the target, where the index in the list matches the qubit number the properties are defined for. If some qubits don’t have properties available you can set that entry to `None` * **concurrent\_measurements** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of sets of qubits that must be measured together. This must be provided as a nested list like `[[0, 1], [2, 3, 4]]`. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If both `num_qubits` and `qubit_properties` are both defined and the value of `num_qubits` differs from the length of `qubit_properties`. ## Attributes ### num\_qubits ### description ### dt ### granularity ### min\_length ### pulse\_alignment ### acquire\_alignment ### qubit\_properties ### concurrent\_measurements ### instructions Get the list of tuples ``(:class:`~qiskit.circuit.Instruction`, (qargs))`` for the target For globally defined variable width operations the tuple will be of the form `(class, None)` where class is the actual operation class that is globally defined. ### operation\_names Get the operation names in the target. ### operations Get the operation class objects in the target. ### physical\_qubits Returns a sorted list of physical\_qubits ### qargs The set of qargs in the target. ## Methods ### add\_instruction Add a new instruction to the [`Target`](#qiskit.transpiler.Target ""qiskit.transpiler.Target"") As `Target` objects are strictly additive this is the primary method for modifying a `Target`. Typically, you will use this to fully populate a `Target` before using it in [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2""). For example: ```python from qiskit.circuit.library import CXGate from qiskit.transpiler import Target, InstructionProperties target = Target() cx_properties = { (0, 1): None, (1, 0): None, (0, 2): None, (2, 0): None, (0, 3): None, (2, 3): None, (3, 0): None, (3, 2): None } target.add_instruction(CXGate(), cx_properties) ``` Will add a [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"") to the target with no properties (duration, error, etc) with the coupling edge list: `(0, 1), (1, 0), (0, 2), (2, 0), (0, 3), (2, 3), (3, 0), (3, 2)`. If there are properties available for the instruction you can replace the `None` value in the properties dictionary with an [`InstructionProperties`](qiskit.transpiler.InstructionProperties ""qiskit.transpiler.InstructionProperties"") object. This pattern is repeated for each [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") the target supports. **Parameters** * **instruction** (*Union\[*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")*,* [*Type*](circuit_classical#qiskit.circuit.classical.types.Type ""qiskit.circuit.classical.types.Type"")*\[*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")*]]*) – The operation object to add to the map. If it’s parameterized any value of the parameter can be set. Optionally for variable width instructions (such as control flow operations such as `ForLoop` or `MCXGate`) you can specify the class. If the class is specified than the `name` argument must be specified. When a class is used the gate is treated as global and not having any properties set. * **properties** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary of qarg entries to an [`InstructionProperties`](qiskit.transpiler.InstructionProperties ""qiskit.transpiler.InstructionProperties"") object for that instruction implementation on the backend. Properties are optional for any instruction implementation, if there are no [`InstructionProperties`](qiskit.transpiler.InstructionProperties ""qiskit.transpiler.InstructionProperties"") available for the backend the value can be None. If there are no constraints on the instruction (as in a noiseless/ideal simulation) this can be set to `{None, None}` which will indicate it runs on all qubits (or all available permutations of qubits for multi-qubit gates). The first `None` indicates it applies to all qubits and the second `None` indicates there are no [`InstructionProperties`](qiskit.transpiler.InstructionProperties ""qiskit.transpiler.InstructionProperties"") for the instruction. By default, if properties is not set it is equivalent to passing `{None: None}`. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – An optional name to use for identifying the instruction. If not specified the [`name`](qiskit.circuit.Instruction#name ""qiskit.circuit.Instruction.name"") attribute of `gate` will be used. All gates in the `Target` need unique names. Backends can differentiate between different parameterization of a single gate by providing a unique name for each (e.g. “rx30”, “rx60”, \`”rx90”\`\` similar to the example in the documentation for the [`Target`](#qiskit.transpiler.Target ""qiskit.transpiler.Target"") class). **Raises** * [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError ""(in Python v3.12)"") – If gate is already in map * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If an operation class is passed in for `instruction` and no name is specified or `properties` is set. ### build\_coupling\_map Get a [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") from this target. If there is a mix of two qubit operations that have a connectivity constraint and those that are globally defined this will also return `None` because the globally connectivity means there is no constraint on the target. If you wish to see the constraints of the two qubit operations that have constraints you should use the `two_q_gate` argument to limit the output to the gates which have a constraint. **Parameters** * **two\_q\_gate** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – An optional gate name for a two qubit gate in the `Target` to generate the coupling map for. If specified the output coupling map will only have edges between qubits where this gate is present. * **filter\_idle\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to `True` the output [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") will remove any qubits that don’t have any operations defined in the target. Note that using this argument will result in an output [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") object which has holes in its indices which might differ from the assumptions of the class. The typical use case of this argument is to be paired with [`CouplingMap.connected_components()`](qiskit.transpiler.CouplingMap#connected_components ""qiskit.transpiler.CouplingMap.connected_components"") which will handle the holes as expected. **Returns** **The [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") object** for this target. If there are no connectivity constraints in the target this will return `None`. **Return type** [CouplingMap](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") **Raises** * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If a non-two qubit gate is passed in for `two_q_gate`. * [**IndexError**](https://docs.python.org/3/library/exceptions.html#IndexError ""(in Python v3.12)"") – If an Instruction not in the `Target` is passed in for `two_q_gate`. ### durations Get an InstructionDurations object from the target **Returns** **The instruction duration represented in the** target **Return type** [InstructionDurations](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"") ### from\_configuration Create a target object from the individual global configuration Prior to the creation of the [`Target`](#qiskit.transpiler.Target ""qiskit.transpiler.Target"") class, the constraints of a backend were represented by a collection of different objects which combined represent a subset of the information contained in the [`Target`](#qiskit.transpiler.Target ""qiskit.transpiler.Target""). This function provides a simple interface to convert those separate objects to a [`Target`](#qiskit.transpiler.Target ""qiskit.transpiler.Target""). This constructor will use the input from `basis_gates`, `num_qubits`, and `coupling_map` to build a base model of the backend and the `instruction_durations`, `backend_properties`, and `inst_map` inputs are then queried (in that order) based on that model to look up the properties of each instruction and qubit. If there is an inconsistency between the inputs any extra or conflicting information present in `instruction_durations`, `backend_properties`, or `inst_map` will be ignored. **Parameters** * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – The list of basis gate names for the backend. For the target to be created these names must either be in the output from `get_standard_gate_name_mapping()` or present in the specified `custom_name_mapping` argument. * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – The number of qubits supported on the backend. * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") *| None*) – The coupling map representing connectivity constraints on the backend. If specified all gates from `basis_gates` will be supported on all qubits (or pairs of qubits). * **inst\_map** ([*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"") *| None*) – The instruction schedule map representing the pulse [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") definitions for each instruction. If this is specified `coupling_map` must be specified. The `coupling_map` is used as the source of truth for connectivity and if `inst_map` is used the schedule is looked up based on the instructions from the pair of `basis_gates` and `coupling_map`. If you want to define a custom gate for a particular qubit or qubit pair, you can manually build [`Target`](#qiskit.transpiler.Target ""qiskit.transpiler.Target""). * **backend\_properties** ([*BackendProperties*](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"") *| None*) – The [`BackendProperties`](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"") object which is used for instruction properties and qubit properties. If specified and instruction properties are intended to be used then the `coupling_map` argument must be specified. This is only used to lookup error rates and durations (unless `instruction_durations` is specified which would take precedence) for instructions specified via `coupling_map` and `basis_gates`. * **instruction\_durations** ([*InstructionDurations*](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"") *| None*) – Optional instruction durations for instructions. If specified it will take priority for setting the `duration` field in the [`InstructionProperties`](qiskit.transpiler.InstructionProperties ""qiskit.transpiler.InstructionProperties"") objects for the instructions in the target. * **concurrent\_measurements** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of sets of qubits that must be measured together. This must be provided as a nested list like `[[0, 1], [2, 3, 4]]`. * **dt** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – The system time resolution of input signals in seconds * **timing\_constraints** (*TimingConstraints | None*) – Optional timing constraints to include in the [`Target`](#qiskit.transpiler.Target ""qiskit.transpiler.Target"") * **custom\_name\_mapping** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, Any] | None*) – An optional dictionary that maps custom gate/operation names in `basis_gates` to an [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation"") object representing that gate/operation. By default, most standard gates names are mapped to the standard gate object from [`qiskit.circuit.library`](circuit_library#module-qiskit.circuit.library ""qiskit.circuit.library"") this only needs to be specified if the input `basis_gates` defines gates in names outside that set. **Returns** the target built from the input configuration **Return type** [Target](#qiskit.transpiler.Target ""qiskit.transpiler.Target"") **Raises** * [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If the input basis gates contain > 2 qubits and `coupling_map` is * **specified.** – * [**KeyError**](https://docs.python.org/3/library/exceptions.html#KeyError ""(in Python v3.12)"") – If no mapping is available for a specified `basis_gate`. ### get ### get\_calibration Get calibrated pulse schedule for the instruction. If calibration is templated with parameters, one can also provide those values to build a schedule with assigned parameters. **Parameters** * **operation\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the operation for the instruction. * **qargs** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, ...]*) – The tuple of qubit indices for the instruction. * **args** (*ParameterValueType*) – Parameter values to build schedule if any. * **kwargs** (*ParameterValueType*) – Parameter values with name to build schedule if any. **Returns** Calibrated pulse schedule of corresponding instruction. **Return type** [Schedule](qiskit.pulse.Schedule ""qiskit.pulse.Schedule"") | [ScheduleBlock](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") ### get\_non\_global\_operation\_names Return the non-global operation names for the target The non-global operations are those in the target which don’t apply on all qubits (for single qubit operations) or all multi-qubit qargs (for multi-qubit operations). **Parameters** **strict\_direction** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to `True` the multi-qubit operations considered as non-global respect the strict direction (or order of qubits in the qargs is significant). For example, if `cx` is defined on `(0, 1)` and `ecr` is defined over `(1, 0)` by default neither would be considered non-global, but if `strict_direction` is set `True` both `cx` and `ecr` would be returned. **Returns** A list of operation names for operations that aren’t global in this target **Return type** List\[[str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")] ### has\_calibration Return whether the instruction (operation + qubits) defines a calibration. **Parameters** * **operation\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the operation for the instruction. * **qargs** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, ...]*) – The tuple of qubit indices for the instruction. **Returns** Returns `True` if the calibration is supported and `False` if it isn’t. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### instruction\_properties Get the instruction properties for a specific instruction tuple This method is to be used in conjunction with the [`instructions`](#qiskit.transpiler.Target.instructions ""qiskit.transpiler.Target.instructions"") attribute of a [`Target`](#qiskit.transpiler.Target ""qiskit.transpiler.Target"") object. You can use this method to quickly get the instruction properties for an element of [`instructions`](#qiskit.transpiler.Target.instructions ""qiskit.transpiler.Target.instructions"") by using the index in that list. However, if you’re not working with [`instructions`](#qiskit.transpiler.Target.instructions ""qiskit.transpiler.Target.instructions"") directly it is likely more efficient to access the target directly via the name and qubits to get the instruction properties. For example, if [`instructions`](#qiskit.transpiler.Target.instructions ""qiskit.transpiler.Target.instructions"") returned: ```python [(XGate(), (0,)), (XGate(), (1,))] ``` you could get the properties of the `XGate` on qubit 1 with: ```python props = target.instruction_properties(1) ``` but just accessing it directly via the name would be more efficient: ```python props = target['x'][(1,)] ``` (assuming the `XGate`’s canonical name in the target is `'x'`) This is especially true for larger targets as this will scale worse with the number of instruction tuples in a target. **Parameters** **index** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The index of the instruction tuple from the [`instructions`](#qiskit.transpiler.Target.instructions ""qiskit.transpiler.Target.instructions"") attribute. For, example if you want the properties from the third element in [`instructions`](#qiskit.transpiler.Target.instructions ""qiskit.transpiler.Target.instructions"") you would set this to be `2`. **Returns** The instruction properties for the specified instruction tuple **Return type** [InstructionProperties](qiskit.transpiler.InstructionProperties ""qiskit.transpiler.InstructionProperties"") ### instruction\_schedule\_map Return an [`InstructionScheduleMap`](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"") for the instructions in the target with a pulse schedule defined. **Returns** The instruction schedule map for the instructions in this target with a pulse schedule defined. **Return type** [InstructionScheduleMap](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"") ### instruction\_supported Return whether the instruction (operation + qubits) is supported by the target **Parameters** * **operation\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the operation for the instruction. Either this or `operation_class` must be specified, if both are specified `operation_class` will take priority and this argument will be ignored. * **qargs** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – The tuple of qubit indices for the instruction. If this is not specified then this method will return `True` if the specified operation is supported on any qubits. The typical application will always have this set (otherwise it’s the same as just checking if the target contains the operation). Normally you would not set this argument if you wanted to check more generally that the target supports an operation with the `parameters` on any qubits. * **operation\_class** ([*Type*](circuit_classical#qiskit.circuit.classical.types.Type ""qiskit.circuit.classical.types.Type"")*\[*[*qiskit.circuit.Instruction*](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"")*]*) – The operation class to check whether the target supports a particular operation by class rather than by name. This lookup is more expensive as it needs to iterate over all operations in the target instead of just a single lookup. If this is specified it will supersede the `operation_name` argument. The typical use case for this operation is to check whether a specific variant of an operation is supported on the backend. For example, if you wanted to check whether a [`RXGate`](qiskit.circuit.library.RXGate ""qiskit.circuit.library.RXGate"") was supported on a specific qubit with a fixed angle. That fixed angle variant will typically have a name different from the object’s [`name`](qiskit.circuit.Instruction#name ""qiskit.circuit.Instruction.name"") attribute (`""rx""`) in the target. This can be used to check if any instances of the class are available in such a case. * **parameters** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of parameters to check if the target supports them on the specified qubits. If the instruction supports the parameter values specified in the list on the operation and qargs specified this will return `True` but if the parameters are not supported on the specified instruction it will return `False`. If this argument is not specified this method will return `True` if the instruction is supported independent of the instruction parameters. If specified with any [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") objects in the list, that entry will be treated as supporting any value, however parameter names will not be checked (for example if an operation in the target is listed as parameterized with `""theta""` and `""phi""` is passed into this function that will return `True`). For example, if called with: ```python parameters = [Parameter(""theta"")] target.instruction_supported(""rx"", (0,), parameters=parameters) ``` will return `True` if an [`RXGate`](qiskit.circuit.library.RXGate ""qiskit.circuit.library.RXGate"") is supported on qubit 0 that will accept any parameter. If you need to check for a fixed numeric value parameter this argument is typically paired with the `operation_class` argument. For example: ```python target.instruction_supported(""rx"", (0,), RXGate, parameters=[pi / 4]) ``` will return `True` if an RXGate(pi/4) exists on qubit 0. **Returns** Returns `True` if the instruction is supported and `False` if it isn’t. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ### items ### keys ### operation\_from\_name Get the operation class object for a given name **Parameters** **instruction** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The instruction name to get the [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") instance for **Returns** The Instruction instance corresponding to the name. This also can also be the class for globally defined variable with operations. **Return type** [qiskit.circuit.Instruction](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") ### operation\_names\_for\_qargs Get the operation names for a specified qargs tuple **Parameters** **qargs** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – A `qargs` tuple of the qubits to get the gates that apply to it. For example, `(0,)` will return the set of all instructions that apply to qubit 0. If set to `None` this will return the names for any globally defined operations in the target. **Returns** The set of operation names that apply to the specified `qargs`. **Return type** [set](https://docs.python.org/3/library/stdtypes.html#set ""(in Python v3.12)"") **Raises** [**KeyError**](https://docs.python.org/3/library/exceptions.html#KeyError ""(in Python v3.12)"") – If `qargs` is not in target ### operations\_for\_qargs Get the operation class object for a specified qargs tuple **Parameters** **qargs** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – A qargs tuple of the qubits to get the gates that apply to it. For example, `(0,)` will return the set of all instructions that apply to qubit 0. If set to `None` this will return any globally defined operations in the target. **Returns** The list of [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") instances that apply to the specified qarg. This may also be a class if a variable width operation is globally defined. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") **Raises** [**KeyError**](https://docs.python.org/3/library/exceptions.html#KeyError ""(in Python v3.12)"") – If qargs is not in target ### qargs\_for\_operation\_name Get the qargs for a given operation name **Parameters** **operation** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The operation name to get qargs for **Returns** The set of qargs the gate instance applies to. **Return type** [set](https://docs.python.org/3/library/stdtypes.html#set ""(in Python v3.12)"") ### timing\_constraints Get an `TimingConstraints` object from the target **Returns** The timing constraints represented in the `Target` **Return type** TimingConstraints ### update\_from\_instruction\_schedule\_map Update the target from an instruction schedule map. If the input instruction schedule map contains new instructions not in the target they will be added. However, if it contains additional qargs for an existing instruction in the target it will error. **Parameters** * **inst\_map** ([*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"")) – The instruction * **inst\_name\_map** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – An optional dictionary that maps any instruction name in `inst_map` to an instruction object. If not provided, instruction is pulled from the standard Qiskit gates, and finally custom gate instance is created with schedule name. * **error\_dict** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – A dictionary of errors of the form: ```python {gate_name: {qarg: error}} ``` * **example::** (*for*) – \{‘rx’: \{(0, ): 1.4e-4, (1, ): 1.2e-4}} * **defined** (*For each entry in the inst\_map if error\_dict is*) – * **from** (*a when updating the Target the error value will be pulled*) – * **then** (*this dictionary. If one is not found in error\_dict*) – * **used.** (*None will be*) – ### update\_instruction\_properties Update the property object for an instruction qarg pair already in the Target **Parameters** * **instruction** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The instruction name to update * **qargs** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – The qargs to update the properties of * **properties** ([*InstructionProperties*](qiskit.transpiler.InstructionProperties ""qiskit.transpiler.InstructionProperties"")) – The properties to set for this instruction **Raises** [**KeyError**](https://docs.python.org/3/library/exceptions.html#KeyError ""(in Python v3.12)"") – If `instruction` or `qarg` are not in the target ### values ",repo/docs/api/qiskit/1.0\qiskit.transpiler.Target.mdx "--- title: TransformationPass description: API reference for qiskit.transpiler.TransformationPass in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.TransformationPass --- # TransformationPass Bases: `BasePass` A transformation pass: change DAG, not property set. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [qiskit.passmanager.compilation\_status.PassManagerState](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run a pass on the DAGCircuit. This is implemented by the pass developer. **Parameters** **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.dagcircuit.DAGCircuit"")) – the dag on which the pass is run. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – when this is left unimplemented for a pass. ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](qiskit.passmanager.PassManagerState ""qiskit.passmanager.compilation_status.PassManagerState"") ",repo/docs/api/qiskit/1.0\qiskit.transpiler.TransformationPass.mdx "--- title: TranspileLayout description: API reference for qiskit.transpiler.TranspileLayout in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit.transpiler.TranspileLayout --- # TranspileLayout Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Layout attributes from output circuit from transpiler. The transpiler in general is unitary-perserving up to permutations caused by setting and applying initial layout during the [Layout Stage](transpiler#layout-stage) and [`SwapGate`](qiskit.circuit.library.SwapGate ""qiskit.circuit.library.SwapGate"") insertion during the [Routing Stage](transpiler#routing-stage). To provide an interface to reason about these permutations caused by the [`transpiler`](transpiler#module-qiskit.transpiler ""qiskit.transpiler""). In general the normal interface to access and reason about the layout transformations made by the transpiler is to use the helper methods defined on this class. For example, looking at the initial layout, the transpiler can potentially remap the order of the qubits in your circuit as it fits the circuit to the target backend. If the input circuit was: Then during the layout stage the transpiler reorders the qubits to be: then the output of the [`initial_virtual_layout()`](#qiskit.transpiler.TranspileLayout.initial_virtual_layout ""qiskit.transpiler.TranspileLayout.initial_virtual_layout"") would be equivalent to: ```python Layout({ qr[0]: 2, qr[1]: 1, qr[2]: 0, }) ``` (it is also this attribute in the [`QuantumCircuit.draw()`](qiskit.circuit.QuantumCircuit#draw ""qiskit.circuit.QuantumCircuit.draw"") and [`circuit_drawer()`](qiskit.visualization.circuit_drawer ""qiskit.visualization.circuit_drawer"") which is used to display the mapping of qubits to positions in circuit visualizations post-transpilation) Building on this above example for final layout, if the transpiler needed to insert swap gates during routing so the output circuit became: then the output of the [`routing_permutation()`](#qiskit.transpiler.TranspileLayout.routing_permutation ""qiskit.transpiler.TranspileLayout.routing_permutation"") method would be: ```python [1, 0, 2] ``` which maps the qubits at each position to their final position after any swap insertions caused by routing. There are three public attributes associated with the class, however these are mostly provided for backwards compatibility and represent the internal state from the transpiler. They are defined as: > * [`initial_layout`](#qiskit.transpiler.TranspileLayout.initial_layout ""qiskit.transpiler.TranspileLayout.initial_layout"") - This attribute is used to model the permutation caused by the [Layout Stage](transpiler#layout-stage) it contains a [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") object that maps the input [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")s [`Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"") objects to the position in the output `QuantumCircuit.qubits` list. > * [`input_qubit_mapping`](#qiskit.transpiler.TranspileLayout.input_qubit_mapping ""qiskit.transpiler.TranspileLayout.input_qubit_mapping"") - This attribute is used to retain input ordering of the original [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") object. It maps the virtual [`Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"") object from the original circuit (and [`initial_layout`](#qiskit.transpiler.TranspileLayout.initial_layout ""qiskit.transpiler.TranspileLayout.initial_layout"")) to its corresponding position in [`QuantumCircuit.qubits`](qiskit.circuit.QuantumCircuit#qubits ""qiskit.circuit.QuantumCircuit.qubits"") in the original circuit. This is needed when computing the permutation of the `Operator` of the circuit (and used by [`Operator.from_circuit()`](qiskit.quantum_info.Operator#from_circuit ""qiskit.quantum_info.Operator.from_circuit"")). > * [`final_layout`](#qiskit.transpiler.TranspileLayout.final_layout ""qiskit.transpiler.TranspileLayout.final_layout"") - This is a [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") object used to model the output permutation caused ny any [`SwapGate`](qiskit.circuit.library.SwapGate ""qiskit.circuit.library.SwapGate"")s inserted into the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") during the [Routing Stage](transpiler#routing-stage). It maps the output circuit’s qubits from `QuantumCircuit.qubits` in the output circuit to the final position after routing. It is **not** a mapping from the original input circuit’s position to the final position at the end of the transpiled circuit. If you need this you can use the [`final_index_layout()`](#qiskit.transpiler.TranspileLayout.final_index_layout ""qiskit.transpiler.TranspileLayout.final_index_layout"") to generate this. If this is set to `None` this indicates that routing was not run and it can be considered equivalent to a trivial layout with the qubits from the output circuit’s [`qubits`](qiskit.circuit.QuantumCircuit#qubits ""qiskit.circuit.QuantumCircuit.qubits"") list. ## Attributes ### final\_layout ### initial\_layout ### input\_qubit\_mapping ## Methods ### final\_index\_layout Generate the final layout as an array of integers This method will generate an array of final positions for each qubit in the output circuit. For example, if you had an input circuit like: ```python qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) ``` and the output from the transpiler was: ```python tqc = QuantumCircuit(3) qc.h(2) qc.cx(2, 1) qc.swap(0, 1) qc.cx(2, 1) ``` then the return from this function would be a list of: ```python [2, 0, 1] ``` because qubit 0 in the original circuit’s final state is on qubit 3 in the output circuit, qubit 1 in the original circuit’s final state is on qubit 0, and qubit 2’s final state is on qubit. The output list length will be as wide as the input circuit’s number of qubits, as the output list from this method is for tracking the permutation of qubits in the original circuit caused by the transpiler. **Parameters** **filter\_ancillas** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to `False` any ancillas allocated in the output circuit will be included in the layout. **Returns** A list of final positions for each input circuit qubit **Return type** [*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)"")] ### final\_virtual\_layout Generate the final layout as a [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") object This method will generate an array of final positions for each qubit in the output circuit. For example, if you had an input circuit like: ```python qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) ``` and the output from the transpiler was: ```python tqc = QuantumCircuit(3) qc.h(2) qc.cx(2, 1) qc.swap(0, 1) qc.cx(2, 1) ``` then the return from this function would be a layout object: ```python Layout({ qc.qubits[0]: 2, qc.qubits[1]: 0, qc.qubits[2]: 1, }) ``` because qubit 0 in the original circuit’s final state is on qubit 3 in the output circuit, qubit 1 in the original circuit’s final state is on qubit 0, and qubit 2’s final state is on qubit. The output list length will be as wide as the input circuit’s number of qubits, as the output list from this method is for tracking the permutation of qubits in the original circuit caused by the transpiler. **Parameters** **filter\_ancillas** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to `False` any ancillas allocated in the output circuit will be included in the layout. **Returns** A layout object mapping to the final positions for each qubit **Return type** [*Layout*](qiskit.transpiler.Layout ""qiskit.transpiler.layout.Layout"") ### initial\_index\_layout Generate an initial layout as an array of integers **Parameters** **filter\_ancillas** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to `True` any ancilla qubits added to the transpiler will not be included in the output. **Returns** A layout array that maps a position in the array to its new position in the output circuit. **Return type** [*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)"")] ### initial\_virtual\_layout Return a [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") object for the initial layout. This returns a mapping of virtual [`Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"") objects in the input circuit to the physical qubit selected during layout. This is analogous to the [`initial_layout`](#qiskit.transpiler.TranspileLayout.initial_layout ""qiskit.transpiler.TranspileLayout.initial_layout"") attribute. **Parameters** **filter\_ancillas** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to `True` only qubits in the input circuit will be in the returned layout. Any ancilla qubits added to the output circuit will be filtered from the returned object. **Returns** A layout object mapping the input circuit’s [`Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"") objects to the selected physical qubits. **Return type** [*Layout*](qiskit.transpiler.Layout ""qiskit.transpiler.layout.Layout"") ### routing\_permutation Generate a final layout as an array of integers If there is no [`final_layout`](#qiskit.transpiler.TranspileLayout.final_layout ""qiskit.transpiler.TranspileLayout.final_layout"") attribute present then that indicates there was no output permutation caused by routing or other transpiler transforms. In this case the function will return a list of `[0, 1, 2, .., n]` to indicate this **Returns** A layout array that maps a position in the array to its new position in the output circuit **Return type** [*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)"")] ",repo/docs/api/qiskit/1.0\qiskit.transpiler.TranspileLayout.mdx "--- title: array_to_latex description: API reference for qiskit.visualization.array_to_latex in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.array_to_latex --- # qiskit.visualization.array\_to\_latex Latex representation of a complex numpy array (with dimension 1 or 2) **Parameters** * **array** (*ndarray*) – The array to be converted to latex, must have dimension 1 or 2 and contain only numerical data. * **precision** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – For numbers not close to integers or common terms, the number of decimal places to round to. * **prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Latex string to be prepended to the latex, intended for labels. * **source** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `False`, will return IPython.display.Latex object. If display is `True`, will instead return the LaTeX source string. * **max\_size** ([*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)"")*) or* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum size of the output Latex array. * If list(`int`), then the 0th element of the list specifies the maximum width (including dots characters) and the 1st specifies the maximum height (also inc. dots characters). * If a single `int` then this value sets the maximum width \_and\_ maximum height. **Returns** **If `source` is `True`, a `str` of the LaTeX** representation of the array, else an `IPython.display.Latex` representation of the array. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") or IPython.display.Latex **Raises** * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – If array can not be interpreted as a numerical numpy array. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the dimension of array is not 1 or 2. * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – If `source` is `False` and `IPython.display.Latex` cannot be imported. ",repo/docs/api/qiskit/1.0\qiskit.visualization.array_to_latex.mdx "--- title: circuit_drawer description: API reference for qiskit.visualization.circuit_drawer in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.circuit_drawer --- # qiskit.visualization.circuit\_drawer Draw the quantum circuit. Use the output parameter to choose the drawing format: **text**: ASCII art TextDrawing that can be printed in the console. **mpl**: images with color rendered purely in Python using matplotlib. **latex**: high-quality images compiled via latex. **latex\_source**: raw uncompiled latex output. Support for [`Expr`](circuit_classical#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.Expr"") nodes in conditions and `SwitchCaseOp.target` fields is preliminary and incomplete. The `text` and `mpl` drawers will make a best-effort attempt to show data dependencies, but the LaTeX-based drawers will skip these completely. **Parameters** * **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – The circuit to visualize. * **scale** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *| None*) – Scale of image to draw (shrink if `< 1.0`). Only used by the `mpl`, `latex` and `latex_source` outputs. Defaults to `1.0`. * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – File path to save image to. Defaults to `None` (result not saved in a file). * **style** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *|*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Style name, file name of style JSON file, or a dictionary specifying the style. * **The supported style names are `""iqp""` (default), `""iqp-dark""`, `""clifford""`,** `""textbook""` and `""bw""`. * **If given a JSON file, e.g. `my_style.json` or `my_style` (the `.json`** extension may be omitted), this function attempts to load the style dictionary from that location. Note, that the JSON file must completely specify the visualization specifications. The file is searched for in `qiskit/visualization/circuit/styles`, the current working directory, and the location specified in `~/.qiskit/settings.conf`. * **If a dictionary, every entry overrides the default configuration. If the** `""name""` key is given, the default configuration is given by that style. For example, `{""name"": ""textbook"", ""subfontsize"": 5}` loads the `""texbook""` style and sets the subfontsize (e.g. the gate angles) to `5`. * **If `None` the default style `""iqp""` is used or, if given, the default style** specified in `~/.qiskit/settings.conf`. * **output** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Select the output method to use for drawing the circuit. Valid choices are `text`, `mpl`, `latex`, `latex_source`. By default the text drawer is used unless the user config file (usually `~/.qiskit/settings.conf`) has an alternative backend set as the default. For example, `circuit_drawer = latex`. If the output kwarg is set, that backend will always be used over the default in the user config file. * **interactive** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – When set to `True`, show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the text or the `latex_source` output type this has no effect and will be silently ignored. Defaults to `False`. * **reverse\_bits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – When set to `True`, reverse the bit order inside registers for the output visualization. Defaults to `False` unless the user config file (usually `~/.qiskit/settings.conf`) has an alternative value set. For example, `circuit_reverse_bits = True`. * **plot\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Enable/disable drawing barriers in the output circuit. Defaults to `True`. * **justify** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Options are `left`, `right` or `none`. If anything else is supplied, it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. `none` results in each gate being placed in its own column. * **vertical\_compression** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – `high`, `medium` or `low`. It merges the lines generated by the text output so the drawing will take less vertical room. Default is `medium`. Only used by the `text` output, will be silently ignored otherwise. * **idle\_wires** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Include idle wires (wires with no circuit elements) in output visualization. Default is `True`. * **with\_layout** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Include layout information, with labels on the physical layout. Default is `True`. * **fold** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Sets pagination. It can be disabled using -1. In `text`, sets the length of the lines. This is useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using `shutil.get_terminal_size()`. However, if running in jupyter, the default line length is set to 80 characters. In `mpl`, it is the number of (visual) layers before folding. Default is 25. * **ax** (*Any | None*) – Only used by the mpl backend. An optional `matplotlib.axes.Axes` object to be used for the visualization output. If none is specified, a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. * **initial\_state** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Adds $|0\rangle$ in the beginning of the qubit wires and $0$ to classical wires. Default is `False`. * **cregbundle** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If set to `True`, bundle classical registers. Default is `True`, except for when `output` is set to `""text""`. * **wire\_order** ([*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 integers used to reorder the display of the bits. The list must have an entry for every bit with the bits in the range 0 to (`num_qubits` + `num_clbits`). * **expr\_len** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of characters to display if an [`Expr`](circuit_classical#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.Expr"") is used for the condition in a [`ControlFlowOp`](qiskit.circuit.ControlFlowOp ""qiskit.circuit.ControlFlowOp""). If this number is exceeded, the string will be truncated at that number and ‘…’ added to the end. **Returns** `TextDrawing` or `matplotlib.figure` or `PIL.Image` or [`str`](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)""): * **`TextDrawing` (if `output='text'`)** A drawing that can be printed as ascii art. * **`matplotlib.figure.Figure` (if `output='mpl'`)** A matplotlib figure object for the circuit diagram. * **`PIL.Image` (if `output='latex`’)** An in-memory representation of the image of the circuit diagram. * **`str` (if `output='latex_source'`)** The LaTeX source code for visualizing the circuit diagram. **Raises** * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – when an invalid output method is selected * [**ImportError**](https://docs.python.org/3/library/exceptions.html#ImportError ""(in Python v3.12)"") – when the output methods requires non-installed libraries. **Example** ```python from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qc = QuantumCircuit(1, 1) qc.h(0) qc.measure(0, 0) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'}) ``` ![../\_images/qiskit-visualization-circuit\_drawer-1.png](/images/api/qiskit/1.0/qiskit-visualization-circuit_drawer-1.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.circuit_drawer.mdx "--- title: dag_drawer description: API reference for qiskit.visualization.dag_drawer in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.dag_drawer --- # qiskit.visualization.dag\_drawer Plot the directed acyclic graph (dag) to represent operation dependencies in a quantum circuit. This function calls the [`graphviz_draw()`](https://www.rustworkx.org/apiref/rustworkx.visualization.graphviz_draw.html#rustworkx.visualization.graphviz_draw ""(in rustworkx v0.14)"") function from the `rustworkx` package to draw the DAG. **Parameters** * **dag** ([*DAGCircuit*](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"")) – The dag to draw. * **scale** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – scaling factor * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – file path to save image to (format inferred from name) * **style** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – ‘plain’: B\&W graph ‘color’ (default): color input/output/op nodes **Returns** **if in Jupyter notebook and not saving to file,** otherwise None. **Return type** PIL.Image **Raises** * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – when style is not recognized. * [**InvalidFileError**](exceptions#qiskit.exceptions.InvalidFileError ""qiskit.exceptions.InvalidFileError"") – when filename provided is not valid **Example** ```python from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.visualization import dag_drawer 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) dag_drawer(dag) ``` ",repo/docs/api/qiskit/1.0\qiskit.visualization.dag_drawer.mdx "--- title: pass_manager_drawer description: API reference for qiskit.visualization.pass_manager_drawer in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.pass_manager_drawer --- # qiskit.visualization.pass\_manager\_drawer Draws the pass manager. This function needs [pydot](https://github.com/pydot/pydot), which in turn needs [Graphviz](https://www.graphviz.org/) to be installed. **Parameters** * **pass\_manager** ([*PassManager*](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"")) – the pass manager to be drawn * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – file path to save image to * **style** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *or OrderedDict*) – keys are the pass classes and the values are the colors to make them. An example can be seen in the DEFAULT\_STYLE. An ordered dict can be used to ensure a priority coloring when pass falls into multiple categories. Any values not included in the provided dict will be filled in from the default dict * **raw** ([*Bool*](circuit_classical#qiskit.circuit.classical.types.Bool ""qiskit.circuit.classical.types.Bool"")) – True if you want to save the raw Dot output not an image. The default is False. **Returns** an in-memory representation of the pass manager. Or None if no image was generated or PIL is not installed. **Return type** PIL.Image or None **Raises** * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – when nxpd or pydot not installed. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – If raw=True and filename=None. **Example** ```python %matplotlib inline from qiskit import QuantumCircuit from qiskit.compiler import transpile from qiskit.transpiler import PassManager from qiskit.visualization import pass_manager_drawer from qiskit.transpiler.passes import Unroller circ = QuantumCircuit(3) circ.ccx(0, 1, 2) circ.draw() pass_ = Unroller(['u1', 'u2', 'u3', 'cx']) pm = PassManager(pass_) new_circ = pm.run(circ) new_circ.draw(output='mpl') pass_manager_drawer(pm, ""passmanager.jpg"") ``` ",repo/docs/api/qiskit/1.0\qiskit.visualization.pass_manager_drawer.mdx "--- title: plot_bloch_multivector description: API reference for qiskit.visualization.plot_bloch_multivector in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_bloch_multivector --- # qiskit.visualization.plot\_bloch\_multivector Plot a Bloch sphere for each qubit. Each component $(x,y,z)$ of the Bloch sphere labeled as ‘qubit i’ represents the expected value of the corresponding Pauli operator acting only on that qubit, that is, the expected value of $I_{N-1} \otimes\dotsb\otimes I_{i+1}\otimes P_i \otimes I_{i-1}\otimes\dotsb\otimes I_0$, where $N$ is the number of qubits, $P\in \{X,Y,Z\}$ and $I$ is the identity operator. **Parameters** * **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") *or ndarray*) – an N-qubit quantum state. * **title** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – a string that represents the plot title * **figsize** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – size of each individual Bloch sphere figure, in inches. * **reverse\_bits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, plots qubits following Qiskit’s convention \[Default:False]. * **font\_size** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Font size for the Bloch ball figures. * **title\_font\_size** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Font size for the title. * **title\_pad** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Padding for the title (suptitle y position is y=1+title\_pad/100). **Returns** A matplotlib figure instance. **Return type** [`matplotlib.figure.Figure`](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure ""(in Matplotlib v3.8.4)"") **Raises** * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – Requires matplotlib. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – if input is not a valid N-qubit state. **Examples** ```python from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) state = Statevector(qc) plot_bloch_multivector(state) ``` ![../\_images/qiskit-visualization-plot\_bloch\_multivector-1.png](/images/api/qiskit/1.0/qiskit-visualization-plot_bloch_multivector-1.png) ```python from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) # You can reverse the order of the qubits. from qiskit.quantum_info import DensityMatrix qc = QuantumCircuit(2) qc.h([0, 1]) qc.t(1) qc.s(0) qc.cx(0,1) matrix = DensityMatrix(qc) plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True) ``` ![../\_images/qiskit-visualization-plot\_bloch\_multivector-2.png](/images/api/qiskit/1.0/qiskit-visualization-plot_bloch_multivector-2.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_bloch_multivector.mdx "--- title: plot_bloch_vector description: API reference for qiskit.visualization.plot_bloch_vector in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_bloch_vector --- # qiskit.visualization.plot\_bloch\_vector Plot the Bloch sphere. Plot a Bloch sphere with the specified coordinates, that can be given in both cartesian and spherical systems. **Parameters** * **bloch** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[double]*) – array of three elements where \[\, \, \] (Cartesian) or \[\, \, \] (spherical in radians) \ is inclination angle from +z direction \ is azimuth from +x direction * **title** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – a string that represents the plot title * **ax** ([*matplotlib.axes.Axes*](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes ""(in Matplotlib v3.8.4)"")) – An Axes to use for rendering the bloch sphere * **figsize** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – Figure size in inches. Has no effect is passing `ax`. * **coord\_type** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – a string that specifies coordinate type for bloch (Cartesian or spherical), default is Cartesian * **font\_size** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Font size. **Returns** A matplotlib figure instance if `ax = None`. **Return type** [`matplotlib.figure.Figure`](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure ""(in Matplotlib v3.8.4)"") **Raises** [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – Requires matplotlib. **Examples** ```python from qiskit.visualization import plot_bloch_vector plot_bloch_vector([0,1,0], title=""New Bloch Sphere"") ``` ![../\_images/qiskit-visualization-plot\_bloch\_vector-1.png](/images/api/qiskit/1.0/qiskit-visualization-plot_bloch_vector-1.png) ```python import numpy as np from qiskit.visualization import plot_bloch_vector # You can use spherical coordinates instead of cartesian. plot_bloch_vector([1, np.pi/2, np.pi/3], coord_type='spherical') ``` ![../\_images/qiskit-visualization-plot\_bloch\_vector-2.png](/images/api/qiskit/1.0/qiskit-visualization-plot_bloch_vector-2.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_bloch_vector.mdx "--- title: plot_circuit_layout description: API reference for qiskit.visualization.plot_circuit_layout in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_circuit_layout --- # qiskit.visualization.plot\_circuit\_layout Plot the layout of a circuit transpiled for a given target backend. **Parameters** * **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – Input quantum circuit. * **backend** ([*Backend*](qiskit.providers.Backend ""qiskit.providers.Backend"")) – Target backend. * **view** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Layout view: either ‘virtual’ or ‘physical’. * **qubit\_coordinates** (*Sequence*) – An optional sequence input (list or array being the most common) of 2d coordinates for each qubit. The length of the sequence must match the number of qubits on the backend. The sequence should be the planar coordinates in a 0-based square grid where each qubit is located. **Returns** A matplotlib figure showing layout. **Return type** Figure **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – Invalid view type given. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – Circuit has no layout attribute. **Example** ```python from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.visualization import plot_circuit_layout ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = GenericBackendV2(num_qubits=5) new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend) ``` ![../\_images/qiskit-visualization-plot\_circuit\_layout-1.png](/images/api/qiskit/1.0/qiskit-visualization-plot_circuit_layout-1.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_circuit_layout.mdx "--- title: plot_coupling_map description: API reference for qiskit.visualization.plot_coupling_map in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_coupling_map --- # qiskit.visualization.plot\_coupling\_map Plots an arbitrary coupling map of qubits (embedded in a plane). **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits defined and plotted. * **qubit\_coordinates** (*List\[List\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – A list of two-element lists, with entries of each nested list being the planar coordinates in a 0-based square grid where each qubit is located. * **coupling\_map** (*List\[List\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – A list of two-element lists, with entries of each nested list being the qubit numbers of the bonds to be plotted. * **figsize** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – Output figure size (wxh) in inches. * **plot\_directed** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Plot directed coupling map. * **label\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Label the qubits. * **qubit\_size** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Size of qubit marker. * **line\_width** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Width of lines. * **font\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Font size of qubit labels. * **qubit\_color** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of colors for the qubits * **qubit\_labels** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of qubit labels * **line\_color** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of colors for each line from coupling\_map. * **font\_color** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The font color for the qubit labels. * **ax** (*Axes*) – A Matplotlib axes instance. * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – file path to save image to. **Returns** A Matplotlib figure instance. **Return type** Figure **Raises** * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – If matplotlib or graphviz is not installed. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If length of qubit labels does not match number of qubits. **Example** ```python from qiskit.visualization import plot_coupling_map num_qubits = 8 qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]] plot_coupling_map(num_qubits, qubit_coordinates, coupling_map) ``` ![../\_images/qiskit-visualization-plot\_coupling\_map-1.png](/images/api/qiskit/1.0/qiskit-visualization-plot_coupling_map-1.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_coupling_map.mdx "--- title: plot_distribution description: API reference for qiskit.visualization.plot_distribution in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_distribution --- # qiskit.visualization.plot\_distribution Plot a distribution from input sampled data. **Parameters** * **data** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or*[*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – This is either a list of dictionaries or a single dict containing the values to represent (ex \{‘001’: 130}) * **figsize** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – Figure size in inches. * **color** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – String or list of strings for distribution bar colors. * **number\_to\_keep** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of terms to plot per dataset. The rest is made into a single bar called ‘rest’. If multiple datasets are given, the `number_to_keep` applies to each dataset individually, which may result in more bars than `number_to_keep + 1`. The `number_to_keep` applies to the total values, rather than the x-axis sort. * **sort** (*string*) – Could be ‘asc’, ‘desc’, ‘hamming’, ‘value’, or ‘value\_desc’. If set to ‘value’ or ‘value\_desc’ the x axis will be sorted by the maximum probability for each bitstring. Defaults to ‘asc’. * **target\_string** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Target string if ‘sort’ is a distance measure. * **legend** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of strings to use for labels of the data. The number of entries must match the length of data (if data is a list or 1 if it’s a dict) * **bar\_labels** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Label each bar in histogram with probability value. * **title** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A string to use for the plot title * **ax** ([*matplotlib.axes.Axes*](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes ""(in Matplotlib v3.8.4)"")) – An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – file path to save image to. **Returns** A figure for the rendered distribution, if the `ax` kwarg is not set. **Return type** matplotlib.Figure **Raises** * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – Matplotlib not available. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – When legend is provided and the length doesn’t match the input data. **Examples** ```python # Plot two counts in the same figure with legends and colors specified. from qiskit.visualization import plot_distribution counts1 = {'00': 525, '11': 499} counts2 = {'00': 511, '11': 514} legend = ['First execution', 'Second execution'] plot_distribution([counts1, counts2], legend=legend, color=['crimson','midnightblue'], title=""New Distribution"") # You can sort the bitstrings using different methods. counts = {'001': 596, '011': 211, '010': 50, '000': 117, '101': 33, '111': 8, '100': 6, '110': 3} # Sort by the counts in descending order dist1 = plot_distribution(counts, sort='value_desc') # Sort by the hamming distance (the number of bit flips to change from # one bitstring to the other) from a target string. dist2 = plot_distribution(counts, sort='hamming', target_string='001') ``` ![../\_images/qiskit-visualization-plot\_distribution-1\_00.png](/images/api/qiskit/1.0/qiskit-visualization-plot_distribution-1_00.png) ![../\_images/qiskit-visualization-plot\_distribution-1\_01.png](/images/api/qiskit/1.0/qiskit-visualization-plot_distribution-1_01.png) ![../\_images/qiskit-visualization-plot\_distribution-1\_02.png](/images/api/qiskit/1.0/qiskit-visualization-plot_distribution-1_02.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_distribution.mdx "--- title: plot_error_map description: API reference for qiskit.visualization.plot_error_map in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_error_map --- # qiskit.visualization.plot\_error\_map Plots the error map of a given backend. **Parameters** * **backend** ([*Backend*](qiskit.providers.Backend ""qiskit.providers.Backend"")) – Given backend. * **figsize** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – Figure size in inches. * **show\_title** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Show the title or not. * **qubit\_coordinates** (*Sequence*) – An optional sequence input (list or array being the most common) of 2d coordinates for each qubit. The length of the sequence much mast the number of qubits on the backend. The sequence should be the planar coordinates in a 0-based square grid where each qubit is located. **Returns** A matplotlib figure showing error map. **Return type** Figure **Raises** * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – The backend does not provide gate errors for the ‘sx’ gate. * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – If matplotlib or seaborn is not installed. **Example** ```python from qiskit.visualization import plot_error_map from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(num_qubits=5) plot_error_map(backend) ``` ![../\_images/qiskit-visualization-plot\_error\_map-1.png](/images/api/qiskit/1.0/qiskit-visualization-plot_error_map-1.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_error_map.mdx "--- title: plot_gate_map description: API reference for qiskit.visualization.plot_gate_map in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_gate_map --- # qiskit.visualization.plot\_gate\_map Plots the gate map of a device. **Parameters** * **backend** ([*Backend*](qiskit.providers.Backend ""qiskit.providers.Backend"")) – The backend instance that will be used to plot the device gate map. * **figsize** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – Output figure size (wxh) in inches. * **plot\_directed** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Plot directed coupling map. * **label\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Label the qubits. * **qubit\_size** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Size of qubit marker. * **line\_width** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Width of lines. * **font\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Font size of qubit labels. * **qubit\_color** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of colors for the qubits * **qubit\_labels** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of qubit labels * **line\_color** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of colors for each line from coupling\_map. * **font\_color** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The font color for the qubit labels. * **ax** (*Axes*) – A Matplotlib axes instance. * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – file path to save image to. * **qubit\_coordinates** (*Sequence*) – An optional sequence input (list or array being the most common) of 2d coordinates for each qubit. The length of the sequence much match the number of qubits on the backend. The sequence should be the planar coordinates in a 0-based square grid where each qubit is located. **Returns** A Matplotlib figure instance. **Return type** Figure **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if tried to pass a simulator, or if the backend is None, but one of num\_qubits, mpl\_data, or cmap is None. * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – if matplotlib not installed. **Example** ```python from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.visualization import plot_gate_map backend = GenericBackendV2(num_qubits=5) plot_gate_map(backend) ``` ![../\_images/qiskit-visualization-plot\_gate\_map-1.png](/images/api/qiskit/1.0/qiskit-visualization-plot_gate_map-1.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_gate_map.mdx "--- title: plot_histogram description: API reference for qiskit.visualization.plot_histogram in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_histogram --- # qiskit.visualization.plot\_histogram Plot a histogram of input counts data. **Parameters** * **data** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or*[*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – This is either a list of dictionaries or a single dict containing the values to represent (ex `{'001': 130}`) * **figsize** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – Figure size in inches. * **color** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – String or list of strings for histogram bar colors. * **number\_to\_keep** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of terms to plot per dataset. The rest is made into a single bar called ‘rest’. If multiple datasets are given, the `number_to_keep` applies to each dataset individually, which may result in more bars than `number_to_keep + 1`. The `number_to_keep` applies to the total values, rather than the x-axis sort. * **sort** (*string*) – Could be ‘asc’, ‘desc’, ‘hamming’, ‘value’, or ‘value\_desc’. If set to ‘value’ or ‘value\_desc’ the x axis will be sorted by the number of counts for each bitstring. Defaults to ‘asc’. * **target\_string** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Target string if ‘sort’ is a distance measure. * **legend** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of strings to use for labels of the data. The number of entries must match the length of data (if data is a list or 1 if it’s a dict) * **bar\_labels** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Label each bar in histogram with counts value. * **title** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – A string to use for the plot title * **ax** ([*matplotlib.axes.Axes*](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes ""(in Matplotlib v3.8.4)"")) – An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – file path to save image to. **Returns** A figure for the rendered histogram, if the `ax` kwarg is not set. **Return type** matplotlib.Figure **Raises** * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – Matplotlib not available. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – When legend is provided and the length doesn’t match the input data. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – Input must be Counts or a dict **Examples** ```python # Plot two counts in the same figure with legends and colors specified. from qiskit.visualization import plot_histogram counts1 = {'00': 525, '11': 499} counts2 = {'00': 511, '11': 514} legend = ['First execution', 'Second execution'] plot_histogram([counts1, counts2], legend=legend, color=['crimson','midnightblue'], title=""New Histogram"") # You can sort the bitstrings using different methods. counts = {'001': 596, '011': 211, '010': 50, '000': 117, '101': 33, '111': 8, '100': 6, '110': 3} # Sort by the counts in descending order hist1 = plot_histogram(counts, sort='value_desc') # Sort by the hamming distance (the number of bit flips to change from # one bitstring to the other) from a target string. hist2 = plot_histogram(counts, sort='hamming', target_string='001') ``` ![../\_images/qiskit-visualization-plot\_histogram-1\_00.png](/images/api/qiskit/1.0/qiskit-visualization-plot_histogram-1_00.png) ![../\_images/qiskit-visualization-plot\_histogram-1\_01.png](/images/api/qiskit/1.0/qiskit-visualization-plot_histogram-1_01.png) ![../\_images/qiskit-visualization-plot\_histogram-1\_02.png](/images/api/qiskit/1.0/qiskit-visualization-plot_histogram-1_02.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_histogram.mdx "--- title: plot_state_city description: API reference for qiskit.visualization.plot_state_city in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_state_city --- # qiskit.visualization.plot\_state\_city Plot the cityscape of quantum state. Plot two 3d bar graphs (two dimensional) of the real and imaginary part of the density matrix rho. **Parameters** * **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") *or ndarray*) – an N-qubit quantum state. * **title** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – a string that represents the plot title * **figsize** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – Figure size in inches. * **color** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of len=2 giving colors for real and imaginary components of matrix elements. * **alpha** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Transparency value for bars * **ax\_real** ([*matplotlib.axes.Axes*](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes ""(in Matplotlib v3.8.4)"")) – An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. If this is specified without an ax\_imag only the real component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. * **ax\_imag** ([*matplotlib.axes.Axes*](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes ""(in Matplotlib v3.8.4)"")) – An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. If this is specified without an ax\_real only the imaginary component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. **Returns** The matplotlib.Figure of the visualization if the `ax_real` and `ax_imag` kwargs are not set **Return type** [`matplotlib.figure.Figure`](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure ""(in Matplotlib v3.8.4)"") **Raises** * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – Requires matplotlib. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – When ‘color’ is not a list of len=2. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – if input is not a valid N-qubit state. **Examples** ```python # You can choose different colors for the real and imaginary parts of the density matrix. from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title=""New State City"") ``` ![../\_images/qiskit-visualization-plot\_state\_city-1.png](/images/api/qiskit/1.0/qiskit-visualization-plot_state_city-1.png) ```python # You can make the bars more transparent to better see the ones that are behind # if they overlap. import numpy as np from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) state = Statevector(qc) plot_state_city(state, alpha=0.6) ``` ![../\_images/qiskit-visualization-plot\_state\_city-2.png](/images/api/qiskit/1.0/qiskit-visualization-plot_state_city-2.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_state_city.mdx "--- title: plot_state_hinton description: API reference for qiskit.visualization.plot_state_hinton in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_state_hinton --- # qiskit.visualization.plot\_state\_hinton Plot a hinton diagram for the density matrix of a quantum state. The hinton diagram represents the values of a matrix using squares, whose size indicate the magnitude of their corresponding value and their color, its sign. A white square means the value is positive and a black one means negative. **Parameters** * **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") *or ndarray*) – An N-qubit quantum state. * **title** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – a string that represents the plot title * **figsize** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – Figure size in inches. * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – file path to save image to. * **ax\_real** ([*matplotlib.axes.Axes*](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes ""(in Matplotlib v3.8.4)"")) – An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. If this is specified without an ax\_imag only the real component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. * **ax\_imag** ([*matplotlib.axes.Axes*](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes ""(in Matplotlib v3.8.4)"")) – An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. If this is specified without an ax\_imag only the real component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. **Returns** The matplotlib.Figure of the visualization if neither ax\_real or ax\_imag is set. **Return type** [`matplotlib.figure.Figure`](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure ""(in Matplotlib v3.8.4)"") **Raises** * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – Requires matplotlib. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – if input is not a valid N-qubit state. **Examples** ```python import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_hinton qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3 , 0) qc.rx(np.pi/5, 1) state = DensityMatrix(qc) plot_state_hinton(state, title=""New Hinton Plot"") ``` ![../\_images/qiskit-visualization-plot\_state\_hinton-1.png](/images/api/qiskit/1.0/qiskit-visualization-plot_state_hinton-1.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_state_hinton.mdx "--- title: plot_state_paulivec description: API reference for qiskit.visualization.plot_state_paulivec in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_state_paulivec --- # qiskit.visualization.plot\_state\_paulivec Plot the Pauli-vector representation of a quantum state as bar graph. The Pauli-vector of a density matrix $\rho$ is defined by the expectation of each possible tensor product of single-qubit Pauli operators (including the identity), that is $$ \rho = \frac{1}{2^n} \sum_{\sigma \in \{I, X, Y, Z\}^{\otimes n}} \mathrm{Tr}(\sigma \rho) \sigma. $$ This function plots the coefficients $\mathrm{Tr}(\sigma\rho)$ as bar graph. **Parameters** * **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") *or ndarray*) – an N-qubit quantum state. * **title** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – a string that represents the plot title * **figsize** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – Figure size in inches. * **color** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") *or*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Color of the coefficient value bars. * **ax** ([*matplotlib.axes.Axes*](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes ""(in Matplotlib v3.8.4)"")) – An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. **Returns** The matplotlib.Figure of the visualization if the `ax` kwarg is not set **Return type** [`matplotlib.figure.Figure`](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure ""(in Matplotlib v3.8.4)"") **Raises** * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – Requires matplotlib. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – if input is not a valid N-qubit state. **Examples** ```python # You can set a color for all the bars. from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_paulivec(state, color='midnightblue', title=""New PauliVec plot"") ``` ![../\_images/qiskit-visualization-plot\_state\_paulivec-1.png](/images/api/qiskit/1.0/qiskit-visualization-plot_state_paulivec-1.png) ```python # If you introduce a list with less colors than bars, the color of the bars will # alternate following the sequence from the list. import numpy as np from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0, 1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) matrix = DensityMatrix(qc) plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen']) ``` ![../\_images/qiskit-visualization-plot\_state\_paulivec-2.png](/images/api/qiskit/1.0/qiskit-visualization-plot_state_paulivec-2.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_state_paulivec.mdx "--- title: plot_state_qsphere description: API reference for qiskit.visualization.plot_state_qsphere in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.plot_state_qsphere --- # qiskit.visualization.plot\_state\_qsphere Plot the qsphere representation of a quantum state. Here, the size of the points is proportional to the probability of the corresponding term in the state and the color represents the phase. **Parameters** * **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") *or ndarray*) – an N-qubit quantum state. * **figsize** ([*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – Figure size in inches. * **ax** ([*matplotlib.axes.Axes*](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes ""(in Matplotlib v3.8.4)"")) – An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. * **show\_state\_labels** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – An optional boolean indicating whether to show labels for each basis state. * **show\_state\_phases** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – An optional boolean indicating whether to show the phase for each basis state. * **use\_degrees** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – An optional boolean indicating whether to use radians or degrees for the phase values in the plot. **Returns** A matplotlib figure instance if the `ax` kwarg is not set **Return type** [`matplotlib.figure.Figure`](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure ""(in Matplotlib v3.8.4)"") **Raises** * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – Requires matplotlib. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – if input is not a valid N-qubit state. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – Input statevector does not have valid dimensions. **Examples** ```python from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_qsphere(state) ``` ![../\_images/qiskit-visualization-plot\_state\_qsphere-1.png](/images/api/qiskit/1.0/qiskit-visualization-plot_state_qsphere-1.png) ```python # You can show the phase of each state and use # degrees instead of radians from qiskit.quantum_info import DensityMatrix import numpy as np from qiskit import QuantumCircuit from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) qc.z(1) matrix = DensityMatrix(qc) plot_state_qsphere(matrix, show_state_phases = True, use_degrees = True) ``` ![../\_images/qiskit-visualization-plot\_state\_qsphere-2.png](/images/api/qiskit/1.0/qiskit-visualization-plot_state_qsphere-2.png) ",repo/docs/api/qiskit/1.0\qiskit.visualization.plot_state_qsphere.mdx "--- title: timeline_drawer description: API reference for qiskit.visualization.timeline_drawer in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.timeline_drawer --- # qiskit.visualization.timeline\_drawer Generate visualization data for scheduled circuit programs. **Parameters** * **program** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")) – Program to visualize. This program should be a QuantumCircuit which is transpiled with a scheduling\_method, thus containing gate time information. * **style** ([*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)"")*,* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")*] | None*) – Stylesheet options. This can be dictionary or preset stylesheet classes. See `IQXStandard`, `IQXSimple`, and `IQXDebugging` for details of preset stylesheets. See also the stylesheet section for details of configuration keys. * **time\_range** ([*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)"")*,* [*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None*) – Set horizontal axis limit. * **disable\_bits** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[Bits] | None*) – List of qubits of classical bits not shown in the output image. * **show\_clbits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – A control property to show classical bits. Set True to show classical bits. * **show\_idle** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – A control property to show idle timeline. Set True to show timeline without gates. * **show\_barriers** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – A control property to show barrier instructions. Set True to show barrier instructions. * **show\_delays** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – A control property to show delay instructions. Set True to show delay instructions. * **show\_labels** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – A control property to show annotations, i.e. name, of gates. Set True to show annotations. * **plotter** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Name of plotter API to generate an output image. One of following APIs should be specified: ```python mpl: Matplotlib API Matplotlib API to generate 2D image. Timelines are placed along y axis with vertical offset. This API takes matplotlib.axes.Axes as `axis` input. ``` axis and style kwargs may depend on the plotter. * **axis** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"") *| None*) – Arbitrary object passed to the plotter. If this object is provided, the plotters uses given axis instead of internally initializing a figure object. This object format depends on the plotter. See plotters section for details. * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – If provided the output image is dumped into a file under the filename. **Returns** Visualization output data. The returned data type depends on the plotter. If matplotlib family is specified, this will be a matplotlib.pyplot.Figure data. The returned data is generated by the .get\_image method of the specified plotter API. **Raises** * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – When required visualization package is not installed. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – When invalid plotter API is specified. **Style Dict Details** The stylesheet kwarg contains numerous options that define the style of the output timeline visualization. The stylesheet options can be classified into formatter, generator and layout. Those options available in the stylesheet are defined below: **Parameters** * **formatter.general.fig\_width** – Width of output image (default 14). * **formatter.general.fig\_unit\_height** – Height of output image per timeline. The sum of all timeline becomes the height of the output image (default 0.8). * **formatter.general.dpi** – Dot per inch of image if filename is set (default 150). * **formatter.margin.top** – Margin from the top boundary of the figure canvas to the zero line of the first time slot (default 0.5). * **formatter.margin.bottom** – Margin from the bottom boundary of the figure canvas to the zero lien of the last time slot (default 0.5). * **formatter.margin.left\_percent** – Margin from the left boundary of the figure canvas to the left limit of the horizontal axis. The value is in units of percentage of the whole program duration. If the duration is 100 and the value of 0.5 is set, this keeps left margin of 5 (default 0.02). * **formatter.margin.right\_percent** – Margin from the right boundary of the figure canvas to the right limit of the horizontal axis. The value is in units of percentage of the whole program duration. If the duration is 100 and the value of 0.5 is set, this keeps right margin of 5 (default 0.02). * **formatter.margin.link\_interval\_percent** – Allowed overlap of gate links. If multiple gate links are drawing within this range, links are horizontally shifted not to overlap with each other. The value is in units of percentage of the whole program duration (default 0.01). * **formatter.time\_bucket.edge\_dt** – The length of round edge of gate boxes. Gate boxes are smoothly faded in and out from the zero line. This value is in units of the system cycle time dt (default 10). * **formatter.margin.minimum\_duration** – Minimum scheduled circuit duration. If the duration of input circuit is below this value, horizontal limit is set based on this value. This value is in units of the system cycle time dt (default 50). * **formatter.color.background** – Color code of the face color of canvas (default #FFFFFF). * **formatter.color.timeslot** – Face color of the time slot box (default #DDDDDD). * **formatter.color.gate\_name** – Text color of the gate name annotations (default #000000). * **formatter.color.bit\_name** – Text color of the bit label annotations (default #000000). * **formatter.color.barrier** – Line color of barriers (default #222222). * **formatter.color.gates** – A dictionary of the gate box or gate symbol colors to use for each element type in the output visualization. The default values are: ```python { 'u0': '#FA74A6', 'u1': '#000000', 'u2': '#FA74A6', 'u3': '#FA74A6', 'id': '#05BAB6', 'sx': '#FA74A6', 'sxdg': '#FA74A6', 'x': '#05BAB6', 'y': '#05BAB6', 'z': '#05BAB6', 'h': '#6FA4FF', 'cx': '#6FA4FF', 'cy': '#6FA4FF', 'cz': '#6FA4FF', 'swap': '#6FA4FF', 's': '#6FA4FF', 'sdg': '#6FA4FF', 'dcx': '#6FA4FF', 'iswap': '#6FA4FF', 't': '#BB8BFF', 'tdg': '#BB8BFF', 'r': '#BB8BFF', 'rx': '#BB8BFF', 'ry': '#BB8BFF', 'rz': '#000000', 'reset': '#808080', 'measure': '#808080' } ``` You must specify all the necessary values if using this. If a gate name is not specified, the color in formatter.color.default\_gate is applied. * **formatter.color.default\_gate** – Default gate color. This color is applied when a gate name to visualize is not contained in the dictionary of formatter.color.gates (default #BB8BFF). * **formatter.latex\_symbol.gates** – A dictionary of latex representation of gate names to use for each element type in the output visualization. The default values are: ```python { 'u0': r'{\rm U}_0', 'u1': r'{\rm U}_1', 'u2': r'{\rm U}_2', 'u3': r'{\rm U}_3', 'id': r'{\rm Id}', 'x': r'{\rm X}', 'y': r'{\rm Y}', 'z': r'{\rm Z}', 'h': r'{\rm H}', 'cx': r'{\rm CX}', 'cy': r'{\rm CY}', 'cz': r'{\rm CZ}', 'swap': r'{\rm SWAP}', 's': r'{\rm S}', 'sdg': r'{\rm S}^\dagger', 'sx': r'{\rm √X}', 'sxdg': r'{\rm √X}^\dagger', 'dcx': r'{\rm DCX}', 'iswap': r'{\rm iSWAP}', 't': r'{\rm T}', 'tdg': r'{\rm T}^\dagger', 'r': r'{\rm R}', 'rx': r'{\rm R}_x', 'ry': r'{\rm R}_y', 'rz': r'{\rm R}_z', 'reset': r'|0\rangle', 'measure': r'{\rm Measure}' } ``` You must specify all the necessary values if using this. There is no provision for passing an incomplete dict in. * **formatter.latex\_symbol.frame\_change** – Latex representation of the frame change symbol (default r\`circlearrowleft\`). * **formatter.unicode\_symbol.frame\_change** – Unicode representation of the frame change symbol (default u’u21BA’). * **formatter.box\_height.gate** – Height of gate box (default 0.5). * **formatter.box\_height.timeslot** – Height of time slot (default 0.6). * **formatter.layer.gate** – Layer index of gate boxes. Larger number comes in the front of the output image (default 3). * **formatter.layer.timeslot** – Layer index of time slots. Larger number comes in the front of the output image (default 0). * **formatter.layer.gate\_name** – Layer index of gate name annotations. Larger number comes in the front of the output image (default 5). * **formatter.layer.bit\_name** – Layer index of bit labels. Larger number comes in the front of the output image (default 5). * **formatter.layer.frame\_change** – Layer index of frame change symbols. Larger number comes in the front of the output image (default 4). * **formatter.layer.barrier** – Layer index of barrier lines. Larger number comes in the front of the output image (default 1). * **formatter.layer.gate\_link** – Layer index of gate link lines. Larger number comes in the front of the output image (default 2). * **formatter.alpha.gate** – Transparency of gate boxes. A value in the range from 0 to 1. The value 0 gives completely transparent boxes (default 1.0). * **formatter.alpha.timeslot** – Transparency of time slots. A value in the range from 0 to 1. The value 0 gives completely transparent boxes (default 0.7). * **formatter.alpha.barrier** – Transparency of barrier lines. A value in the range from 0 to 1. The value 0 gives completely transparent lines (default 0.5). * **formatter.alpha.gate\_link** – Transparency of gate link lines. A value in the range from 0 to 1. The value 0 gives completely transparent lines (default 0.8). * **formatter.line\_width.gate** – Line width of the fringe of gate boxes (default 0). * **formatter.line\_width.timeslot** – Line width of the fringe of time slots (default 0). * **formatter.line\_width.barrier** – Line width of barrier lines (default 3). * **formatter.line\_width.gate\_link** – Line width of gate links (default 3). * **formatter.line\_style.barrier** – Line style of barrier lines. This conforms to the line style spec of matplotlib (default ‘-’). * **formatter.line\_style.gate\_link** – Line style of gate link lines. This conforms to the line style spec of matplotlib (default ‘-’). * **formatter.text\_size.gate\_name** – Text size of gate name annotations (default 12). * **formatter.text\_size.bit\_name** – Text size of bit labels (default 15). * **formatter.text\_size.frame\_change** – Text size of frame change symbols (default 18). * **formatter.text\_size.axis\_label** – Text size of axis labels (default 13). * **formatter.label\_offset.frame\_change** – Offset of zero duration gate name annotations from the zero line of time slot (default 0.25). * **formatter.control.show\_idle** – Set True to show time slots without gate (default True). * **formatter.control.show\_clbits** – Set True to show time slots of classical bits (default True). * **formatter.control.show\_barriers** – Set True to show barriers (default True). * **formatter.control.show\_delays** – Set True to show delay boxes (default True). * **generator.gates** – List of callback functions that generates drawings for gates. Arbitrary callback functions satisfying the generator format can be set here. There are some default generators in the timeline drawer. See `generators` for more details. No default generator is set (default \[]). * **generator.bits** – List of callback functions that generates drawings for bit labels and time slots. Arbitrary callback functions satisfying the generator format can be set here. There are some default generators in the timeline drawer. See `generators` for more details. No default generator is set (default \[]). * **generator.barriers** – List of callback functions that generates drawings for barriers. Arbitrary callback functions satisfying the generator format can be set here. There are some default generators in the timeline drawer. See `generators` for more details. No default generator is set (default \[]). * **generator.gate\_links** – List of callback functions that generates drawings for gate links. Arbitrary callback functions satisfying the generator format can be set here. There are some default generators in the timeline drawer. See `generators` for more details. No default generator is set (default \[]). * **layout.bit\_arrange** – Callback function that sorts bits. See `layouts` for more details. No default layout is set. (default None). * **layout.time\_axis\_map** – Callback function that determines the layout of horizontal axis labels. See `layouts` for more details. No default layout is set. (default None). **Examples** To visualize a scheduled circuit program, you can call this function with set of control arguments. Most of appearance of the output image can be controlled by the stylesheet. Drawing with the default stylesheet. ```python from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw from qiskit.providers.fake_provider import GenericBackendV2 qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, GenericBackendV2(5), scheduling_method='alap', layout_method='trivial') draw(qc) ``` ![../\_images/qiskit-visualization-timeline\_drawer-1.png](/images/api/qiskit/1.0/qiskit-visualization-timeline_drawer-1.png) Drawing with the simple stylesheet. ```python from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXSimple from qiskit.providers.fake_provider import GenericBackendV2 qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, GenericBackendV2(5), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXSimple()) ``` ![../\_images/qiskit-visualization-timeline\_drawer-2.png](/images/api/qiskit/1.0/qiskit-visualization-timeline_drawer-2.png) Drawing with the stylesheet suited for program debugging. ```python from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXDebugging from qiskit.providers.fake_provider import GenericBackendV2 qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, GenericBackendV2(5), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXDebugging()) ``` ![../\_images/qiskit-visualization-timeline\_drawer-3.png](/images/api/qiskit/1.0/qiskit-visualization-timeline_drawer-3.png) You can partially customize a preset stylesheet when call it: ```python my_style = { 'formatter.general.fig_width': 16, 'formatter.general.fig_unit_height': 1 } style = IQXStandard(**my_style) # draw draw(qc, style=style) ``` In the same way as above, you can create custom generator or layout functions and update existing stylesheet with custom functions. This feature enables you to control the most of appearance of the output image without modifying the codebase of the scheduled circuit drawer. ",repo/docs/api/qiskit/1.0\qiskit.visualization.timeline_drawer.mdx "--- title: visualize_transition description: API reference for qiskit.visualization.visualize_transition in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit.visualization.visualize_transition --- # qiskit.visualization.visualize\_transition Creates animation showing transitions between states of a single qubit by applying quantum gates. **Parameters** * **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")) – Qiskit single-qubit QuantumCircuit. Gates supported are h,x, y, z, rx, ry, rz, s, sdg, t, tdg and u1. * **trace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Controls whether to display tracing vectors - history of 10 past vectors at each step of the animation. * **saveas** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – User can choose to save the animation as a video to their filesystem. This argument is a string of path with filename and extension (e.g. “movie.mp4” to save the video in current working directory). * **fpg** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Frames per gate. Finer control over animation smoothness and computational needs to render the animation. Works well for tkinter GUI as it is, for jupyter GUI it might be preferable to choose fpg between 5-30. * **spg** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Seconds per gate. How many seconds should animation of individual gate transitions take. **Returns** If arg jupyter is set to True. Otherwise opens tkinter GUI and returns after the GUI is closed. **Return type** IPython.core.display.HTML **Raises** * [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – Must have Matplotlib (and/or IPython) installed. * [**VisualizationError**](visualization#qiskit.visualization.VisualizationError ""qiskit.visualization.VisualizationError"") – Given gate(s) are not supported. ",repo/docs/api/qiskit/1.0\qiskit.visualization.visualize_transition.mdx "--- title: qobj description: API reference for qiskit.qobj in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.qobj --- # Qobj `qiskit.qobj` ## Base | | | | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | [`QobjExperimentHeader`](qiskit.qobj.QobjExperimentHeader ""qiskit.qobj.QobjExperimentHeader"")(\*\*kwargs) | A class representing a header dictionary for a Qobj Experiment. | | [`QobjHeader`](qiskit.qobj.QobjHeader ""qiskit.qobj.QobjHeader"")(\*\*kwargs) | A class used to represent a dictionary header in Qobj objects. | ## Qasm | | | | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | [`QasmQobj`](qiskit.qobj.QasmQobj ""qiskit.qobj.QasmQobj"")(\[qobj\_id, config, experiments, header]) | An OpenQASM 2 Qobj. | | [`QasmQobjInstruction`](qiskit.qobj.QasmQobjInstruction ""qiskit.qobj.QasmQobjInstruction"")(name\[, params, qubits, ...]) | A class representing a single instruction in an QasmQobj Experiment. | | [`QasmQobjExperimentConfig`](qiskit.qobj.QasmQobjExperimentConfig ""qiskit.qobj.QasmQobjExperimentConfig"")(\[calibrations, ...]) | Configuration for a single OpenQASM 2 experiment in the qobj. | | [`QasmQobjExperiment`](qiskit.qobj.QasmQobjExperiment ""qiskit.qobj.QasmQobjExperiment"")(\[config, header, ...]) | An OpenQASM 2 Qobj Experiment. | | [`QasmQobjConfig`](qiskit.qobj.QasmQobjConfig ""qiskit.qobj.QasmQobjConfig"")(\[shots, seed\_simulator, ...]) | A configuration for an OpenQASM 2 Qobj. | | [`QasmExperimentCalibrations`](qiskit.qobj.QasmExperimentCalibrations ""qiskit.qobj.QasmExperimentCalibrations"")(gates) | A container for any calibrations data. | | [`GateCalibration`](qiskit.qobj.GateCalibration ""qiskit.qobj.GateCalibration"")(name, qubits, params, ...) | Each calibration specifies a unique gate by name, qubits and params, and contains the Pulse instructions to implement it. | ## Pulse | | | | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | [`PulseQobj`](qiskit.qobj.PulseQobj ""qiskit.qobj.PulseQobj"")(qobj\_id, config, experiments\[, header]) | A Pulse Qobj. | | [`PulseQobjInstruction`](qiskit.qobj.PulseQobjInstruction ""qiskit.qobj.PulseQobjInstruction"")(name, t0\[, ch, ...]) | A class representing a single instruction in an PulseQobj Experiment. | | [`PulseQobjExperimentConfig`](qiskit.qobj.PulseQobjExperimentConfig ""qiskit.qobj.PulseQobjExperimentConfig"")(\[qubit\_lo\_freq, ...]) | A config for a single Pulse experiment in the qobj. | | [`PulseQobjExperiment`](qiskit.qobj.PulseQobjExperiment ""qiskit.qobj.PulseQobjExperiment"")(instructions\[, config, ...]) | A Pulse Qobj Experiment. | | [`PulseQobjConfig`](qiskit.qobj.PulseQobjConfig ""qiskit.qobj.PulseQobjConfig"")(meas\_level, meas\_return, ...) | A configuration for a Pulse Qobj. | | [`QobjMeasurementOption`](qiskit.qobj.QobjMeasurementOption ""qiskit.qobj.QobjMeasurementOption"")(name\[, params]) | An individual measurement option. | | [`PulseLibraryItem`](qiskit.qobj.PulseLibraryItem ""qiskit.qobj.PulseLibraryItem"")(name, samples) | An item in a pulse library. | ",repo/docs/api/qiskit/1.0\qobj.mdx "--- title: qpy description: API reference for qiskit.qpy in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.qpy --- # QPY serialization `qiskit.qpy` QPY is a binary serialization format for [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") and [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") objects that is designed to be cross-platform, Python version agnostic, and backwards compatible moving forward. QPY should be used if you need a mechanism to save or copy between systems a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") or [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") that preserves the full Qiskit object structure (except for custom attributes defined outside of Qiskit code). This differs from other serialization formats like [OpenQASM](https://github.com/openqasm/openqasm) (2.0 or 3.0) which has a different abstraction model and can result in a loss of information contained in the original circuit (or is unable to represent some aspects of the Qiskit objects) or Python’s [pickle](https://docs.python.org/3/library/pickle.html) which will preserve the Qiskit object exactly but will only work for a single Qiskit version (it is also [potentially insecure](https://docs.python.org/3/library/pickle.html#module-pickle)). ## Using QPY Using QPY is defined to be straightforward and mirror the user API of the serializers in Python’s standard library, `pickle` and `json`. There are 2 user facing functions: [`qiskit.qpy.dump()`](#qiskit.qpy.dump ""qiskit.qpy.dump"") and [`qiskit.qpy.load()`](#qiskit.qpy.load ""qiskit.qpy.load"") which are used to dump QPY data to a file object and load circuits from QPY data in a file object respectively. For example: ```python from qiskit.circuit import QuantumCircuit from qiskit import qpy qc = QuantumCircuit(2, name='Bell', metadata={'test': True}) qc.h(0) qc.cx(0, 1) qc.measure_all() with open('bell.qpy', 'wb') as fd: qpy.dump(qc, fd) with open('bell.qpy', 'rb') as fd: new_qc = qpy.load(fd)[0] ``` The [`qiskit.qpy.dump()`](#qiskit.qpy.dump ""qiskit.qpy.dump"") function also lets you include multiple circuits in a single QPY file: ```python with open('twenty_bells.qpy', 'wb') as fd: qpy.dump([qc] * 20, fd) ``` and then loading that file will return a list with all the circuits > **with open(‘twenty\_bells.qpy’, ‘rb’) as fd:** > > twenty\_new\_bells = qpy.load(fd) ### API documentation #### load Load a QPY binary file This function is used to load a serialized QPY Qiskit program file and create [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") objects or [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"") objects from its contents. For example: ```python from qiskit import qpy with open('bell.qpy', 'rb') as fd: circuits = qpy.load(fd) ``` or with a gzip compressed file: ```python import gzip from qiskit import qpy with gzip.open('bell.qpy.gz', 'rb') as fd: circuits = qpy.load(fd) ``` which will read the contents of the qpy and return a list of [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") objects or [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"") objects from the file. **Parameters** * **file\_obj** ([*BinaryIO*](https://docs.python.org/3/library/typing.html#typing.BinaryIO ""(in Python v3.12)"")) – A file like object that contains the QPY binary data for a circuit or pulse schedule. * **metadata\_deserializer** ([*Type*](https://docs.python.org/3/library/typing.html#typing.Type ""(in Python v3.12)"")*\[JSONDecoder] | None*) – An optional JSONDecoder class that will be used for the `cls` kwarg on the internal `json.load` call used to deserialize the JSON payload used for the `.metadata` attribute for any programs in the QPY file. If this is not specified the circuit metadata will be parsed as JSON with the stdlib `json.load()` function using the default `JSONDecoder` class. **Returns** The list of Qiskit programs contained in the QPY data. A list is always returned, even if there is only 1 program in the QPY data. **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if `file_obj` is not a valid QPY file * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – When invalid data type is loaded. **Return type** [*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")\[[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") | [*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"")] #### dump Write QPY binary data to a file This function is used to save a circuit to a file for later use or transfer between machines. The QPY format is backwards compatible and can be loaded with future versions of Qiskit. For example: ```python from qiskit.circuit import QuantumCircuit from qiskit import qpy qc = QuantumCircuit(2, name='Bell', metadata={'test': True}) qc.h(0) qc.cx(0, 1) qc.measure_all() ``` from this you can write the qpy data to a file: ```python with open('bell.qpy', 'wb') as fd: qpy.dump(qc, fd) ``` or a gzip compressed file: ```python import gzip with gzip.open('bell.qpy.gz', 'wb') as fd: qpy.dump(qc, fd) ``` Which will save the qpy serialized circuit to the provided file. **Parameters** * **programs** ([*List*](https://docs.python.org/3/library/typing.html#typing.List ""(in Python v3.12)"")*\[*[*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") *|*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"")*] |* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") *|*[*ScheduleBlock*](qiskit.pulse.ScheduleBlock ""qiskit.pulse.schedule.ScheduleBlock"")) – QPY supported object(s) to store in the specified file like object. QPY supports [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") and [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock""). Different data types must be separately serialized. * **file\_obj** ([*BinaryIO*](https://docs.python.org/3/library/typing.html#typing.BinaryIO ""(in Python v3.12)"")) – The file like object to write the QPY data too * **metadata\_serializer** ([*Type*](https://docs.python.org/3/library/typing.html#typing.Type ""(in Python v3.12)"")*\[JSONEncoder] | None*) – An optional JSONEncoder class that will be passed the `.metadata` attribute for each program in `programs` and will be used as the `cls` kwarg on the json.dump()\` call to JSON serialize that dictionary. * **use\_symengine** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True, all objects containing symbolic expressions will be serialized using symengine’s native mechanism. This is a faster serialization alternative, but not supported in all platforms. Please check that your target platform is supported by the symengine library before setting this option, as it will be required by qpy to deserialize the payload. For this reason, the option defaults to False. * **version** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The QPY format version to emit. By default this defaults to the latest supported format of [`QPY_VERSION`](#qiskit.qpy.QPY_VERSION ""qiskit.qpy.QPY_VERSION""), however for compatibility reasons if you need to load the generated QPY payload with an older version of Qiskit you can also select an older QPY format version down to the minimum supported export version, which only can change during a Qiskit major version release, to generate an older QPY format version. You can access the current QPY version and minimum compatible version with [`qpy.QPY_VERSION`](#qiskit.qpy.QPY_VERSION ""qiskit.qpy.QPY_VERSION"") and [`qpy.QPY_COMPATIBILITY_VERSION`](#qiskit.qpy.QPY_COMPATIBILITY_VERSION ""qiskit.qpy.QPY_COMPATIBILITY_VERSION"") respectively. If specified with an older version of QPY the limitations and potential bugs stemming from the QPY format at that version will persist. This should only be used if compatibility with loading the payload with an older version of Qiskit is necessary. **Raises** * [**QpyError**](#qiskit.qpy.QpyError ""qiskit.qpy.QpyError"") – When multiple data format is mixed in the output. * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError ""(in Python v3.12)"") – When invalid data type is input. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – When an unsupported version number is passed in for the `version` argument These functions will raise a custom subclass of [`QiskitError`](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") if they encounter problems during serialization or deserialization. #### QpyError Errors raised by the qpy module. Set the error message. #### qiskit.qpy.QPY\_VERSION The current QPY format version as of this release. This is the default value of the `version` keyword argument on [`qpy.dump()`](#qiskit.qpy.dump ""qiskit.qpy.dump"") and also the upper bound for accepted values for the same argument. This is also the upper bond on the versions supported by [`qpy.load()`](#qiskit.qpy.load ""qiskit.qpy.load""). **Type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") #### qiskit.qpy.QPY\_COMPATIBILITY\_VERSION The current minimum compatibility QPY format version. This is the minimum version that [`qpy.dump()`](#qiskit.qpy.dump ""qiskit.qpy.dump"") will accept for the `version` keyword argument. [`qpy.load()`](#qiskit.qpy.load ""qiskit.qpy.load"") will be able to load all released format versions of QPY (up until `QPY_VERSION`). **Type** [int](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") ### QPY Compatibility The QPY format is designed to be backwards compatible moving forward. This means you should be able to load a QPY with any newer Qiskit version than the one that generated it. However, loading a QPY file with an older Qiskit version is not supported and may not work. For example, if you generated a QPY file using qiskit-terra 0.18.1 you could load that QPY file with qiskit-terra 0.19.0 and a hypothetical qiskit-terra 0.29.0. However, loading that QPY file with 0.18.0 is not supported and may not work. If a feature being loaded is deprecated in the corresponding qiskit release, QPY will raise a [`QPYLoadingDeprecatedFeatureWarning`](#qiskit.qpy.QPYLoadingDeprecatedFeatureWarning ""qiskit.qpy.QPYLoadingDeprecatedFeatureWarning"") informing of the deprecation period and how the feature will be internally handled. #### QPYLoadingDeprecatedFeatureWarning Visible deprecation warning for QPY loading functions without a stable point in the call stack. ## QPY Format The QPY serialization format is a portable cross-platform binary serialization format for [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") objects in Qiskit. The basic file format is as follows: A QPY file (or memory object) always starts with the following 6 byte UTF8 string: `QISKIT` which is immediately followed by the overall file header. The contents of the file header as defined as a C struct are: ```python struct { uint8_t qpy_version; uint8_t qiskit_major_version; uint8_t qiskit_minor_version; uint8_t qiskit_patch_version; uint64_t num_circuits; } ``` From V10 on, a new field is added to the file header struct to represent the encoding scheme used for symbolic expressions: ```python struct { uint8_t qpy_version; uint8_t qiskit_major_version; uint8_t qiskit_minor_version; uint8_t qiskit_patch_version; uint64_t num_circuits; char symbolic_encoding; } ``` All values use network byte order [\[1\]](#f1) (big endian) for cross platform compatibility. The file header is immediately followed by the circuit payloads. Each individual circuit is composed of the following parts: `HEADER | METADATA | REGISTERS | CUSTOM_DEFINITIONS | INSTRUCTIONS` There is a circuit payload for each circuit (where the total number is dictated by `num_circuits` in the file header). There is no padding between the circuits in the data. ### Version 11 Version 11 is identical to Version 10 except for the following. First, the names in the CUSTOM\_INSTRUCTION blocks have a suffix of the form `""_{uuid_hex}""` where `uuid_hex` is a uuid hexadecimal string such as returned by `UUID.hex`. For example: `""b3ecab5b4d6a4eb6bc2b2dbf18d83e1e""`. Second, it adds support for [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation"") objects. The base operation of an annotated operation is stored using the INSTRUCTION block, and an additional `type` value `'a'``is added to indicate that the custom instruction is an annotated operation. The list of modifiers are stored as instruction parameters using INSTRUCTION_PARAM, with an additional value ``'m'` is added to indicate that the parameter is of type `Modifier`. Each modifier is stored using the MODIFIER struct. #### MODIFIER This represents `Modifier` ```python struct { char type; uint32_t num_ctrl_qubits; uint32_t ctrl_state; double power; } ``` This is sufficient to store different types of modifiers required for serializing objects of type [`AnnotatedOperation`](qiskit.circuit.AnnotatedOperation ""qiskit.circuit.AnnotatedOperation""). The field `type` is either `'i'`, `'c'` or `'p'`, representing whether the modifier is respectively an inverse modifier, a control modifier or a power modifier. In the second case, the fields `num_ctrl_qubits` and `ctrl_state` specify the control logic of the base operation, and in the third case the field `power` represents the power of the base operation. ### Version 10 Version 10 adds support for symengine-native serialization for objects of type [`ParameterExpression`](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") as well as symbolic expressions in Pulse schedule blocks. Version 10 also adds support for new fields in the [`TranspileLayout`](qiskit.transpiler.TranspileLayout ""qiskit.transpiler.TranspileLayout"") class added in the Qiskit 0.45.0 release. The symbolic\_encoding field is added to the file header, and a new encoding type char is introduced, mapped to each symbolic library as follows: `p` refers to sympy encoding and `e` refers to symengine encoding. #### FILE\_HEADER The contents of FILE\_HEADER after V10 are defined as a C struct as: ```python struct { uint8_t qpy_version; uint8_t qiskit_major_version; uint8_t qiskit_minor_version; uint8_t qiskit_patch_version; uint64_t num_circuits; char symbolic_encoding; } ``` #### LAYOUT The `LAYOUT` struct is updated to have an additional `input_qubit_count` field. With version 10 the `LAYOUT` struct is now: ```python struct { char exists; int32_t initial_layout_size; int32_t input_mapping_size; int32_t final_layout_size; uint32_t extra_registers; int32_t input_qubit_count; } ``` The rest of the layout data after the `LAYOUT` struct is represented as in previous versions. If `input qubit_count` is \< 0 that indicates that both `_input_qubit_count` and `_output_qubit_list` in the [`TranspileLayout`](qiskit.transpiler.TranspileLayout ""qiskit.transpiler.TranspileLayout"") object are `None`. ### Version 9 Version 9 adds support for classical [`Expr`](circuit_classical#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.Expr"") nodes and their associated [`Type`](circuit_classical#qiskit.circuit.classical.types.Type ""qiskit.circuit.classical.types.Type"")s. #### EXPRESSION An [`Expr`](circuit_classical#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.Expr"") node is represented by a stream of variable-width data. A node itself is represented by (in order in the byte stream): 1. a one-byte type code discriminator; 2. an EXPR\_TYPE object; 3. a type-code-specific additional payload; 4. a type-code-specific number of child EXPRESSION payloads (the number of these is implied by the type code and not explicitly stored). Each of these are described in the following table: | Qiskit class | Type code | Payload | Children | | --------------------------------------------------------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | [`Var`](circuit_classical#qiskit.circuit.classical.expr.Var ""qiskit.circuit.classical.expr.Var"") | `x` | One EXPR\_VAR. | 0 | | [`Value`](circuit_classical#qiskit.circuit.classical.expr.Value ""qiskit.circuit.classical.expr.Value"") | `v` | One EXPR\_VALUE. | 0 | | [`Cast`](circuit_classical#qiskit.circuit.classical.expr.Cast ""qiskit.circuit.classical.expr.Cast"") | `c` | One `_Bool` that corresponds to the value of `implicit`. | 1 | | [`Unary`](circuit_classical#qiskit.circuit.classical.expr.Unary ""qiskit.circuit.classical.expr.Unary"") | `u` | One `uint8_t` with the same numeric value as the [`Unary.Op`](circuit_classical#qiskit.circuit.classical.expr.Unary.Op ""qiskit.circuit.classical.expr.Unary.Op""). | 1 | | [`Binary`](circuit_classical#qiskit.circuit.classical.expr.Binary ""qiskit.circuit.classical.expr.Binary"") | `b` | One `uint8_t` with the same numeric value as the [`Binary.Op`](circuit_classical#qiskit.circuit.classical.expr.Binary.Op ""qiskit.circuit.classical.expr.Binary.Op""). | 2 | #### EXPR\_TYPE A [`Type`](circuit_classical#qiskit.circuit.classical.types.Type ""qiskit.circuit.classical.types.Type"") is encoded by a single-byte ASCII `char` that encodes the kind of type, followed by a payload that varies depending on the type. The defined codes are: | Qiskit class | Type code | Payload | | ----------------------------------------------------------------------------------------------------- | --------- | --------------------- | | [`Bool`](circuit_classical#qiskit.circuit.classical.types.Bool ""qiskit.circuit.classical.types.Bool"") | `b` | None. | | [`Uint`](circuit_classical#qiskit.circuit.classical.types.Uint ""qiskit.circuit.classical.types.Uint"") | `u` | One `uint32_t width`. | #### EXPR\_VAR This represents a runtime variable of a [`Var`](circuit_classical#qiskit.circuit.classical.expr.Var ""qiskit.circuit.classical.expr.Var"") node. These are a type code, followed by a type-code-specific payload: | Python class | Type code | Payload | | ------------------------------------------------------------------------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------- | | [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"") | `C` | One `uint32_t index` that is the index of the [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"") in the containing circuit. | | [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"") | `R` | One `uint16_t reg_name_size`, followed by that many bytes of UTF-8 string data of the register name. | #### EXPR\_VALUE This represents a literal object in the classical type system, such as an integer. Currently there are very few such literals. These are encoded as a type code, followed by a type-code-specific payload. | Python type | Type code | Payload | | ----------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `bool` | `b` | One `_Bool value`. | | `int` | `i` | One `uint8_t num_bytes`, followed by the integer encoded into that many many bytes (network order) in a two’s complement representation. | #### Changes to INSTRUCTION To support the use of [`Expr`](circuit_classical#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.Expr"") nodes in the fields [`IfElseOp.condition`](qiskit.circuit.IfElseOp#condition ""qiskit.circuit.IfElseOp.condition""), [`WhileLoopOp.condition`](qiskit.circuit.WhileLoopOp#condition ""qiskit.circuit.WhileLoopOp.condition"") and `SwitchCaseOp.target`, the INSTRUCTION struct is changed in an ABI compatible-manner to [its previous definition](#qpy-instruction-v5). The new struct is the C struct: ```python struct { uint16_t name_size; uint16_t label_size; uint16_t num_parameters; uint32_t num_qargs; uint32_t num_cargs; uint8_t conditional_key; uint16_t conditional_reg_name_size; int64_t conditional_value; uint32_t num_ctrl_qubits; uint32_t ctrl_state; } ``` where the only change is that a `uint8_t conditional_key` entry has replaced `_Bool has_conditional`. This new `conditional_key` takes the following numeric values, with these effects: | Value | Effects | | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 0 | The instruction has its `.condition` field set to `None`. The `conditional_reg_name_size` and `conditional_value` fields should be ignored. | | 1 | The instruction has its `.condition` field set to a 2-tuple of either a [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"") or a [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister""), and a integer of value `conditional_value`. The INSTRUCTION payload, including its trailing data is parsed exactly as it would be in QPY versions less than 8. | | 2 | The instruction has its `.condition` field set to a [`Expr`](circuit_classical#qiskit.circuit.classical.expr.Expr ""qiskit.circuit.classical.expr.Expr"") node. The `conditional_reg_name_size` and `conditional_value` fields should be ignored. The data following the struct is followed (as in QPY versions less than 8) by `name_size` bytes of UTF-8 string data for the class name and `label_size` bytes of UTF-8 string data for the label (if any). Then, there is one INSTRUCTION\_PARAM, which will contain an EXPRESSION. After that, parsing continues with the INSTRUCTION\_ARG structs, as in previous versions of QPY. | #### Changes to INSTRUCTION\_PARAM A new type code `x` is added that defines an EXPRESSION parameter. ### Version 8 Version 8 adds support for handling a [`TranspileLayout`](qiskit.transpiler.TranspileLayout ""qiskit.transpiler.TranspileLayout"") stored in the [`QuantumCircuit.layout`](qiskit.circuit.QuantumCircuit#layout ""qiskit.circuit.QuantumCircuit.layout"") attribute. In version 8 immediately following the calibrations block at the end of the circuit payload there is now the `LAYOUT` struct. This struct outlines the size of the three attributes of a [`TranspileLayout`](qiskit.transpiler.TranspileLayout ""qiskit.transpiler.TranspileLayout"") class. #### LAYOUT ```python struct { char exists; int32_t initial_layout_size; int32_t input_mapping_size; int32_t final_layout_size; uint32_t extra_registers; } ``` If any of the signed values are `-1` this indicates the corresponding attribute is `None`. Immediately following the `LAYOUT` struct there is a [REGISTERS](#qpy-registers) struct for `extra_registers` (specifically the format introduced in [Version 4](#qpy-version-4)) standalone register definitions that aren’t present in the circuit. Then there are `initial_layout_size` `INITIAL_LAYOUT_BIT` structs to define the [`TranspileLayout.initial_layout`](qiskit.transpiler.TranspileLayout#initial_layout ""qiskit.transpiler.TranspileLayout.initial_layout"") attribute. #### INITIAL\_LAYOUT\_BIT ```python struct { int32_t index; int32_t register_size; } ``` Where a value of `-1` indicates `None` (as in no register is associated with the bit). Following each `INITIAL_LAYOUT_BIT` struct is `register_size` bytes for a `utf8` encoded string for the register name. Following the initial layout there is `input_mapping_size` array of `uint32_t` integers representing the positions of the physical bit from the initial layout. This enables constructing a list of virtual bits where the array index is its input mapping position. Finally, there is an array of `final_layout_size` `uint32_t` integers. Each element is an index in the circuit’s `qubits` attribute which enables building a mapping from qubit starting position to the output position at the end of the circuit. ### Version 7 Version 7 adds support for `Reference` instruction and serialization of a `ScheduleBlock` program while keeping its reference to subroutines: ```python from qiskit import pulse from qiskit import qpy with pulse.build() as schedule: pulse.reference(""cr45p"", ""q0"", ""q1"") pulse.reference(""x"", ""q0"") pulse.reference(""cr45p"", ""q0"", ""q1"") with open('template_ecr.qpy', 'wb') as fd: qpy.dump(schedule, fd) ``` The conventional [SCHEDULE\_BLOCK](#qpy-schedule-block) data model is preserved, but in version 7 it is immediately followed by an extra [MAPPING](#qpy-mapping) utf8 bytes block representing the data of the referenced subroutines. New type key character is added to the [SCHEDULE\_BLOCK\_INSTRUCTIONS](#qpy-schedule-instructions) group for the `Reference` instruction. * `y`: [`Reference`](qiskit.pulse.instructions.Reference ""qiskit.pulse.instructions.Reference"") instruction New type key character is added to the [SCHEDULE\_BLOCK\_OPERANDS](#qpy-schedule-operands) group for the operands of `Reference` instruction, which is a tuple of strings, e.g. (“cr45p”, “q0”, “q1”). * `o`: string (operand string) Note that this is the same encoding with the built-in Python string, however, the standard value encoding in QPY uses `s` type character for string data, which conflicts with the [`SymbolicPulse`](qiskit.pulse.library.SymbolicPulse ""qiskit.pulse.library.SymbolicPulse"") in the scope of pulse instruction operands. A special type character `o` is reserved for the string data that appears in the pulse instruction operands. In addition, version 7 adds two new type keys to the INSTRUCTION\_PARM struct. `""d""` is followed by no data and represents the literal value [`CASE_DEFAULT`](circuit#qiskit.circuit.CASE_DEFAULT ""qiskit.circuit.CASE_DEFAULT"") for switch-statement support. `""R""` represents a [`ClassicalRegister`](qiskit.circuit.ClassicalRegister ""qiskit.circuit.ClassicalRegister"") or [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit""), and is followed by the same format as the description of register or classical bit as used in the first element of [the condition of an INSTRUCTION field](#qpy-instructions). ### Version 6 Version 6 adds support for `ScalableSymbolicPulse`. These objects are saved and read like SymbolicPulse objects, and the class name is added to the data to correctly handle the class selection. SymbolicPulse block now starts with SYMBOLIC\_PULSE\_V2 header: ```python struct { uint16_t class_name_size; uint16_t type_size; uint16_t envelope_size; uint16_t constraints_size; uint16_t valid_amp_conditions_size; _bool amp_limited; } ``` The only change compared to [Version 5](#qpy-version-5) is the addition of class\_name\_size. The header is then immediately followed by `class_name_size` utf8 bytes with the name of the class. Currently, either SymbolicPulse or ScalableSymbolicPulse are supported. The rest of the data is then identical to [Version 5](#qpy-version-5). ### Version 5 Version 5 changes from [Version 4](#qpy-version-4) by adding support for `ScheduleBlock` and changing two payloads the INSTRUCTION metadata payload and the CUSTOM\_INSTRUCTION block. These now have new fields to better account for [`ControlledGate`](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") objects in a circuit. In addition, new payload MAP\_ITEM is defined to implement the [MAPPING](#qpy-mapping) block. With the support of `ScheduleBlock`, now [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") can be serialized together with [`calibrations`](qiskit.circuit.QuantumCircuit#calibrations ""qiskit.circuit.QuantumCircuit.calibrations""), or [Pulse Gates](/build/pulse). In QPY version 5 and above, [CIRCUIT\_CALIBRATIONS](#qpy-circuit-calibrations) payload is packed after the [INSTRUCTIONS](#qpy-instructions) block. In QPY version 5 and above, ```python struct { char type; } ``` immediately follows the file header block to represent the program type stored in the file. * When `type==c`, [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") payload follows * When `type==s`, [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") payload follows Different programs cannot be packed together in the same file. You must create different files for different program types. Multiple objects with the same type can be saved in a single file. #### SCHEDULE\_BLOCK [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") is first supported in QPY Version 5. This allows users to save pulse programs in the QPY binary format as follows: ```python from qiskit import pulse, qpy with pulse.build() as schedule: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) with open('schedule.qpy', 'wb') as fd: qpy.dump(qc, fd) with open('schedule.qpy', 'rb') as fd: new_qc = qpy.load(fd)[0] ``` Note that circuit and schedule block are serialized and deserialized through the same QPY interface. Input data type is implicitly analyzed and no extra option is required to save the schedule block. #### SCHEDULE\_BLOCK\_HEADER [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") block starts with the following header: ```python struct { uint16_t name_size; uint64_t metadata_size; uint16_t num_element; } ``` which is immediately followed by `name_size` utf8 bytes of schedule name and `metadata_size` utf8 bytes of the JSON serialized metadata dictionary attached to the schedule. #### SCHEDULE\_BLOCK\_ALIGNMENTS Then, alignment context of the schedule block starts with `char` representing the supported context type followed by the [SEQUENCE](#qpy-sequence) block representing the parameters associated with the alignment context `AlignmentKind._context_params`. The context type char is mapped to each alignment subclass as follows: * `l`: [`AlignLeft`](qiskit.pulse.transforms.AlignLeft ""qiskit.pulse.transforms.AlignLeft"") * `r`: [`AlignRight`](qiskit.pulse.transforms.AlignRight ""qiskit.pulse.transforms.AlignRight"") * `s`: [`AlignSequential`](qiskit.pulse.transforms.AlignSequential ""qiskit.pulse.transforms.AlignSequential"") * `e`: [`AlignEquispaced`](qiskit.pulse.transforms.AlignEquispaced ""qiskit.pulse.transforms.AlignEquispaced"") Note that [`AlignFunc`](qiskit.pulse.transforms.AlignFunc ""qiskit.pulse.transforms.AlignFunc"") context is not supported because of the callback function stored in the context parameters. #### SCHEDULE\_BLOCK\_INSTRUCTIONS This alignment block is further followed by `num_element` length of block elements which may consist of nested schedule blocks and schedule instructions. Each schedule instruction starts with `char` representing the instruction type followed by the [SEQUENCE](#qpy-sequence) block representing the instruction `operands`. Note that the data structure of pulse [`Instruction`](pulse#qiskit.pulse.instructions.Instruction ""qiskit.pulse.instructions.Instruction"") is unified so that instance can be uniquely determined by the class and a tuple of operands. The mapping of type char to the instruction subclass is defined as follows: * `a`: [`Acquire`](qiskit.pulse.instructions.Acquire ""qiskit.pulse.instructions.Acquire"") instruction * `p`: [`Play`](qiskit.pulse.instructions.Play ""qiskit.pulse.instructions.Play"") instruction * `d`: [`Delay`](qiskit.pulse.instructions.Delay ""qiskit.pulse.instructions.Delay"") instruction * `f`: [`SetFrequency`](qiskit.pulse.instructions.SetFrequency ""qiskit.pulse.instructions.SetFrequency"") instruction * `g`: [`ShiftFrequency`](qiskit.pulse.instructions.ShiftFrequency ""qiskit.pulse.instructions.ShiftFrequency"") instruction * `q`: [`SetPhase`](qiskit.pulse.instructions.SetPhase ""qiskit.pulse.instructions.SetPhase"") instruction * `r`: [`ShiftPhase`](qiskit.pulse.instructions.ShiftPhase ""qiskit.pulse.instructions.ShiftPhase"") instruction * `b`: [`RelativeBarrier`](qiskit.pulse.instructions.RelativeBarrier ""qiskit.pulse.instructions.RelativeBarrier"") instruction * `t`: [`TimeBlockade`](qiskit.pulse.instructions.TimeBlockade ""qiskit.pulse.instructions.TimeBlockade"") instruction * `y`: [`Reference`](qiskit.pulse.instructions.Reference ""qiskit.pulse.instructions.Reference"") instruction (new in version 0.7) #### SCHEDULE\_BLOCK\_OPERANDS The operands of these instances can be serialized through the standard QPY value serialization mechanism, however there are special object types that only appear in the schedule operands. Since the operands are serialized as [SEQUENCE](#qpy-sequence), each element must be packed with the INSTRUCTION\_PARAM pack struct, where each payload starts with a header block consists of the char `type` and uint64\_t `size`. Special objects start with the following type key: * `c`: [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") * `w`: [`Waveform`](qiskit.pulse.library.Waveform ""qiskit.pulse.library.Waveform"") * `s`: [`SymbolicPulse`](qiskit.pulse.library.SymbolicPulse ""qiskit.pulse.library.SymbolicPulse"") * `o`: string (operand string, new in version 0.7) #### CHANNEL Channel block starts with channel subtype `char` that maps an object data to [`Channel`](pulse#qiskit.pulse.channels.Channel ""qiskit.pulse.channels.Channel"") subclass. Mapping is defined as follows: * `d`: [`DriveChannel`](qiskit.pulse.channels.DriveChannel ""qiskit.pulse.channels.DriveChannel"") * `c`: [`ControlChannel`](qiskit.pulse.channels.ControlChannel ""qiskit.pulse.channels.ControlChannel"") * `m`: [`MeasureChannel`](qiskit.pulse.channels.MeasureChannel ""qiskit.pulse.channels.MeasureChannel"") * `a`: [`AcquireChannel`](qiskit.pulse.channels.AcquireChannel ""qiskit.pulse.channels.AcquireChannel"") * `e`: [`MemorySlot`](qiskit.pulse.channels.MemorySlot ""qiskit.pulse.channels.MemorySlot"") * `r`: [`RegisterSlot`](qiskit.pulse.channels.RegisterSlot ""qiskit.pulse.channels.RegisterSlot"") The key is immediately followed by the channel index serialized as the INSTRUCTION\_PARAM. #### Waveform Waveform block starts with WAVEFORM header: ```python struct { double epsilon; uint32_t data_size; _bool amp_limited; } ``` which is followed by `data_size` bytes of complex `ndarray` binary generated by [numpy.save](https://numpy.org/doc/stable/reference/generated/numpy.save.html). This represents the complex IQ data points played on a quantum device. [`name`](qiskit.pulse.library.Waveform#name ""qiskit.pulse.library.Waveform.name"") is saved after the samples in the INSTRUCTION\_PARAM pack struct, which can be string or `None`. #### SymbolicPulse SymbolicPulse block starts with SYMBOLIC\_PULSE header: ```python struct { uint16_t type_size; uint16_t envelope_size; uint16_t constraints_size; uint16_t valid_amp_conditions_size; _bool amp_limited; } ``` which is followed by `type_size` utf8 bytes of [`SymbolicPulse.pulse_type`](qiskit.pulse.library.SymbolicPulse#pulse_type ""qiskit.pulse.library.SymbolicPulse.pulse_type"") string that represents a class of waveform, such as “Gaussian” or “GaussianSquare”. Then, `envelope_size`, `constraints_size`, `valid_amp_conditions_size` utf8 bytes of serialized symbolic expressions are generated for [`SymbolicPulse.envelope`](qiskit.pulse.library.SymbolicPulse#envelope ""qiskit.pulse.library.SymbolicPulse.envelope""), [`SymbolicPulse.constraints`](qiskit.pulse.library.SymbolicPulse#constraints ""qiskit.pulse.library.SymbolicPulse.constraints""), and [`SymbolicPulse.valid_amp_conditions`](qiskit.pulse.library.SymbolicPulse#valid_amp_conditions ""qiskit.pulse.library.SymbolicPulse.valid_amp_conditions""), respectively. Since string representation of these expressions are usually lengthy, the expression binary is generated by the python [zlib](https://docs.python.org/3/library/zlib.html) module with data compression. To uniquely specify a pulse instance, we also need to store the associated parameters, which consist of `duration` and the rest of parameters as a dictionary. Dictionary parameters are first dumped in the [MAPPING](#qpy-mapping) form, and then `duration` is dumped with the INSTRUCTION\_PARAM pack struct. Lastly, [`name`](qiskit.pulse.library.SymbolicPulse#name ""qiskit.pulse.library.SymbolicPulse.name"") is saved also with the INSTRUCTION\_PARAM pack struct, which can be string or `None`. #### MAPPING The MAPPING is a representation for arbitrary mapping object. This is a fixed length [SEQUENCE](#qpy-sequence) of key-value pair represented by the MAP\_ITEM payload. A MAP\_ITEM starts with a header defined as: ```python struct { uint16_t key_size; char type; uint16_t size; } ``` which is immediately followed by the `key_size` utf8 bytes representing the dictionary key in string and `size` utf8 bytes of arbitrary object data of QPY serializable `type`. #### CIRCUIT\_CALIBRATIONS The CIRCUIT\_CALIBRATIONS block is a dictionary to define pulse calibrations of the custom instruction set. This block starts with the following CALIBRATION header: ```python struct { uint16_t num_cals; } ``` which is followed by the `num_cals` length of calibration entries, each starts with the CALIBRATION\_DEF header: ```python struct { uint16_t name_size; uint16_t num_qubits; uint16_t num_params; char type; } ``` The calibration definition header is then followed by `name_size` utf8 bytes of the gate name, `num_qubits` length of integers representing a sequence of qubits, and `num_params` length of INSTRUCTION\_PARAM payload for parameters associated to the custom instruction. The `type` indicates the class of pulse program which is either, in principle, [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") or [`Schedule`](qiskit.pulse.Schedule ""qiskit.pulse.Schedule""). As of QPY Version 5, only [`ScheduleBlock`](qiskit.pulse.ScheduleBlock ""qiskit.pulse.ScheduleBlock"") payload is supported. Finally, [SCHEDULE\_BLOCK](#qpy-schedule-block) payload is packed for each CALIBRATION\_DEF entry. #### INSTRUCTION The INSTRUCTION block was modified to add two new fields `num_ctrl_qubits` and `ctrl_state` which are used to model the [`ControlledGate.num_ctrl_qubits`](qiskit.circuit.ControlledGate#num_ctrl_qubits ""qiskit.circuit.ControlledGate.num_ctrl_qubits"") and [`ControlledGate.ctrl_state`](qiskit.circuit.ControlledGate#ctrl_state ""qiskit.circuit.ControlledGate.ctrl_state"") attributes. The new payload packed struct format is: ```python struct { uint16_t name_size; uint16_t label_size; uint16_t num_parameters; uint32_t num_qargs; uint32_t num_cargs; _Bool has_conditional; uint16_t conditional_reg_name_size; int64_t conditional_value; uint32_t num_ctrl_qubits; uint32_t ctrl_state; } ``` The rest of the instruction payload is the same. You can refer to [INSTRUCTIONS](#qpy-instructions) for the details of the full payload. #### CUSTOM\_INSTRUCTION The CUSTOM\_INSTRUCTION block in QPY version 5 adds a new field `base_gate_size` which is used to define the size of the [`qiskit.circuit.Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") object stored in the `ControlledGate.base_gate` attribute for a custom [`ControlledGate`](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate"") object. With this change the CUSTOM\_INSTRUCTION metadata block becomes: ```python struct { uint16_t name_size; char type; uint32_t num_qubits; uint32_t num_clbits; _Bool custom_definition; uint64_t size; uint32_t num_ctrl_qubits; uint32_t ctrl_state; uint64_t base_gate_size } ``` Immediately following the CUSTOM\_INSTRUCTION struct is the utf8 encoded name of size `name_size`. If `custom_definition` is `True` that means that the immediately following `size` bytes contains a QPY circuit data which can be used for the custom definition of that gate. If `custom_definition` is `False` then the instruction can be considered opaque (ie no definition). The `type` field determines what type of object will get created with the custom definition. If it’s `'g'` it will be a [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") object, `'i'` it will be a [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") object. Following this the next `base_gate_size` bytes contain the `INSTRUCTION` payload for the `ControlledGate.base_gate`. Additionally an addition value for `type` is added `'c'` which is used to indicate the custom instruction is a custom [`ControlledGate`](qiskit.circuit.ControlledGate ""qiskit.circuit.ControlledGate""). ### Version 4 Version 4 is identical to [Version 3](#qpy-version-3) except that it adds 2 new type strings to the INSTRUCTION\_PARAM struct, `z` to represent `None` (which is encoded as no data), `q` to represent a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") (which is encoded as a QPY circuit), `r` to represent a `range` of integers (which is encoded as a [RANGE](#qpy-range-pack)), and `t` to represent a `sequence` (which is encoded as defined by [SEQUENCE](#qpy-sequence)). Additionally, version 4 changes the type of register index mapping array from `uint32_t` to `int64_t`. If the values of any of the array elements are negative they represent a register bit that is not present in the circuit. The [REGISTERS](#qpy-registers) header format has also been updated to ```python struct { char type; _Bool standalone; uint32_t size; uint16_t name_size; _bool in_circuit; } ``` which just adds the `in_circuit` field which represents whether the register is part of the circuit or not. #### RANGE A RANGE is a representation of a `range` object. It is defined as: ```python struct { int64_t start; int64_t stop; int64_t step; } ``` #### SEQUENCE A SEQUENCE is a representation of an arbitrary sequence object. As sequence are just fixed length containers of arbitrary python objects their QPY can’t fully represent any sequence, but as long as the contents in a sequence are other QPY serializable types for the INSTRUCTION\_PARAM payload the `sequence` object can be serialized. A sequence instruction parameter starts with a header defined as: ```python struct { uint64_t size; } ``` followed by `size` elements that are INSTRUCTION\_PARAM payloads, where each of these define an element in the sequence. The sequence object will be typecasted into proper type, e.g. `tuple`, afterwards. ### Version 3 Version 3 of the QPY format is identical to [Version 2](#qpy-version-2) except that it defines a struct format to represent a [`PauliEvolutionGate`](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate"") natively in QPY. To accomplish this the [CUSTOM\_DEFINITIONS](#qpy-custom-definition) struct now supports a new type value `'p'` to represent a [`PauliEvolutionGate`](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate""). Enties in the custom instructions tables have unique name generated that start with the string `""###PauliEvolutionGate_""` followed by a uuid string. This gate name is reservered in QPY and if you have a custom [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") object with a definition set and that name prefix it will error. If it’s of type `'p'` the data payload is defined as follows: #### PAULI\_EVOLUTION This represents the high level [`PauliEvolutionGate`](qiskit.circuit.library.PauliEvolutionGate ""qiskit.circuit.library.PauliEvolutionGate"") ```python struct { uint64_t operator_count; _Bool standalone_op; char time_type; uint64_t time_size; uint64_t synthesis_size; } ``` This is immediately followed by `operator_count` elements defined by the [SPARSE\_PAULI\_OP\_LIST\_ELEM](#qpy-pauli-sum-op) payload. Following that we have `time_size` bytes representing the `time` attribute. If `standalone_op` is `True` then there must only be a single operator. The encoding of these bytes is determined by the value of `time_type`. Possible values of `time_type` are `'f'`, `'p'`, and `'e'`. If `time_type` is `'f'` it’s a double, `'p'` defines a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") object which is represented by a [PARAMETER](#qpy-param-struct), `e` defines a [`ParameterExpression`](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") object (that’s not a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")) which is represented by a [PARAMETER\_EXPR](#qpy-param-expr). Following that is `synthesis_size` bytes which is a utf8 encoded json payload representing the [`EvolutionSynthesis`](qiskit.synthesis.EvolutionSynthesis ""qiskit.synthesis.EvolutionSynthesis"") class used by the gate. #### SPARSE\_PAULI\_OP\_LIST\_ELEM This represents an instance of [`SparsePauliOp`](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp""). ```python struct { uint32_t pauli_op_size; } ``` which is immediately followed by `pauli_op_size` bytes which are .npy format [\[2\]](#f2) data which represents the [`SparsePauliOp`](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp""). Version 3 of the QPY format also defines a struct format to represent a `ParameterVectorElement` as a distinct subclass from a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter""). This adds a new parameter type char `'v'` to represent a `ParameterVectorElement` which is now supported as a type string value for an INSTRUCTION\_PARAM. The payload for these parameters are defined below as [PARAMETER\_VECTOR\_ELEMENT](#qpy-param-vector). #### PARAMETER\_VECTOR\_ELEMENT A PARAMETER\_VECTOR\_ELEMENT represents a `ParameterVectorElement` object the data for a INSTRUCTION\_PARAM. The contents of the PARAMETER\_VECTOR\_ELEMENT are defined as: ```python struct { uint16_t vector_name_size; uint64_t vector_size; char uuid[16]; uint64_t index; } ``` which is immediately followed by `vector_name_size` utf8 bytes representing the parameter’s vector name. #### PARAMETER\_EXPR Additionally, since QPY format version v3 distinguishes between a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") and `ParameterVectorElement` the payload for a [`ParameterExpression`](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") needs to be updated to distinguish between the types. The following is the modified payload format which is mostly identical to the format in Version 1 and [Version 2](#qpy-version-2) but just modifies the `map_elements` struct to include a symbol type field. A PARAMETER\_EXPR represents a [`ParameterExpression`](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") object that the data for an INSTRUCTION\_PARAM. The contents of a PARAMETER\_EXPR are defined as: ```python struct { uint64_t map_elements; uint64_t expr_size; } ``` Immediately following the header is `expr_size` bytes of utf8 data containing the expression string, which is the sympy srepr of the expression for the parameter expression. Following that is a symbol map which contains `map_elements` elements with the format ```python struct { char symbol_type; char type; uint64_t size; } ``` The `symbol_type` key determines the payload type of the symbol representation for the element. If it’s `p` it represents a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") and if it’s `v` it represents a `ParameterVectorElement`. The map element struct is immediately followed by the symbol map key payload, if `symbol_type` is `p` then it is followed immediately by a [PARAMETER](#qpy-param-struct) object (both the struct and utf8 name bytes) and if `symbol_type` is `v` then the struct is imediately followed by [PARAMETER\_VECTOR\_ELEMENT](#qpy-param-vector) (both the struct and utf8 name bytes). That is followed by `size` bytes for the data of the symbol. The data format is dependent on the value of `type`. If `type` is `p` then it represents a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") and size will be 0, the value will just be the same as the key. Similarly if the `type` is `v` then it represents a `ParameterVectorElement` and size will be 0 as the value will just be the same as the key. If `type` is `f` then it represents a double precision float. If `type` is `c` it represents a double precision complex, which is represented by the [COMPLEX](#qpy-complex). Finally, if type is `i` it represents an integer which is an `int64_t`. ### Version 2 Version 2 of the QPY format is identical to version 1 except for the HEADER section is slightly different. You can refer to the [Version 1](#qpy-version-1) section for the details on the rest of the payload format. #### HEADER The contents of HEADER are defined as a C struct are: ```python struct { uint16_t name_size; char global_phase_type; uint16_t global_phase_size; uint32_t num_qubits; uint32_t num_clbits; uint64_t metadata_size; uint32_t num_registers; uint64_t num_instructions; uint64_t num_custom_gates; } ``` This is immediately followed by `name_size` bytes of utf8 data for the name of the circuit. Following this is immediately `global_phase_size` bytes representing the global phase. The content of that data is dictated by the value of `global_phase_type`. If it’s `'f'` the data is a float and is the size of a `double`. If it’s `'p'` defines a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") object which is represented by a PARAM struct (see below), `e` defines a [`ParameterExpression`](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") object (that’s not a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")) which is represented by a PARAM\_EXPR struct (see below). ### Version 1 #### HEADER The contents of HEADER as defined as a C struct are: ```python struct { uint16_t name_size; double global_phase; uint32_t num_qubits; uint32_t num_clbits; uint64_t metadata_size; uint32_t num_registers; uint64_t num_instructions; uint64_t num_custom_gates; } ``` This is immediately followed by `name_size` bytes of utf8 data for the name of the circuit. #### METADATA The METADATA field is a UTF8 encoded JSON string. After reading the HEADER (which is a fixed size at the start of the QPY file) and the `name` string you then read the `metadata_size` number of bytes and parse the JSON to get the metadata for the circuit. #### REGISTERS The contents of REGISTERS is a number of REGISTER object. If num\_registers is > 0 then after reading METADATA you read that number of REGISTER structs defined as: ```python struct { char type; _Bool standalone; uint32_t size; uint16_t name_size; } ``` `type` can be `'q'` or `'c'`. Immediately following the REGISTER struct is the utf8 encoded register name of size `name_size`. After the `name` utf8 bytes there is then an array of int64\_t values of size `size` that contains a map of the register’s index to the circuit’s qubit index. For example, array element 0’s value is the index of the `register[0]`’s position in the containing circuit’s qubits list. Prior to QPY [Version 4](#qpy-version-4) the type of array elements was uint32\_t. This was changed to enable negative values which represent bits in the array not present in the circuit The standalone boolean determines whether the register is constructed as a standalone register that was added to the circuit or was created from existing bits. A register is considered standalone if it has bits constructed solely as part of it, for example: ```python qr = QuantumRegister(2) qc = QuantumCircuit(qr) ``` the register `qr` would be a standalone register. While something like: ```python bits = [Qubit(), Qubit()] qr2 = QuantumRegister(bits=bits) qc = QuantumCircuit(qr2) ``` `qr2` would have `standalone` set to `False`. #### CUSTOM\_DEFINITIONS This section specifies custom definitions for any of the instructions in the circuit. CUSTOM\_DEFINITION\_HEADER contents are defined as: ```python struct { uint64_t size; } ``` If size is greater than 0 that means the circuit contains custom instruction(s). Each custom instruction is defined with a CUSTOM\_INSTRUCTION block defined as: ```python struct { uint16_t name_size; char type; uint32_t num_qubits; uint32_t num_clbits; _Bool custom_definition; uint64_t size; } ``` Immediately following the CUSTOM\_INSTRUCTION struct is the utf8 encoded name of size `name_size`. If `custom_definition` is `True` that means that the immediately following `size` bytes contains a QPY circuit data which can be used for the custom definition of that gate. If `custom_definition` is `False` then the instruction can be considered opaque (ie no definition). The `type` field determines what type of object will get created with the custom definition. If it’s `'g'` it will be a [`Gate`](qiskit.circuit.Gate ""qiskit.circuit.Gate"") object, `'i'` it will be a [`Instruction`](qiskit.circuit.Instruction ""qiskit.circuit.Instruction"") object. #### INSTRUCTIONS The contents of INSTRUCTIONS is a list of INSTRUCTION metadata objects ```python struct { uint16_t name_size; uint16_t label_size; uint16_t num_parameters; uint32_t num_qargs; uint32_t num_cargs; _Bool has_conditional; uint16_t conditional_reg_name_size; int64_t conditional_value; } ``` This metadata object is immediately followed by `name_size` bytes of utf8 bytes for the `name`. `name` here is the Qiskit class name for the Instruction class if it’s defined in Qiskit. Otherwise it falls back to the custom instruction name. Following the `name` bytes there are `label_size` bytes of utf8 data for the label if one was set on the instruction. Following the label bytes if `has_conditional` is `True` then there are `conditional_reg_name_size` bytes of utf8 data for the name of the conditional register name. In case of single classical bit conditions the register name utf8 data will be prefixed with a null character “x00” and then a utf8 string integer representing the classical bit index in the circuit that the condition is on. This is immediately followed by the INSTRUCTION\_ARG structs for the list of arguments of that instruction. These are in the order of all quantum arguments (there are num\_qargs of these) followed by all classical arguments (num\_cargs of these). The contents of each INSTRUCTION\_ARG is: ```python struct { char type; uint32_t index; } ``` `type` can be `'q'` or `'c'`. After all arguments for an instruction the parameters are specified with `num_parameters` INSTRUCTION\_PARAM structs. The contents of each INSTRUCTION\_PARAM is: ```python struct { char type; uint64_t size; } ``` After each INSTRUCTION\_PARAM the next `size` bytes are the parameter’s data. The `type` field can be `'i'`, `'f'`, `'p'`, `'e'`, `'s'`, `'c'` or `'n'` which dictate the format. For `'i'` it’s an integer, `'f'` it’s a double, `'s'` if it’s a string (encoded as utf8), `'c'` is a complex and the data is represented by the struct format in the [PARAMETER\_EXPR](#qpy-param-expr) section. `'p'` defines a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") object which is represented by a [PARAMETER](#qpy-param-struct) struct, `e` defines a [`ParameterExpression`](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") object (that’s not a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")) which is represented by a [PARAMETER\_EXPR](#qpy-param-expr) struct (on QPY format [Version 3](#qpy-version-3) the format is tweak slightly see: [PARAMETER\_EXPR](#qpy-param-expr-v3)), `'n'` represents an object from numpy (either an `ndarray` or a numpy type) which means the data is .npy format [\[2\]](#f2) data, and in QPY [Version 3](#qpy-version-3) `'v'` represents a `ParameterVectorElement` which is represented by a [PARAMETER\_VECTOR\_ELEMENT](#qpy-param-vector) struct. #### PARAMETER A PARAMETER represents a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") object the data for a INSTRUCTION\_PARAM. The contents of the PARAMETER are defined as: ```python struct { uint16_t name_size; char uuid[16]; } ``` which is immediately followed by `name_size` utf8 bytes representing the parameter name. #### PARAMETER\_EXPR A PARAMETER\_EXPR represents a [`ParameterExpression`](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") object that the data for an INSTRUCTION\_PARAM. The contents of a PARAMETER\_EXPR are defined as: The PARAMETER\_EXPR data starts with a header: ```python struct { uint64_t map_elements; uint64_t expr_size; } ``` Immediately following the header is `expr_size` bytes of utf8 data containing the expression string, which is the sympy srepr of the expression for the parameter expression. Follwing that is a symbol map which contains `map_elements` elements with the format ```python struct { char type; uint64_t size; } ``` Which is followed immediately by `PARAMETER` object (both the struct and utf8 name bytes) for the symbol map key. That is followed by `size` bytes for the data of the symbol. The data format is dependent on the value of `type`. If `type` is `p` then it represents a [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"") and size will be 0, the value will just be the same as the key. If `type` is `f` then it represents a double precision float. If `type` is `c` it represents a double precision complex, which is represented by [COMPLEX](#qpy-complex). Finally, if type is `i` it represents an integer which is an `int64_t`. #### COMPLEX When representing a double precision complex value in QPY the following struct is used: ```python struct { double real; double imag; } ``` this matches the internal C representation of Python’s complex type. [\[3\]](#f3) \[[1](#id2)] [https://tools.ietf.org/html/rfc1700](https://tools.ietf.org/html/rfc1700) \[2] ([1](#id4),[2](#id6)) [https://numpy.org/doc/stable/reference/generated/numpy.lib.format.html](https://numpy.org/doc/stable/reference/generated/numpy.lib.format.html) \[[3](#id8)] [https://docs.python.org/3/c-api/complex.html#c.Py\_complex](https://docs.python.org/3/c-api/complex.html#c.Py_complex) ",repo/docs/api/qiskit/1.0\qpy.mdx "--- title: quantum_info description: API reference for qiskit.quantum_info in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.quantum_info --- # Quantum Information `qiskit.quantum_info` ## Operators | | | | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | [`Operator`](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")(data\[, input\_dims, output\_dims]) | Matrix operator class | | [`Pauli`](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"")(\[data]) | N-qubit Pauli operator. | | [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"")(data\[, validate, copy]) | An N-qubit unitary operator from the Clifford group. | | [`ScalarOp`](qiskit.quantum_info.ScalarOp ""qiskit.quantum_info.ScalarOp"")(\[dims, coeff]) | Scalar identity operator class. | | [`SparsePauliOp`](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"")(data\[, coeffs, ...]) | Sparse N-qubit operator in a Pauli basis representation. | | [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"")(\[data, num\_qubits, validate]) | An N-qubit operator from the CNOT-Dihedral group. | | [`PauliList`](qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"")(data) | List of N-qubit Pauli operators. | | [`pauli_basis`](qiskit.quantum_info.pauli_basis ""qiskit.quantum_info.pauli_basis"")(num\_qubits\[, weight]) | Return the ordered PauliList for the n-qubit Pauli basis. | ## States | | | | ----------------------------------------------------------------------------------------------------------------- | ---------------------- | | [`Statevector`](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"")(data\[, dims]) | Statevector class | | [`DensityMatrix`](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")(data\[, dims]) | DensityMatrix class | | [`StabilizerState`](qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.StabilizerState"")(data\[, validate]) | StabilizerState class. | ## Channels | | | | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | [`Choi`](qiskit.quantum_info.Choi ""qiskit.quantum_info.Choi"")(data\[, input\_dims, output\_dims]) | Choi-matrix representation of a Quantum Channel. | | [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"")(data\[, input\_dims, output\_dims]) | Superoperator representation of a quantum channel. | | [`Kraus`](qiskit.quantum_info.Kraus ""qiskit.quantum_info.Kraus"")(data\[, input\_dims, output\_dims]) | Kraus representation of a quantum channel. | | [`Stinespring`](qiskit.quantum_info.Stinespring ""qiskit.quantum_info.Stinespring"")(data\[, input\_dims, output\_dims]) | Stinespring representation of a quantum channel. | | [`Chi`](qiskit.quantum_info.Chi ""qiskit.quantum_info.Chi"")(data\[, input\_dims, output\_dims]) | Pauli basis Chi-matrix representation of a quantum channel. | | [`PTM`](qiskit.quantum_info.PTM ""qiskit.quantum_info.PTM"")(data\[, input\_dims, output\_dims]) | Pauli Transfer Matrix (PTM) representation of a Quantum Channel. | ## Measures ### average\_gate\_fidelity Return the average gate fidelity of a noisy quantum channel. The average gate fidelity $F_{\text{ave}}$ is given by $$ \begin{aligned} F_{\text{ave}}(\mathcal{E}, U) &= \int d\psi \langle\psi|U^\dagger \mathcal{E}(|\psi\rangle\!\langle\psi|)U|\psi\rangle \\ &= \frac{d F_{\text{pro}}(\mathcal{E}, U) + 1}{d + 1} \end{aligned} $$ where $F_{\text{pro}}(\mathcal{E}, U)$ is the [`process_fidelity()`](#qiskit.quantum_info.process_fidelity ""qiskit.quantum_info.process_fidelity"") of the input quantum *channel* $\mathcal{E}$ with a *target* unitary $U$, and $d$ is the dimension of the *channel*. **Parameters** * **channel** (*QuantumChannel or* [*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"")) – noisy quantum channel. * **target** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") *or None*) – target unitary operator. If None target is the identity operator \[Default: None]. * **require\_cp** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – check if input and target channels are completely-positive and if non-CP log warning containing negative eigenvalues of Choi-matrix \[Default: True]. * **require\_tp** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – check if input and target channels are trace-preserving and if non-TP log warning containing negative eigenvalues of partial Choi-matrix $Tr_{\text{out}}[\mathcal{E}] - I$ \[Default: True]. **Returns** The average gate fidelity $F_{\text{ave}}$. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the channel and target do not have the same dimensions, or have different input and output dimensions. ### process\_fidelity Return the process fidelity of a noisy quantum channel. The process fidelity $F_{\text{pro}}(\mathcal{E}, \mathcal{F})$ between two quantum channels $\mathcal{E}, \mathcal{F}$ is given by $$ F_{\text{pro}}(\mathcal{E}, \mathcal{F}) = F(\rho_{\mathcal{E}}, \rho_{\mathcal{F}}) $$ where $F$ is the [`state_fidelity()`](#qiskit.quantum_info.state_fidelity ""qiskit.quantum_info.state_fidelity""), $\rho_{\mathcal{E}} = \Lambda_{\mathcal{E}} / d$ is the normalized [`Choi`](qiskit.quantum_info.Choi ""qiskit.quantum_info.Choi"") matrix for the channel $\mathcal{E}$, and $d$ is the input dimension of $\mathcal{E}$. When the target channel is unitary this is equivalent to $$ F_{\text{pro}}(\mathcal{E}, U) = \frac{Tr[S_U^\dagger S_{\mathcal{E}}]}{d^2} $$ where $S_{\mathcal{E}}, S_{U}$ are the [`SuperOp`](qiskit.quantum_info.SuperOp ""qiskit.quantum_info.SuperOp"") matrices for the *input* quantum channel $\mathcal{E}$ and *target* unitary $U$ respectively, and $d$ is the input dimension of the channel. **Parameters** * **channel** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") *or QuantumChannel*) – input quantum channel. * **target** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") *or QuantumChannel or None*) – target quantum channel. If None target is the identity operator \[Default: None]. * **require\_cp** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – check if input and target channels are completely-positive and if non-CP log warning containing negative eigenvalues of Choi-matrix \[Default: True]. * **require\_tp** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – check if input and target channels are trace-preserving and if non-TP log warning containing negative eigenvalues of partial Choi-matrix $Tr_{\text{out}}[\mathcal{E}] - I$ \[Default: True]. **Returns** The process fidelity $F_{\text{pro}}$. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the channel and target do not have the same dimensions. ### gate\_error Return the gate error of a noisy quantum channel. The gate error $E$ is given by the average gate infidelity $$ E(\mathcal{E}, U) = 1 - F_{\text{ave}}(\mathcal{E}, U) $$ where $F_{\text{ave}}(\mathcal{E}, U)$ is the [`average_gate_fidelity()`](#qiskit.quantum_info.average_gate_fidelity ""qiskit.quantum_info.average_gate_fidelity"") of the input quantum *channel* $\mathcal{E}$ with a *target* unitary $U$. **Parameters** * **channel** (*QuantumChannel*) – noisy quantum channel. * **target** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") *or None*) – target unitary operator. If None target is the identity operator \[Default: None]. * **require\_cp** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – check if input and target channels are completely-positive and if non-CP log warning containing negative eigenvalues of Choi-matrix \[Default: True]. * **require\_tp** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – check if input and target channels are trace-preserving and if non-TP log warning containing negative eigenvalues of partial Choi-matrix $Tr_{\text{out}}[\mathcal{E}] - I$ \[Default: True]. **Returns** The average gate error $E$. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the channel and target do not have the same dimensions, or have different input and output dimensions. ### diamond\_norm Return the diamond norm of the input quantum channel object. This function computes the completely-bounded trace-norm (often referred to as the diamond-norm) of the input quantum channel object using the semidefinite-program from reference \[1]. **Parameters** * **choi** ([*Choi*](qiskit.quantum_info.Choi ""qiskit.quantum_info.Choi"") *or QuantumChannel*) – a quantum channel object or Choi-matrix array. * **solver** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The solver to use. * **kwargs** – optional arguments to pass to CVXPY solver. **Returns** The completely-bounded trace norm $\|\mathcal{E}\|_{\diamond}$. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if CVXPY package cannot be found. **Additional Information:** The input to this function is typically *not* a CPTP quantum channel, but rather the *difference* between two quantum channels $\|\Delta\mathcal{E}\|_\diamond$ where $\Delta\mathcal{E} = \mathcal{E}_1 - \mathcal{E}_2$. **Reference:** J. Watrous. “Simpler semidefinite programs for completely bounded norms”, arXiv:1207.5726 \[quant-ph] (2012). This function requires the optional CVXPY package to be installed. Any additional kwargs will be passed to the `cvxpy.solve` function. See the CVXPY documentation for information on available SDP solvers. ### state\_fidelity Return the state fidelity between two quantum states. The state fidelity $F$ for density matrix input states $\rho_1, \rho_2$ is given by $$ F(\rho_1, \rho_2) = Tr[\sqrt{\sqrt{\rho_1}\rho_2\sqrt{\rho_1}}]^2. $$ If one of the states is a pure state this simplifies to $F(\rho_1, \rho_2) = \langle\psi_1|\rho_2|\psi_1\rangle$, where $\rho_1 = |\psi_1\rangle\!\langle\psi_1|$. **Parameters** * **state1** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")) – the first quantum state. * **state2** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")) – the second quantum state. * **validate** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – check if the inputs are valid quantum states \[Default: True] **Returns** The state fidelity $F(\rho_1, \rho_2)$. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if `validate=True` and the inputs are invalid quantum states. ### purity Calculate the purity of a quantum state. The purity of a density matrix $\rho$ is $$ \text{Purity}(\rho) = Tr[\rho^2] $$ **Parameters** * **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")) – a quantum state. * **validate** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – check if input state is valid \[Default: True] **Returns** the purity $Tr[\rho^2]$. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input isn’t a valid quantum state. ### concurrence Calculate the concurrence of a quantum state. The concurrence of a bipartite [`Statevector`](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") $|\psi\rangle$ is given by $$ C(|\psi\rangle) = \sqrt{2(1 - Tr[\rho_0^2])} $$ where $\rho_0 = Tr_1[|\psi\rangle\!\langle\psi|]$ is the reduced state from by taking the [`partial_trace()`](#qiskit.quantum_info.partial_trace ""qiskit.quantum_info.partial_trace"") of the input state. For density matrices the concurrence is only defined for 2-qubit states, it is given by: $$ C(\rho) = \max(0, \lambda_1 - \lambda_2 - \lambda_3 - \lambda_4) $$ where $\lambda _1 \ge \lambda _2 \ge \lambda _3 \ge \lambda _4$ are the ordered eigenvalues of the matrix $R=\sqrt{\sqrt{\rho }(Y\otimes Y)\overline{\rho}(Y\otimes Y)\sqrt{\rho}}$. **Parameters** **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")) – a 2-qubit quantum state. **Returns** The concurrence. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input state is not a valid QuantumState. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input is not a bipartite QuantumState. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if density matrix input is not a 2-qubit state. ### entropy Calculate the von-Neumann entropy of a quantum state. The entropy $S$ is given by $$ S(\rho) = - Tr[\rho \log(\rho)] $$ **Parameters** * **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")) – a quantum state. * **base** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the base of the logarithm \[Default: 2]. **Returns** The von-Neumann entropy S(rho). **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input state is not a valid QuantumState. ### entanglement\_of\_formation Calculate the entanglement of formation of quantum state. The input quantum state must be either a bipartite state vector, or a 2-qubit density matrix. **Parameters** **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")) – a 2-qubit quantum state. **Returns** The entanglement of formation. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input state is not a valid QuantumState. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input is not a bipartite QuantumState. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if density matrix input is not a 2-qubit state. ### mutual\_information Calculate the mutual information of a bipartite state. The mutual information $I$ is given by: $$ I(\rho_{AB}) = S(\rho_A) + S(\rho_B) - S(\rho_{AB}) $$ where $\rho_A=Tr_B[\rho_{AB}], \rho_B=Tr_A[\rho_{AB}]$, are the reduced density matrices of the bipartite state $\rho_{AB}$. **Parameters** * **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")) – a bipartite state. * **base** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the base of the logarithm \[Default: 2]. **Returns** The mutual information $I(\rho_{AB})$. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input state is not a valid QuantumState. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input is not a bipartite QuantumState. ## Utility Functions | | | | ------------------------------------------------------------------------------------- | ---------------------------------- | | [`Quaternion`](qiskit.quantum_info.Quaternion ""qiskit.quantum_info.Quaternion"")(data) | A class representing a Quaternion. | ### partial\_trace Return reduced density matrix by tracing out part of quantum state. If all subsystems are traced over this returns the [`trace()`](qiskit.quantum_info.DensityMatrix#trace ""qiskit.quantum_info.DensityMatrix.trace"") of the input state. **Parameters** * **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")) – the input state. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – The subsystems to trace over. **Returns** The reduced density matrix. **Return type** [DensityMatrix](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if input state is invalid. ### schmidt\_decomposition Return the Schmidt Decomposition of a pure quantum state. For an arbitrary bipartite state: $$ |\psi\rangle_{AB} = \sum_{i,j} c_{ij} |x_i\rangle_A \otimes |y_j\rangle_B, $$ its Schmidt Decomposition is given by the single-index sum over k: $$ |\psi\rangle_{AB} = \sum_{k} \lambda_{k} |u_k\rangle_A \otimes |v_k\rangle_B $$ where $|u_k\rangle_A$ and $|v_k\rangle_B$ are an orthonormal set of vectors in their respective spaces $A$ and $B$, and the Schmidt coefficients $\lambda_k$ are positive real values. **Parameters** * **state** ([*Statevector*](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") *or*[*DensityMatrix*](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"")) – the input state. * **qargs** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – the list of Input state positions corresponding to subsystem $B$. **Returns** list of tuples `(s, u, v)`, where `s` (float) are the Schmidt coefficients $\lambda_k$, and `u` (Statevector), `v` (Statevector) are the Schmidt vectors $|u_k\rangle_A$, $|u_k\rangle_B$, respectively. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"") **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if Input qargs is not a list of positions of the Input state. * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if Input qargs is not a proper subset of Input state. In Qiskit, qubits are ordered using little-endian notation, with the least significant qubits having smaller indices. For example, a four-qubit system is represented as $|q_3q_2q_1q_0\rangle$. Using this convention, setting `qargs=[0]` will partition the state as $|q_3q_2q_1\rangle_A\otimes|q_0\rangle_B$. Furthermore, qubits will be organized in this notation regardless of the order they are passed. For instance, passing either `qargs=[1,2]` or `qargs=[2,1]` will result in partitioning the state as $|q_3q_0\rangle_A\otimes|q_2q_1\rangle_B$. ### shannon\_entropy Compute the Shannon entropy of a probability vector. The shannon entropy of a probability vector $\vec{p} = [p_0, ..., p_{n-1}]$ is defined as $$ H(\vec{p}) = \sum_{i=0}^{n-1} p_i \log_b(p_i) $$ where $b$ is the log base and (default 2), and $0 \log_b(0) \equiv 0$. **Parameters** * **pvec** (*array\_like*) – a probability vector. * **base** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the base of the logarithm \[Default: 2]. **Returns** The Shannon entropy H(pvec). **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") ### commutator Compute commutator of a and b. $$ ab - ba. $$ **Parameters** * **a** (*OperatorTypeT*) – Operator a. * **b** (*OperatorTypeT*) – Operator b. **Returns** The commutator **Return type** *OperatorTypeT* ### anti\_commutator Compute anti-commutator of a and b. $$ ab + ba. $$ **Parameters** * **a** (*OperatorTypeT*) – Operator a. * **b** (*OperatorTypeT*) – Operator b. **Returns** The anti-commutator **Return type** *OperatorTypeT* ### double\_commutator Compute symmetric double commutator of a, b and c. See also Equation (13.6.18) in \[1]. If commutator is True, it returns $$ [[A, B], C]/2 + [A, [B, C]]/2 = (2ABC + 2CBA - BAC - CAB - ACB - BCA)/2. $$ If commutator is False, it returns $$ \lbrace[A, B], C\rbrace/2 + \lbrace A, [B, C]\rbrace/2 = (2ABC - 2CBA - BAC + CAB - ACB + BCA)/2. $$ **Parameters** * **a** (*OperatorTypeT*) – Operator a. * **b** (*OperatorTypeT*) – Operator b. * **c** (*OperatorTypeT*) – Operator c. * **commutator** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True` compute the double commutator, if `False` the double anti-commutator. **Returns** The double commutator **Return type** *OperatorTypeT* **References** **\[1]: R. McWeeny.** Methods of Molecular Quantum Mechanics. 2nd Edition, Academic Press, 1992. ISBN 0-12-486552-6. ## Random ### random\_statevector Generator a random Statevector. The statevector is sampled from the uniform distribution. This is the measure induced by the Haar measure on unitary matrices. **Parameters** * **dims** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the dimensions of the state. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or np.random.Generator*) – Optional. Set a fixed seed or generator for RNG. **Returns** the random statevector. **Return type** [Statevector](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") **Reference:** K. Zyczkowski and H. Sommers (2001), “Induced measures in the space of mixed quantum states”, [J. Phys. A: Math. Gen. 34 7111](https://arxiv.org/abs/quant-ph/0012101). ### random\_density\_matrix Generator a random DensityMatrix. **Parameters** * **dims** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the dimensions of the DensityMatrix. * **rank** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or None*) – Optional, the rank of the density matrix. The default value is full-rank. * **method** (*string*) – Optional. The method to use. ‘Hilbert-Schmidt’: (Default) sample from the Hilbert-Schmidt metric. ‘Bures’: sample from the Bures metric. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or np.random.Generator*) – Optional. Set a fixed seed or generator for RNG. **Returns** the random density matrix. **Return type** [DensityMatrix](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the method is not valid. ### random\_unitary Return a random unitary Operator. The operator is sampled from the unitary Haar measure. **Parameters** * **dims** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the input dimensions of the Operator. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or np.random.Generator*) – Optional. Set a fixed seed or generator for RNG. **Returns** a unitary operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") ### random\_hermitian Return a random hermitian Operator. The operator is sampled from Gaussian Unitary Ensemble. **Parameters** * **dims** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the input dimension of the Operator. * **traceless** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Optional. If True subtract diagonal entries to return a traceless hermitian operator (Default: False). * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or np.random.Generator*) – Optional. Set a fixed seed or generator for RNG. **Returns** a Hermitian operator. **Return type** [Operator](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") ### random\_pauli Return a random Pauli. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of qubits. * **group\_phase** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Optional. If True generate random phase. Otherwise the phase will be set so that the Pauli coefficient is +1 (default: False). * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or np.random.Generator*) – Optional. Set a fixed seed or generator for RNG. **Returns** a random Pauli **Return type** [Pauli](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") ### random\_clifford Return a random Clifford operator. The Clifford is sampled using the method of Reference \[1]. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of qubits for the Clifford * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or np.random.Generator*) – Optional. Set a fixed seed or generator for RNG. **Returns** a random Clifford operator. **Return type** [Clifford](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") **Reference:** 1. S. Bravyi and D. Maslov, *Hadamard-free circuits expose the structure of the Clifford group*. [arXiv:2003.09412 \[quant-ph\]](https://arxiv.org/abs/2003.09412) ### random\_quantum\_channel Return a random CPTP quantum channel. This constructs the Stinespring operator for the quantum channel by sampling a random isometry from the unitary Haar measure. **Parameters** * **input\_dims** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the input dimension of the channel. * **output\_dims** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or*[*tuple*](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")) – the input dimension of the channel. * **rank** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional. The rank of the quantum channel Choi-matrix. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or np.random.Generator*) – Optional. Set a fixed seed or generator for RNG. **Returns** a quantum channel operator. **Return type** [Stinespring](qiskit.quantum_info.Stinespring ""qiskit.quantum_info.Stinespring"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if rank or dimensions are invalid. ### random\_cnotdihedral Return a random CNOTDihedral element. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of qubits for the CNOTDihedral object. * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or RandomState*) – Optional. Set a fixed seed or generator for RNG. **Returns** a random CNOTDihedral element. **Return type** [CNOTDihedral](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") ### random\_pauli\_list Return a random PauliList. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – the number of qubits. * **size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Optional. The length of the Pauli list (Default: 1). * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *or np.random.Generator*) – Optional. Set a fixed seed or generator for RNG. * **phase** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If True the Pauli phases are randomized, otherwise the phases are fixed to 0. \[Default: True] **Returns** a random PauliList. **Return type** [PauliList](qiskit.quantum_info.PauliList ""qiskit.quantum_info.PauliList"") ## Analysis ### hellinger\_distance Computes the Hellinger distance between two counts distributions. **Parameters** * **dist\_p** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – First dict of counts. * **dist\_q** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Second dict of counts. **Returns** Distance **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **References** [Hellinger Distance @ wikipedia](https://en.wikipedia.org/wiki/Hellinger_distance) ### hellinger\_fidelity Computes the Hellinger fidelity between two counts distributions. The fidelity is defined as $\left(1-H^{2}\right)^{2}$ where H is the Hellinger distance. This value is bounded in the range \[0, 1]. This is equivalent to the standard classical fidelity $F(Q,P)=\left(\sum_{i}\sqrt{p_{i}q_{i}}\right)^{2}$ that in turn is equal to the quantum state fidelity for diagonal density matrices. **Parameters** * **dist\_p** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – First dict of counts. * **dist\_q** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Second dict of counts. **Returns** Fidelity **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Example** ```python from qiskit import QuantumCircuit from qiskit.quantum_info.analysis import hellinger_fidelity from qiskit.providers.basic_provider import BasicSimulator qc = QuantumCircuit(5, 5) qc.h(2) qc.cx(2, 1) qc.cx(2, 3) qc.cx(3, 4) qc.cx(1, 0) qc.measure(range(5), range(5)) sim = BasicSimulator() res1 = sim.run(qc).result() res2 = sim.run(qc).result() hellinger_fidelity(res1.get_counts(), res2.get_counts()) ``` **References** [Quantum Fidelity @ wikipedia](https://en.wikipedia.org/wiki/Fidelity_of_quantum_states) [Hellinger Distance @ wikipedia](https://en.wikipedia.org/wiki/Hellinger_distance) | | | | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [`Z2Symmetries`](qiskit.quantum_info.Z2Symmetries ""qiskit.quantum_info.Z2Symmetries"")(symmetries, sq\_paulis, sq\_list) | The \$Z\_2\$ symmetry converter identifies symmetries from the problem hamiltonian and uses them to provide a tapered - more efficient - representation of operators as Paulis for this problem. | ",repo/docs/api/qiskit/1.0\quantum_info.mdx "--- title: result description: API reference for qiskit.result in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.result --- # Experiment Results `qiskit.result` | | | | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | [`Result`](qiskit.result.Result ""qiskit.result.Result"")(backend\_name, backend\_version, ...\[, ...]) | Model for Results. | | [`ResultError`](qiskit.result.ResultError ""qiskit.result.ResultError"")(error) | Exceptions raised due to errors in result output. | | [`Counts`](qiskit.result.Counts ""qiskit.result.Counts"")(data\[, time\_taken, creg\_sizes, ...]) | A class to store a counts result from a circuit execution. | ### marginal\_counts Marginalize counts from an experiment over some indices of interest. **Parameters** * **result** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") *|*[*Result*](qiskit.result.Result ""qiskit.result.result.Result"")) – result to be marginalized (a Result object or a dict(str, int) of counts). * **indices** ([*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*) – The bit positions of interest to marginalize over. If `None` (default), do not marginalize at all. * **inplace** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Default: False. Operates on the original Result argument if True, leading to loss of original Job Result. It has no effect if `result` is a dict. * **format\_marginal** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Default: False. If True, takes the output of marginalize and formats it with placeholders between cregs and for non-indices. * **marginalize\_memory** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") *| None*) – If True, then also marginalize the memory field (if present). If False, remove the memory field from the result. If None, leave the memory field as is. **Returns** **A Result object or a dictionary with** the observed counts, marginalized to only account for frequency of observations of bits of interest. **Return type** [Result](qiskit.result.Result ""qiskit.result.Result"") or [dict](https://docs.python.org/3/library/stdtypes.html#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)"")) **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – in case of invalid indices to marginalize over. ### marginal\_distribution Marginalize counts from an experiment over some indices of interest. Unlike [`marginal_counts()`](#qiskit.result.marginal_counts ""qiskit.result.marginal_counts"") this function respects the order of the input `indices`. If the input `indices` list is specified then the order the bit indices are specified will be the output order of the bitstrings in the marginalized output. **Parameters** * **counts** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – result to be marginalized * **indices** ([*Sequence*](https://docs.python.org/3/library/typing.html#typing.Sequence ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*] | None*) – The bit positions of interest to marginalize over. If `None` (default), do not marginalize at all. * **format\_marginal** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Default: False. If True, takes the output of marginalize and formats it with placeholders between cregs and for non-indices. **Returns** A marginalized dictionary **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#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)"")) **Raises** * [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If any value in `indices` is invalid or the `counts` dict * **is invalid.** – ### marginal\_memory Marginalize shot memory This function is multithreaded and will launch a thread pool with threads equal to the number of CPUs by default. You can tune the number of threads with the `RAYON_NUM_THREADS` environment variable. For example, setting `RAYON_NUM_THREADS=4` would limit the thread pool to 4 threads. **Parameters** * **memory** ([*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)"")*] |* [*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – The input memory list, this is either a list of hexadecimal strings to be marginalized representing measure level 2 memory or a numpy array representing level 0 measurement memory (single or avg) or level 1 measurement memory (single or avg). * **indices** ([*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*) – The bit positions of interest to marginalize over. If `None` (default), do not marginalize at all. * **int\_return** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to `True` the output will be a list of integers. By default the return type is a bit string. This and `hex_return` are mutually exclusive and can not be specified at the same time. This option only has an effect with memory level 2. * **hex\_return** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to `True` the output will be a list of hexadecimal strings. By default the return type is a bit string. This and `int_return` are mutually exclusive and can not be specified at the same time. This option only has an effect with memory level 2. * **avg\_data** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If a 2 dimensional numpy array is passed in for `memory` this can be set to `True` to indicate it’s a avg level 0 data instead of level 1 single data. * **parallel\_threshold** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of elements in `memory` to start running in multiple threads. If `len(memory)` is >= this value, the function will run in multiple threads. By default this is set to 1000. **Returns** The list of marginalized memory **Return type** marginal\_memory **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – if both `int_return` and `hex_return` are set to `True` ## Distributions | | | | ------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | | [`ProbDistribution`](qiskit.result.ProbDistribution ""qiskit.result.ProbDistribution"")(data\[, shots]) | A generic dict-like class for probability distributions. | | [`QuasiDistribution`](qiskit.result.QuasiDistribution ""qiskit.result.QuasiDistribution"")(data\[, shots, ...]) | A dict-like class for representing quasi-probabilities. | ## Expectation values ### sampled\_expectation\_value Computes expectation value from a sampled distribution Note that passing a raw dict requires bit-string keys. **Parameters** * **dist** ([*Counts*](qiskit.result.Counts ""qiskit.result.Counts"") *or*[*QuasiDistribution*](qiskit.result.QuasiDistribution ""qiskit.result.QuasiDistribution"") *or*[*ProbDistribution*](qiskit.result.ProbDistribution ""qiskit.result.ProbDistribution"") *or*[*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Input sampled distribution * **oper** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or*[*Pauli*](qiskit.quantum_info.Pauli ""qiskit.quantum_info.Pauli"") *or PauliOp or PauliSumOp or*[*SparsePauliOp*](qiskit.quantum_info.SparsePauliOp ""qiskit.quantum_info.SparsePauliOp"")) – The operator for the observable **Returns** The expectation value **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input distribution or operator is an invalid type ## Mitigation | | | | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | | [`BaseReadoutMitigator`](qiskit.result.BaseReadoutMitigator ""qiskit.result.BaseReadoutMitigator"")() | Base readout error mitigator class. | | [`CorrelatedReadoutMitigator`](qiskit.result.CorrelatedReadoutMitigator ""qiskit.result.CorrelatedReadoutMitigator"")(assignment\_matrix) | N-qubit readout error mitigator. | | [`LocalReadoutMitigator`](qiskit.result.LocalReadoutMitigator ""qiskit.result.LocalReadoutMitigator"")(\[assignment\_matrices, ...]) | 1-qubit tensor product readout error mitigator. | ",repo/docs/api/qiskit/1.0\result.mdx "--- title: scheduler description: API reference for qiskit.scheduler in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.scheduler --- # Circuit Scheduler `qiskit.scheduler` A circuit scheduler compiles a circuit program to a pulse program. ### ScheduleConfig Configuration for pulse scheduling. Container for information needed to schedule a QuantumCircuit into a pulse Schedule. **Parameters** * **inst\_map** ([*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.instruction_schedule_map.InstructionScheduleMap"")) – The schedule definition of all gates supported on a backend. * **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)"")*]]*) – A list of groups of qubits which have to be measured together. * **dt** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – Sample duration. ### schedule\_circuit Basic scheduling pass from a circuit to a pulse Schedule, using the backend. If no method is specified, then a basic, as late as possible scheduling pass is performed, i.e. pulses are scheduled to occur as late as possible. Supported methods: > * `'as_soon_as_possible'`: Schedule pulses greedily, as early as possible on a qubit resource. (alias: `'asap'`) > * `'as_late_as_possible'`: Schedule pulses late– keep qubits in the ground state when possible. (alias: `'alap'`) **Parameters** * **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")) – The quantum circuit to translate. * **schedule\_config** ([*ScheduleConfig*](#qiskit.scheduler.ScheduleConfig ""qiskit.scheduler.config.ScheduleConfig"")) – Backend specific parameters used for building the Schedule. * **method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The scheduling pass method to use. * **backend** ([*BackendV1*](qiskit.providers.BackendV1 ""qiskit.providers.backend.BackendV1"") *|*[*BackendV2*](qiskit.providers.BackendV2 ""qiskit.providers.backend.BackendV2"") *| None*) – A backend used to build the Schedule, the backend could be BackendV1 or BackendV2. **Returns** Schedule corresponding to the input circuit. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If method isn’t recognized. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") Pulse scheduling methods. ### as\_soon\_as\_possible Return the pulse Schedule which implements the input circuit using an “as soon as possible” (asap) scheduling policy. Circuit instructions are first each mapped to equivalent pulse Schedules according to the command definition given by the schedule\_config. Then, this circuit instruction-equivalent Schedule is appended at the earliest time at which all qubits involved in the instruction are available. **Parameters** * **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")) – The quantum circuit to translate. * **schedule\_config** ([*ScheduleConfig*](#qiskit.scheduler.ScheduleConfig ""qiskit.scheduler.config.ScheduleConfig"")) – Backend specific parameters used for building the Schedule. * **backend** ([*BackendV1*](qiskit.providers.BackendV1 ""qiskit.providers.backend.BackendV1"") *|*[*BackendV2*](qiskit.providers.BackendV2 ""qiskit.providers.backend.BackendV2"") *| None*) – A backend used to build the Schedule, the backend could be BackendV1 or BackendV2. **Returns** A schedule corresponding to the input `circuit` with pulses occurring as early as possible. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") ### as\_late\_as\_possible Return the pulse Schedule which implements the input circuit using an “as late as possible” (alap) scheduling policy. Circuit instructions are first each mapped to equivalent pulse Schedules according to the command definition given by the schedule\_config. Then, this circuit instruction-equivalent Schedule is appended at the latest time that it can be without allowing unnecessary time between instructions or allowing instructions with common qubits to overlap. This method should improves the outcome fidelity over ASAP scheduling, because we may maximize the time that the qubit remains in the ground state. **Parameters** * **circuit** ([*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")) – The quantum circuit to translate. * **schedule\_config** ([*ScheduleConfig*](#qiskit.scheduler.ScheduleConfig ""qiskit.scheduler.config.ScheduleConfig"")) – Backend specific parameters used for building the Schedule. * **backend** ([*BackendV1*](qiskit.providers.BackendV1 ""qiskit.providers.backend.BackendV1"") *|*[*BackendV2*](qiskit.providers.BackendV2 ""qiskit.providers.backend.BackendV2"") *| None*) – A backend used to build the Schedule, the backend could be BackendV1 or BackendV2. **Returns** A schedule corresponding to the input `circuit` with pulses occurring as late as possible. **Return type** [*Schedule*](qiskit.pulse.Schedule ""qiskit.pulse.schedule.Schedule"") ",repo/docs/api/qiskit/1.0\scheduler.mdx "--- title: synthesis description: API reference for qiskit.synthesis in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.synthesis --- # Circuit Synthesis `qiskit.synthesis` ## Evolution Synthesis | | | | ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | [`EvolutionSynthesis`](qiskit.synthesis.EvolutionSynthesis ""qiskit.synthesis.EvolutionSynthesis"")() | Interface for evolution synthesis algorithms. | | [`ProductFormula`](qiskit.synthesis.ProductFormula ""qiskit.synthesis.ProductFormula"")(order\[, reps, ...]) | Product formula base class for the decomposition of non-commuting operator exponentials. | | [`LieTrotter`](qiskit.synthesis.LieTrotter ""qiskit.synthesis.LieTrotter"")(\[reps, insert\_barriers, ...]) | The Lie-Trotter product formula. | | [`SuzukiTrotter`](qiskit.synthesis.SuzukiTrotter ""qiskit.synthesis.SuzukiTrotter"")(\[order, reps, ...]) | The (higher order) Suzuki-Trotter product formula. | | [`MatrixExponential`](qiskit.synthesis.MatrixExponential ""qiskit.synthesis.MatrixExponential"")() | Exact operator evolution via matrix exponentiation and unitary synthesis. | | [`QDrift`](qiskit.synthesis.QDrift ""qiskit.synthesis.QDrift"")(\[reps, insert\_barriers, ...]) | The QDrift Trotterization method, which selects each each term in the Trotterization randomly, with a probability proportional to its weight. | ## Linear Function Synthesis ### synth\_cnot\_count\_full\_pmh Synthesize linear reversible circuits for all-to-all architecture using Patel, Markov and Hayes method. This function is an implementation of the Patel, Markov and Hayes algorithm from \[1] for optimal synthesis of linear reversible circuits for all-to-all architecture, as specified by an $n \times n$ matrix. **Parameters** * **state** ([*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)"")*\[*[*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*]] | np.ndarray\[*[*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*]*) – $n \times n$ boolean invertible matrix, describing the state of the input circuit * **section\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The size of each section, used in the Patel–Markov–Hayes algorithm \[1]. `section_size` must be a factor of the number of qubits. **Returns** a CX-only circuit implementing the linear transformation. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – when variable `state` isn’t of type `numpy.ndarray` **References** 1. Patel, Ketan N., Igor L. Markov, and John P. Hayes, *Optimal synthesis of linear reversible circuits*, Quantum Information & Computation 8.3 (2008): 282-294. [arXiv:quant-ph/0302002 \[quant-ph\]](https://arxiv.org/abs/quant-ph/0302002) ### synth\_cnot\_depth\_line\_kms Synthesize linear reversible circuit for linear nearest-neighbor architectures using Kutin, Moulton, Smithline method. Synthesis algorithm for linear reversible circuits from \[1], section 7. This algorithm synthesizes any linear reversible circuit of $n$ qubits over a linear nearest-neighbor architecture using CX gates with depth at most $5n$. **Parameters** **mat** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")*\[*[*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*]*) – A boolean invertible matrix. **Returns** The synthesized quantum circuit. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if `mat` is not invertible. **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. Kutin, S., Moulton, D. P., Smithline, L., *Computation at a distance*, Chicago J. Theor. Comput. Sci., vol. 2007, (2007), [arXiv:quant-ph/0701194](https://arxiv.org/abs/quant-ph/0701194) ## Linear-Phase Synthesis ### synth\_cz\_depth\_line\_mr Synthesis of a CZ circuit for linear nearest neighbour (LNN) connectivity, based on Maslov and Roetteler. Note that this method *reverts* the order of qubits in the circuit, and returns a circuit containing [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"")s and phase gates ([`SGate`](qiskit.circuit.library.SGate ""qiskit.circuit.library.SGate""), [`SdgGate`](qiskit.circuit.library.SdgGate ""qiskit.circuit.library.SdgGate"") or [`ZGate`](qiskit.circuit.library.ZGate ""qiskit.circuit.library.ZGate"")). **Parameters** **mat** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – an upper-diagonal matrix representing the CZ circuit. `mat[i][j]=1 for i ### synth\_cx\_cz\_depth\_line\_my Joint synthesis of a -CZ-CX- circuit for linear nearest neighbour (LNN) connectivity, with 2-qubit depth at most 5n, based on Maslov and Yang. This method computes the CZ circuit inside the CX circuit via phase gate insertions. **Parameters** * **mat\_z** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – a boolean symmetric matrix representing a CZ circuit. `mat_z[i][j]=1` represents a `cz(i,j)` gate * **mat\_x** ([*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")) – a boolean invertible matrix representing a CX circuit. **Returns** A circuit implementation of a CX circuit following a CZ circuit, denoted as a -CZ-CX- circuit,in two-qubit depth at most `5n`, for LNN connectivity. **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. Kutin, S., Moulton, D. P., Smithline, L., *Computation at a distance*, Chicago J. Theor. Comput. Sci., vol. 2007, (2007), [arXiv:quant-ph/0701194](https://arxiv.org/abs/quant-ph/0701194) 2. Dmitri Maslov, Willers Yang, *CNOT circuits need little help to implement arbitrary Hadamard-free Clifford transformations they generate*, [arXiv:2210.16195](https://arxiv.org/abs/2210.16195). ### synth\_cnot\_phase\_aam This function is an implementation of the GraySynth algorithm of Amy, Azimadeh and Mosca. GraySynth is a heuristic algorithm from \[1] for synthesizing small parity networks. It is inspired by Gray codes. Given a set of binary strings $S$ (called `cnots` bellow), the algorithm synthesizes a parity network for $S$ by repeatedly choosing an index $i$ to expand and then effectively recursing on the co-factors $S_0$ and $S_1$, consisting of the strings $y \in S$, with $y_i = 0$ or $1$ respectively. As a subset $S$ is recursively expanded, `cx` gates are applied so that a designated target bit contains the (partial) parity $\chi_y(x)$ where $y_i = 1$ if and only if $y'_i = 1$ for all $y' \in S$. If $S$ contains a single element $\{y'\}$, then $y = y'$, and the target bit contains the value $\chi_{y'}(x)$ as desired. Notably, rather than uncomputing this sequence of `cx` (CNOT) gates when a subset $S$ is finished being synthesized, the algorithm maintains the invariant that the remaining parities to be computed are expressed over the current state of bits. This allows the algorithm to avoid the ‘backtracking’ inherent in uncomputing-based methods. The algorithm is described in detail in section 4 of \[1]. **Parameters** * **cnots** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]]*) – A matrix whose columns are the parities to be synthesized e.g.: ```python [[0, 1, 1, 1, 1, 1], [1, 0, 0, 1, 1, 1], [1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0]] ``` corresponds to: ```python x1^x2 + x0 + x0^x3 + x0^x1^x2 + x0^x1^x3 + x0^x1 ``` * **angles** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – A list containing all the phase-shift gates which are to be applied, in the same order as in `cnots`. A number is interpreted as the angle of $p(angle)$, otherwise the elements have to be `'t'`, `'tdg'`, `'s'`, `'sdg'` or `'z'`. * **section\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The size of every section in the Patel–Markov–Hayes algorithm. `section_size` must be a factor of the number of qubits. **Returns** The decomposed quantum circuit. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – when dimensions of `cnots` and `angles` don’t align. **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. Matthew Amy, Parsiad Azimzadeh, and Michele Mosca. *On the controlled-NOT complexity of controlled-NOT–phase circuits.*, Quantum Science and Technology 4.1 (2018): 015002. [arXiv:1712.01859](https://arxiv.org/abs/1712.01859) ## Permutation Synthesis ### synth\_permutation\_depth\_lnn\_kms Synthesize a permutation circuit for a linear nearest-neighbor architecture using the Kutin, Moulton, Smithline method. This is the permutation synthesis algorithm from \[1], section 6. It synthesizes any permutation of n qubits over linear nearest-neighbor architecture using SWAP gates with depth at most $n$ and size at most $n(n-1)/2$ (where both depth and size are measured with respect to SWAPs). **Parameters** **pattern** ([*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)"")*] | np.ndarray\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – Permutation pattern, describing which qubits occupy the positions 0, 1, 2, etc. after applying the permutation. That is, `pattern[k] = m` when the permutation maps qubit `m` to position `k`. As an example, the pattern `[2, 4, 3, 0, 1]` means that qubit `2` goes to position `0`, qubit `4` goes to position `1`, etc. **Returns** The synthesized quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **References** 1. Samuel A. Kutin, David Petrie Moulton and Lawren M. Smithline. *Computation at a distance.*, [arXiv:quant-ph/0701194v1](https://arxiv.org/abs/quant-ph/0701194) ### synth\_permutation\_basic Synthesize a permutation circuit for a fully-connected architecture using sorting. More precisely, if the input permutation is a cycle of length `m`, then this creates a quantum circuit with `m-1` SWAPs (and of depth `m-1`); if the input permutation consists of several disjoint cycles, then each cycle is essentially treated independently. **Parameters** **pattern** ([*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)"")*] | np.ndarray\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – Permutation pattern, describing which qubits occupy the positions 0, 1, 2, etc. after applying the permutation. That is, `pattern[k] = m` when the permutation maps qubit `m` to position `k`. As an example, the pattern `[2, 4, 3, 0, 1]` means that qubit `2` goes to position `0`, qubit `4` goes to position `1`, etc. **Returns** The synthesized quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ### synth\_permutation\_acg Synthesize a permutation circuit for a fully-connected architecture using the Alon, Chung, Graham method. This produces a quantum circuit of depth 2 (measured in the number of SWAPs). This implementation is based on the Proposition 4.1 in reference \[1] with the detailed proof given in Theorem 2 in reference \[2] **Parameters** **pattern** ([*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)"")*] | np.ndarray\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]*) – Permutation pattern, describing which qubits occupy the positions 0, 1, 2, etc. after applying the permutation. That is, `pattern[k] = m` when the permutation maps qubit `m` to position `k`. As an example, the pattern `[2, 4, 3, 0, 1]` means that qubit `2` goes to position `0`, qubit `4` goes to position `1`, etc. **Returns** The synthesized quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **References** 1. N. Alon, F. R. K. Chung, and R. L. Graham. *Routing Permutations on Graphs Via Matchings.*, Proceedings of the Twenty-Fifth Annual ACM Symposium on Theory of Computing(1993). Pages 583–591. [(Extended abstract) 10.1145/167088.167239](https://doi.org/10.1145/167088.167239) 2. N. Alon, F. R. K. Chung, and R. L. Graham. *Routing Permutations on Graphs Via Matchings.*, [(Full paper)](https://www.cs.tau.ac.il/~nogaa/PDFS/r.pdf) ## Clifford Synthesis ### synth\_clifford\_full Decompose a [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") operator into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). For $N \leq 3$ qubits this is based on optimal CX-cost decomposition from reference \[1]. For $N > 3$ qubits this is done using the general non-optimal greedy compilation routine from reference \[3], which typically yields better CX cost compared to the AG method in \[2]. **Parameters** * **clifford** ([*Clifford*](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"")) – A Clifford operator. * **method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Optional, a synthesis method (`'AG'` or `'greedy'`). If set this overrides optimal decomposition for $N \leq 3$ qubits. **Returns** A circuit implementation of the Clifford. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **References** 1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the structure of the Clifford group*, [arXiv:2003.09412 \[quant-ph\]](https://arxiv.org/abs/2003.09412) 2. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). [arXiv:quant-ph/0406196](https://arxiv.org/abs/quant-ph/0406196) 3. Sergey Bravyi, Shaohan Hu, Dmitri Maslov, Ruslan Shaydulin, *Clifford Circuit Optimization with Templates and Symbolic Pauli Gates*, [arXiv:2105.02291 \[quant-ph\]](https://arxiv.org/abs/2105.02291) ### synth\_clifford\_ag Decompose a [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") operator into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") based on Aaronson-Gottesman method \[1]. **Parameters** **clifford** ([*Clifford*](qiskit.quantum_info.Clifford ""qiskit.quantum_info.operators.symplectic.clifford.Clifford"")) – A Clifford operator. **Returns** A circuit implementation of the Clifford. **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). [arXiv:quant-ph/0406196](https://arxiv.org/abs/quant-ph/0406196) ### synth\_clifford\_bm Optimal CX-cost decomposition of a [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") operator on 2 qubits or 3 qubits into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") based on the Bravyi-Maslov method \[1]. **Parameters** **clifford** ([*Clifford*](qiskit.quantum_info.Clifford ""qiskit.quantum_info.operators.symplectic.clifford.Clifford"")) – A Clifford operator. **Returns** A circuit implementation of the Clifford. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if Clifford is on more than 3 qubits. **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the structure of the Clifford group*, [arXiv:2003.09412 \[quant-ph\]](https://arxiv.org/abs/2003.09412) ### synth\_clifford\_greedy Decompose a [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") operator into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") based on the greedy Clifford compiler that is described in Appendix A of Bravyi, Hu, Maslov and Shaydulin \[1]. This method typically yields better CX cost compared to the Aaronson-Gottesman method. Note that this function only implements the greedy Clifford compiler from Appendix A of \[1], and not the templates and symbolic Pauli gates optimizations that are mentioned in the same paper. **Parameters** **clifford** ([*Clifford*](qiskit.quantum_info.Clifford ""qiskit.quantum_info.operators.symplectic.clifford.Clifford"")) – A Clifford operator. **Returns** A circuit implementation of the Clifford. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if symplectic Gaussian elimination fails. **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. Sergey Bravyi, Shaohan Hu, Dmitri Maslov, Ruslan Shaydulin, *Clifford Circuit Optimization with Templates and Symbolic Pauli Gates*, [arXiv:2105.02291 \[quant-ph\]](https://arxiv.org/abs/2105.02291) ### synth\_clifford\_layers , cz_synth_func=, cx_cz_synth_func=None, cz_func_reverse_qubits=False, validate=False)""> Synthesis of a [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") into layers, it provides a similar decomposition to the synthesis described in Lemma 8 of Bravyi and Maslov \[1]. For example, a 5-qubit Clifford circuit is decomposed into the following layers: ```python ┌─────┐┌─────┐┌────────┐┌─────┐┌─────┐┌─────┐┌─────┐┌────────┐ q_0: ┤0 ├┤0 ├┤0 ├┤0 ├┤0 ├┤0 ├┤0 ├┤0 ├ │ ││ ││ ││ ││ ││ ││ ││ │ q_1: ┤1 ├┤1 ├┤1 ├┤1 ├┤1 ├┤1 ├┤1 ├┤1 ├ │ ││ ││ ││ ││ ││ ││ ││ │ q_2: ┤2 S2 ├┤2 CZ ├┤2 CX_dg ├┤2 H2 ├┤2 S1 ├┤2 CZ ├┤2 H1 ├┤2 Pauli ├ │ ││ ││ ││ ││ ││ ││ ││ │ q_3: ┤3 ├┤3 ├┤3 ├┤3 ├┤3 ├┤3 ├┤3 ├┤3 ├ │ ││ ││ ││ ││ ││ ││ ││ │ q_4: ┤4 ├┤4 ├┤4 ├┤4 ├┤4 ├┤4 ├┤4 ├┤4 ├ └─────┘└─────┘└────────┘└─────┘└─────┘└─────┘└─────┘└────────┘ ``` This decomposition is for the default `cz_synth_func` and `cx_synth_func` functions, with other functions one may see slightly different decomposition. **Parameters** * **cliff** ([*Clifford*](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"")) – A Clifford operator. * **cx\_synth\_func** (*Callable\[\[np.ndarray],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]*) – A function to decompose the CX sub-circuit. It gets as input a boolean invertible matrix, and outputs a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). * **cz\_synth\_func** (*Callable\[\[np.ndarray],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*]*) – A function to decompose the CZ sub-circuit. It gets as input a boolean symmetric matrix, and outputs a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). * **cx\_cz\_synth\_func** (*Callable*) – optional, a function to decompose both sub-circuits CZ and CX. * **validate** (*Boolean*) – if True, validates the synthesis process. * **cz\_func\_reverse\_qubits** (*Boolean*) – True only if `cz_synth_func` is [`synth_cz_depth_line_mr()`](#qiskit.synthesis.synth_cz_depth_line_mr ""qiskit.synthesis.synth_cz_depth_line_mr""), since this function returns a circuit that reverts the order of qubits. **Returns** A circuit implementation of the Clifford. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **References** 1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the structure of the Clifford group*, [arXiv:2003.09412 \[quant-ph\]](https://arxiv.org/abs/2003.09412) ### synth\_clifford\_depth\_lnn Synthesis of a [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") into layers for linear-nearest neighbour connectivity. The depth of the synthesized n-qubit circuit is bounded by $7n+2$, which is not optimal. It should be replaced by a better algorithm that provides depth bounded by $7n-4$ \[3]. **Parameters** **cliff** ([*Clifford*](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"")) – a Clifford operator. **Returns** a circuit implementation of the Clifford. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **References** 1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the structure of the Clifford group*, [arXiv:2003.09412 \[quant-ph\]](https://arxiv.org/abs/2003.09412) 2. Dmitri Maslov, Martin Roetteler, *Shorter stabilizer circuits via Bruhat decomposition and quantum circuit transformations*, [arXiv:1705.09176](https://arxiv.org/abs/1705.09176). 3. Dmitri Maslov, Willers Yang, *CNOT circuits need little help to implement arbitrary Hadamard-free Clifford transformations they generate*, [arXiv:2210.16195](https://arxiv.org/abs/2210.16195). ## CNOTDihedral Synthesis ### synth\_cnotdihedral\_full Decompose a [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") element into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). For $N \leq 2$ qubits this is based on optimal CX-cost decomposition from reference \[1]. For $N > 2$ qubits this is done using the general non-optimal compilation routine from reference \[2]. **Parameters** **elem** ([*CNOTDihedral*](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.operators.dihedral.dihedral.CNOTDihedral"")) – A [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") element. **Returns** A circuit implementation of the [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") element. **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. Shelly Garion and Andrew W. Cross, *Synthesis of CNOT-Dihedral circuits with optimal number of two qubit gates*, [Quantum 4(369), 2020](https://quantum-journal.org/papers/q-2020-12-07-369/) 2. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). ### synth\_cnotdihedral\_two\_qubits Decompose a [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") element on a single qubit and two qubits into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). This decomposition has an optimal number of [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"")s. **Parameters** **elem** ([*CNOTDihedral*](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.operators.dihedral.dihedral.CNOTDihedral"")) – A [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") element. **Returns** A circuit implementation of the [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") element. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the element in not 1-qubit or 2-qubit [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral""). **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. Shelly Garion and Andrew W. Cross, *On the structure of the CNOT-Dihedral group*, [arXiv:2006.12042 \[quant-ph\]](https://arxiv.org/abs/2006.12042) ### synth\_cnotdihedral\_general Decompose a [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") element into a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). Decompose a general [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") elements. The number of CX gates is not necessarily optimal. For a decomposition of a 1-qubit or 2-qubit element, call [`synth_cnotdihedral_two_qubits()`](#qiskit.synthesis.synth_cnotdihedral_two_qubits ""qiskit.synthesis.synth_cnotdihedral_two_qubits""). **Parameters** **elem** ([*CNOTDihedral*](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.operators.dihedral.dihedral.CNOTDihedral"")) – A [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") element. **Returns** A circuit implementation of the [`CNOTDihedral`](qiskit.quantum_info.CNOTDihedral ""qiskit.quantum_info.CNOTDihedral"") element. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the element could not be decomposed into a circuit. **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). ## Stabilizer State Synthesis ### synth\_stabilizer\_layers , cz_func_reverse_qubits=False, validate=False)""> Synthesis of a stabilizer state into layers. It provides a similar decomposition to the synthesis described in Lemma 8 of reference \[1], without the initial Hadamard-free sub-circuit which do not affect the stabilizer state. For example, a 5-qubit stabilizer state is decomposed into the following layers: ```python ┌─────┐┌─────┐┌─────┐┌─────┐┌────────┐ q_0: ┤0 ├┤0 ├┤0 ├┤0 ├┤0 ├ │ ││ ││ ││ ││ │ q_1: ┤1 ├┤1 ├┤1 ├┤1 ├┤1 ├ │ ││ ││ ││ ││ │ q_2: ┤2 H2 ├┤2 S1 ├┤2 CZ ├┤2 H1 ├┤2 Pauli ├ │ ││ ││ ││ ││ │ q_3: ┤3 ├┤3 ├┤3 ├┤3 ├┤3 ├ │ ││ ││ ││ ││ │ q_4: ┤4 ├┤4 ├┤4 ├┤4 ├┤4 ├ └─────┘└─────┘└─────┘└─────┘└────────┘ ``` **Parameters** * **stab** ([*StabilizerState*](qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.states.stabilizerstate.StabilizerState"")) – A stabilizer state. * **cz\_synth\_func** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"")*\[\[*[*ndarray*](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray ""(in NumPy v1.26)"")*],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"")*]*) – A function to decompose the CZ sub-circuit. It gets as input a boolean symmetric matrix, and outputs a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""). * **cz\_func\_reverse\_qubits** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – `True` only if `cz_synth_func` is [`synth_cz_depth_line_mr()`](#qiskit.synthesis.synth_cz_depth_line_mr ""qiskit.synthesis.synth_cz_depth_line_mr""), since this function returns a circuit that reverts the order of qubits. * **validate** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True`, validates the synthesis process. **Returns** A circuit implementation of the stabilizer state. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the input is not a [`StabilizerState`](qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.StabilizerState""). **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the structure of the Clifford group*, [arXiv:2003.09412 \[quant-ph\]](https://arxiv.org/abs/2003.09412) ### synth\_stabilizer\_depth\_lnn Synthesis of an n-qubit stabilizer state for linear-nearest neighbour connectivity, in 2-qubit depth $2n+2$ and two distinct CX layers, using [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"")s and phase gates ([`SGate`](qiskit.circuit.library.SGate ""qiskit.circuit.library.SGate""), [`SdgGate`](qiskit.circuit.library.SdgGate ""qiskit.circuit.library.SdgGate"") or [`ZGate`](qiskit.circuit.library.ZGate ""qiskit.circuit.library.ZGate"")). **Parameters** **stab** ([*StabilizerState*](qiskit.quantum_info.StabilizerState ""qiskit.quantum_info.states.stabilizerstate.StabilizerState"")) – A stabilizer state. **Returns** A circuit implementation of the stabilizer state. **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the structure of the Clifford group*, [arXiv:2003.09412 \[quant-ph\]](https://arxiv.org/abs/2003.09412) 2. Dmitri Maslov, Martin Roetteler, *Shorter stabilizer circuits via Bruhat decomposition and quantum circuit transformations*, [arXiv:1705.09176](https://arxiv.org/abs/1705.09176). ### synth\_circuit\_from\_stabilizers Synthesis of a circuit that generates a state stabilized by the stabilizers using Gaussian elimination with Clifford gates. If the stabilizers are underconstrained, and `allow_underconstrained` is `True`, the circuit will output one of the states stabilized by the stabilizers. Based on stim implementation. **Parameters** * **stabilizers** ([*Collection*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Collection ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – List of stabilizer strings * **allow\_redundant** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Allow redundant stabilizers (i.e., some stabilizers can be products of the others) * **allow\_underconstrained** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Allow underconstrained set of stabilizers (i.e., the stabilizers do not specify a unique state) * **invert** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Return inverse circuit **Returns** A circuit that generates a state stabilized by `stabilizers`. **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – if the stabilizers are invalid, do not commute, or contradict each other, if the list is underconstrained and `allow_underconstrained` is `False`, or if the list is redundant and `allow_redundant` is `False`. **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. [https://github.com/quantumlib/Stim/blob/c0dd0b1c8125b2096cd54b6f72884a459e47fe3e/src/stim/stabilizers/conversions.inl#L469](https://github.com/quantumlib/Stim/blob/c0dd0b1c8125b2096cd54b6f72884a459e47fe3e/src/stim/stabilizers/conversions.inl#L469) 2. [https://quantumcomputing.stackexchange.com/questions/12721/how-to-calculate-destabilizer-group-of-toric-and-other-codes](https://quantumcomputing.stackexchange.com/questions/12721/how-to-calculate-destabilizer-group-of-toric-and-other-codes) ## Discrete Basis Synthesis | | | | --------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | [`SolovayKitaevDecomposition`](qiskit.synthesis.SolovayKitaevDecomposition ""qiskit.synthesis.SolovayKitaevDecomposition"")(\[...]) | The Solovay Kitaev discrete decomposition algorithm. | ### generate\_basic\_approximations Generates a list of `GateSequence`s with the gates in `basis_gates`. **Parameters** * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*Gate*](qiskit.circuit.Gate ""qiskit.circuit.Gate"")*]*) – The gates from which to create the sequences of gates. * **depth** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum depth of the approximations. * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – If provided, the basic approximations are stored in this file. **Returns** List of `GateSequence`s using the gates in `basis_gates`. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If `basis_gates` contains an invalid gate identifier. **Return type** [list](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")\[GateSequence] ## Basis Change Synthesis ### synth\_qft\_line Synthesis of a QFT circuit for a linear nearest neighbor connectivity. Based on Fig 2.b in Fowler et al. \[1]. Note that this method *reverts* the order of qubits in the circuit, compared to the original [`QFT`](qiskit.circuit.library.QFT ""qiskit.circuit.library.QFT"") code. Hence, the default value of the `do_swaps` parameter is `True` since it produces a circuit with fewer CX gates. **Parameters** * **num\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The number of qubits on which the QFT acts. * **approximation\_degree** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The degree of approximation (0 for no approximation). * **do\_swaps** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Whether to include the final swaps in the QFT. **Returns** A circuit implementation of the QFT circuit. **Return type** [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.quantumcircuit.QuantumCircuit"") **References** 1. A. G. Fowler, S. J. Devitt, and L. C. L. Hollenberg, *Implementation of Shor’s algorithm on a linear nearest neighbour qubit array*, Quantum Info. Comput. 4, 4 (July 2004), 237–251. [arXiv:quant-ph/0402196 \[quant-ph\]](https://arxiv.org/abs/quant-ph/0402196) ## Unitary Synthesis Decomposition of general $2^n \times 2^n$ unitary matrices for any number of qubits. ### qs\_decomposition Decomposes a unitary matrix into one and two qubit gates using Quantum Shannon Decomposition, This decomposition is described in Shende et al. \[1]. ```python ┌───┐ ┌───┐ ┌───┐ ┌───┐ ─┤ ├─ ───────┤ Rz├─────┤ Ry├─────┤ Rz├───── │ │ ≃ ┌───┐└─┬─┘┌───┐└─┬─┘┌───┐└─┬─┘┌───┐ /─┤ ├─ /─┤ ├──□──┤ ├──□──┤ ├──□──┤ ├ └───┘ └───┘ └───┘ └───┘ └───┘ ``` The number of [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"")s generated with the decomposition without optimizations is: $$ \frac{9}{16} 4^n - \frac{3}{2} 2^n $$ If `opt_a1 = True`, the default, the CX count is reduced by: $$ \frac{1}{3} 4^{n - 2} - 1. $$ If `opt_a2 = True`, the default, the CX count is reduced by: $$ 4^{n-2} - 1. $$ **Parameters** * **mat** (*np.ndarray*) – unitary matrix to decompose * **opt\_a1** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – whether to try optimization A.1 from Shende et al. \[1]. This should eliminate 1 `cx` per call. If `True`, [`CZGate`](qiskit.circuit.library.CZGate ""qiskit.circuit.library.CZGate"")s are left in the output. If desired these can be further decomposed to [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"")s. * **opt\_a2** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – whether to try optimization A.2 from Shende et al. \[1]. This decomposes two qubit unitaries into a diagonal gate and a two cx unitary and reduces overall cx count by $4^{n-2} - 1$. * **decomposer\_1q** (*Callable\[\[np.ndarray],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] | None*) – optional 1Q decomposer. If None, uses [`OneQubitEulerDecomposer`](qiskit.synthesis.OneQubitEulerDecomposer ""qiskit.synthesis.OneQubitEulerDecomposer""). * **decomposer\_2q** (*Callable\[\[np.ndarray],* [*QuantumCircuit*](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"")*] | None*) – optional 2Q decomposer. If None, uses [`TwoQubitBasisDecomposer`](qiskit.synthesis.TwoQubitBasisDecomposer ""qiskit.synthesis.TwoQubitBasisDecomposer""). **Returns** Decomposed quantum circuit. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") **References** 1. Shende, Bullock, Markov, *Synthesis of Quantum Logic Circuits*, [arXiv:0406176 \[quant-ph\]](https://arxiv.org/abs/quant-ph/0406176) The Approximate Quantum Compiler is available here: | | | | --------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | [`qiskit.synthesis.unitary.aqc`](qiskit.synthesis.unitary.aqc#module-qiskit.synthesis.unitary.aqc ""qiskit.synthesis.unitary.aqc"") | Approximate Quantum Compiler (qiskit.synthesis.unitary.aqc) | ## One-Qubit Synthesis | | | | ------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------- | | [`OneQubitEulerDecomposer`](qiskit.synthesis.OneQubitEulerDecomposer ""qiskit.synthesis.OneQubitEulerDecomposer"")(\[basis, use\_dag]) | A class for decomposing 1-qubit unitaries into Euler angle rotations. | ## Two-Qubit Synthesis | | | | ------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`TwoQubitBasisDecomposer`](qiskit.synthesis.TwoQubitBasisDecomposer ""qiskit.synthesis.TwoQubitBasisDecomposer"")(gate\[, ...]) | A class for decomposing 2-qubit unitaries into minimal number of uses of a 2-qubit basis gate. | | [`XXDecomposer`](qiskit.synthesis.XXDecomposer ""qiskit.synthesis.XXDecomposer"")(\[basis\_fidelity, euler\_basis, ...]) | A class for optimal decomposition of 2-qubit unitaries into 2-qubit basis gates of `XX` type (i.e., each locally equivalent to $CAN(\alpha, 0, 0)$ for a possibly varying $alpha$). | | [`TwoQubitWeylDecomposition`](qiskit.synthesis.TwoQubitWeylDecomposition ""qiskit.synthesis.TwoQubitWeylDecomposition"")(unitary\_matrix, \*) | Two-qubit Weyl decomposition. | ### two\_qubit\_cnot\_decompose This is an instance of [`TwoQubitBasisDecomposer`](qiskit.synthesis.TwoQubitBasisDecomposer ""qiskit.synthesis.TwoQubitBasisDecomposer"") that always uses `cx` as the KAK gate for the basis decomposition. You can use this function as a quick access to `cx`-based 2-qubit decompositions. **Parameters** * **unitary** ([*Operator*](qiskit.quantum_info.Operator ""qiskit.quantum_info.Operator"") *or np.ndarray*) – The 4x4 unitary to synthesize. * **basis\_fidelity** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *or None*) – If given the assumed fidelity for applications of [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate""). * **approximate** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True` approximate if `basis_fidelity` is less than 1.0. **Returns** The synthesized circuit of the input unitary. **Return type** [QuantumCircuit](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") ",repo/docs/api/qiskit/1.0\synthesis.mdx "--- title: transpiler description: API reference for qiskit.transpiler in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.transpiler --- # Transpiler `qiskit.transpiler` ## Overview Transpilation is the process of rewriting a given input circuit to match the topology of a specific quantum device, and/or to optimize the circuit for execution on present day noisy quantum systems. Most circuits must undergo a series of transformations that make them compatible with a given target device, and optimize them to reduce the effects of noise on the resulting outcomes. Rewriting quantum circuits to match hardware constraints and optimizing for performance can be far from trivial. The flow of logic in the rewriting tool chain need not be linear, and can often have iterative sub-loops, conditional branches, and other complex behaviors. That being said, the standard compilation flow follows the structure given below: ![../\_images/transpiling\_core\_steps.png](/images/api/qiskit/1.0/transpiling_core_steps.png) Qiskit has four pre-built transpilation pipelines available here: [`qiskit.transpiler.preset_passmanagers`](transpiler_preset#module-qiskit.transpiler.preset_passmanagers ""qiskit.transpiler.preset_passmanagers""). Unless the reader is familiar with quantum circuit optimization methods and their usage, it is best to use one of these ready-made routines. By default the preset pass managers are composed of six stages: 1. `init` - This stage runs any initial passes that are required before we start embedding the circuit to the backend. This typically involves unrolling custom instructions and converting the circuit to all 1 and 2 qubit gates. 2. `layout` - This stage applies a layout, mapping the virtual qubits in the circuit to the physical qubits on a backend. See [Layout Stage](#layout-stage) for more details. 3. `routing` - This stage runs after a layout has been applied and will inject gates (i.e. swaps) into the original circuit to make it compatible with the backend’s connectivity. See [Routing Stage](#routing-stage) for more details. 4. `translation` - This stage translates the gates in the circuit to the target backend’s basis set. See [Translation Stage](#translation-stage) for more details. 5. `optimization` - This stage runs the main optimization loop repeatedly until a condition (such as fixed depth) is reached. See [Optimization Stage](#optimization-stage) for more details. 6. `scheduling` - This stage is for any hardware-aware scheduling passes. See [Scheduling Stage](#scheduling-stage) for more details. When using [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile""), the implementation of each stage can be modified with the `*_method` arguments (e.g. `layout_method`). These can be set to one of the built-in methods and can also refer to available external plugins. See [`qiskit.transpiler.preset_passmanagers.plugin`](transpiler_plugins#module-qiskit.transpiler.preset_passmanagers.plugin ""qiskit.transpiler.preset_passmanagers.plugin"") for details on this plugin interface. ## Working with Preset Pass Managers Qiskit includes functions to build preset [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") objects. These preset passmanagers are used by the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") function for each optimization level. There are 4 optimization levels ranging from 0 to 3, where higher optimization levels take more time and computational effort but may yield a more optimal circuit. Optimization level 0 is intended for device characterization experiments and, as such, only maps the input circuit to the constraints of the target backend, without performing any optimizations. Optimization level 3 spends the most effort to optimize the circuit. However, as many of the optimization techniques in the transpiler are heuristic based, spending more computational effort does not always result in an improvement in the quality of the output circuit. If you’d like to work directly with a preset pass manager you can use the [`generate_preset_pass_manager()`](transpiler_preset#qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager ""qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager"") function to easily generate one. For example: ```python from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(num_qubits=5) pass_manager = generate_preset_pass_manager(3, backend) ``` which will generate a [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager"") object for optimization level 3 targeting the [`GenericBackendV2`](qiskit.providers.fake_provider.GenericBackendV2 ""qiskit.providers.fake_provider.GenericBackendV2"") backend (equivalent to what is used internally by [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") with `backend=GenericBackendV2(5)` and `optimization_level=3`). You can use this just like you would any other [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager""). However, because it is a [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager"") it also makes it easy to compose and/or replace stages of the pipeline. For example, if you wanted to run a custom scheduling stage using dynamical decoupling (via the [`PadDynamicalDecoupling`](qiskit.transpiler.passes.PadDynamicalDecoupling ""qiskit.transpiler.passes.PadDynamicalDecoupling"") pass) and also add initial logical optimization prior to routing, you would do something like (building off the previous example): ```python import numpy as np from qiskit.circuit.library import HGate, PhaseGate, RXGate, TdgGate, TGate, XGate from qiskit.transpiler import PassManager from qiskit.transpiler.passes import ( ALAPScheduleAnalysis, CXCancellation, InverseCancellation, PadDynamicalDecoupling, ) dd_sequence = [XGate(), XGate()] scheduling_pm = PassManager( [ ALAPScheduleAnalysis(target=backend.target), PadDynamicalDecoupling(target=backend.target, dd_sequence=dd_sequence), ] ) inverse_gate_list = [ HGate(), (RXGate(np.pi / 4), RXGate(-np.pi / 4)), (PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4)), (TGate(), TdgGate()), ] logical_opt = PassManager( [ CXCancellation(), InverseCancellation(inverse_gate_list), ] ) # Add pre-layout stage to run extra logical optimization pass_manager.pre_layout = logical_opt # Set scheduling stage to custom pass manager pass_manager.scheduling = scheduling_pm ``` Now, when the staged pass manager is run via the [`run()`](qiskit.transpiler.StagedPassManager#run ""qiskit.transpiler.StagedPassManager.run"") method, the `logical_opt` pass manager will be called before the `layout` stage, and the `scheduling_pm` pass manager will be used for the `scheduling` stage instead of the default. ## Custom Pass Managers In addition to modifying preset pass managers, it is also possible to construct a pass manager to build an entirely custom pipeline for transforming input circuits. You can use the [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager"") class directly to do this. You can define arbitrary stage names and populate them with a [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") instance. For example, the following code creates a new [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager"") that has 2 stages, `init` and `translation`.: ```python from qiskit.transpiler.passes import ( UnitarySynthesis, Collect2qBlocks, ConsolidateBlocks, UnitarySynthesis, Unroll3qOrMore, ) from qiskit.transpiler import PassManager, StagedPassManager basis_gates = [""rx"", ""ry"", ""rxx""] init = PassManager([UnitarySynthesis(basis_gates, min_qubits=3), Unroll3qOrMore()]) translate = PassManager( [ Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates), ] ) staged_pm = StagedPassManager( stages=[""init"", ""translation""], init=init, translation=translate ) ``` There is no limit on the number of stages you can put in a [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager""). The [Stage Generator Functions](transpiler_preset#stage-generators) may be useful for the construction of custom `generate_embed_passmanager` generates a [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") to “embed” a selected initial [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") from a layout pass to the specified target device. ## Representing Quantum Computers To be able to compile a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") for a specific backend, the transpiler needs a specialized representation of that backend, including its constraints, instruction set, qubit properties, and more, to be able to compile and optimize effectively. While the [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") class defines an interface for querying and interacting with backends, its scope is larger than just the transpiler’s needs including managing job submission and potentially interfacing with remote services. The specific information needed by the transpiler is described by the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") class For example, to construct a simple [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object, one can iteratively add descriptions of the instructions it supports: ```python from qiskit.circuit import Parameter, Measure from qiskit.transpiler import Target, InstructionProperties from qiskit.circuit.library import UGate, RZGate, RXGate, RYGate, CXGate, CZGate target = Target(num_qubits=3) target.add_instruction(CXGate(), {(0, 1): InstructionProperties(error=.0001, duration=5e-7)}) target.add_instruction( UGate(Parameter('theta'), Parameter('phi'), Parameter('lam')), { (0,): InstructionProperties(error=.00001, duration=5e-8), (1,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RZGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RYGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RXGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( CZGate(), { (1, 2): InstructionProperties(error=.0001, duration=5e-7), (2, 0): InstructionProperties(error=.0001, duration=5e-7) } ) target.add_instruction( Measure(), { (0,): InstructionProperties(error=.001, duration=5e-5), (1,): InstructionProperties(error=.002, duration=6e-5), (2,): InstructionProperties(error=.2, duration=5e-7) } ) print(target) ``` ```python Target Number of qubits: 3 Instructions: cx (0, 1): Duration: 5e-07 sec. Error Rate: 0.0001 u (0,): Duration: 5e-08 sec. Error Rate: 1e-05 (1,): Duration: 6e-08 sec. Error Rate: 2e-05 rz (1,): Duration: 5e-08 sec. Error Rate: 1e-05 (2,): Duration: 6e-08 sec. Error Rate: 2e-05 ry (1,): Duration: 5e-08 sec. Error Rate: 1e-05 (2,): Duration: 6e-08 sec. Error Rate: 2e-05 rx (1,): Duration: 5e-08 sec. Error Rate: 1e-05 (2,): Duration: 6e-08 sec. Error Rate: 2e-05 cz (1, 2): Duration: 5e-07 sec. Error Rate: 0.0001 (2, 0): Duration: 5e-07 sec. Error Rate: 0.0001 measure (0,): Duration: 5e-05 sec. Error Rate: 0.001 (1,): Duration: 6e-05 sec. Error Rate: 0.002 (2,): Duration: 5e-07 sec. Error Rate: 0.2 ``` This [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") represents a 3 qubit backend that supports [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"") between qubits 0 and 1, [`UGate`](qiskit.circuit.library.UGate ""qiskit.circuit.library.UGate"") on qubits 0 and 1, [`RZGate`](qiskit.circuit.library.RZGate ""qiskit.circuit.library.RZGate""), [`RXGate`](qiskit.circuit.library.RXGate ""qiskit.circuit.library.RXGate""), and [`RYGate`](qiskit.circuit.library.RYGate ""qiskit.circuit.library.RYGate"") on qubits 1 and 2, [`CZGate`](qiskit.circuit.library.CZGate ""qiskit.circuit.library.CZGate"") between qubits 1 and 2, and qubits 2 and 0, and [`Measure`](qiskit.circuit.library.Measure ""qiskit.circuit.library.Measure"") on all qubits. There are also specific data structures to represent a specific subset of information from the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target""). For example, the [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") class is used to solely represent the connectivity constraints of a backend as a directed graph. A coupling map can be generated from a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") using the [`Target.build_coupling_map()`](qiskit.transpiler.Target#build_coupling_map ""qiskit.transpiler.Target.build_coupling_map"") method. These data structures typically pre-date the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") class but are still used by some transpiler passes that do not work natively with a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") instance yet or when dealing with backends that aren’t using the latest [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") interface. For example, if we wanted to visualize the [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") for the example 3 qubit [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") above: ```python from qiskit.circuit import Parameter, Measure from qiskit.transpiler import Target, InstructionProperties from qiskit.circuit.library import UGate, RZGate, RXGate, RYGate, CXGate, CZGate target = Target(num_qubits=3) target.add_instruction(CXGate(), {(0, 1): InstructionProperties(error=.0001, duration=5e-7)}) target.add_instruction( UGate(Parameter('theta'), Parameter('phi'), Parameter('lam')), { (0,): InstructionProperties(error=.00001, duration=5e-8), (1,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RZGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RYGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RXGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( CZGate(), { (1, 2): InstructionProperties(error=.0001, duration=5e-7), (2, 0): InstructionProperties(error=.0001, duration=5e-7) } ) target.add_instruction( Measure(), { (0,): InstructionProperties(error=.001, duration=5e-5), (1,): InstructionProperties(error=.002, duration=6e-5), (2,): InstructionProperties(error=.2, duration=5e-7) } ) target.build_coupling_map().draw() ``` This shows the global connectivity of the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") which is the combination of the supported qubits for [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"") and [`CZGate`](qiskit.circuit.library.CZGate ""qiskit.circuit.library.CZGate""). To see the individual connectivity, you can pass the operation name to `CouplingMap.build_coupling_map()`: ```python from qiskit.circuit import Parameter, Measure from qiskit.transpiler import Target, InstructionProperties from qiskit.circuit.library import UGate, RZGate, RXGate, RYGate, CXGate, CZGate target = Target(num_qubits=3) target.add_instruction(CXGate(), {(0, 1): InstructionProperties(error=.0001, duration=5e-7)}) target.add_instruction( UGate(Parameter('theta'), Parameter('phi'), Parameter('lam')), { (0,): InstructionProperties(error=.00001, duration=5e-8), (1,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RZGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RYGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RXGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( CZGate(), { (1, 2): InstructionProperties(error=.0001, duration=5e-7), (2, 0): InstructionProperties(error=.0001, duration=5e-7) } ) target.add_instruction( Measure(), { (0,): InstructionProperties(error=.001, duration=5e-5), (1,): InstructionProperties(error=.002, duration=6e-5), (2,): InstructionProperties(error=.2, duration=5e-7) } ) target.build_coupling_map('cx').draw() ``` ```python from qiskit.circuit import Parameter, Measure from qiskit.transpiler import Target, InstructionProperties from qiskit.circuit.library import UGate, RZGate, RXGate, RYGate, CXGate, CZGate target = Target(num_qubits=3) target.add_instruction(CXGate(), {(0, 1): InstructionProperties(error=.0001, duration=5e-7)}) target.add_instruction( UGate(Parameter('theta'), Parameter('phi'), Parameter('lam')), { (0,): InstructionProperties(error=.00001, duration=5e-8), (1,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RZGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RYGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( RXGate(Parameter('theta')), { (1,): InstructionProperties(error=.00001, duration=5e-8), (2,): InstructionProperties(error=.00002, duration=6e-8) } ) target.add_instruction( CZGate(), { (1, 2): InstructionProperties(error=.0001, duration=5e-7), (2, 0): InstructionProperties(error=.0001, duration=5e-7) } ) target.add_instruction( Measure(), { (0,): InstructionProperties(error=.001, duration=5e-5), (1,): InstructionProperties(error=.002, duration=6e-5), (2,): InstructionProperties(error=.2, duration=5e-7) } ) target.build_coupling_map('cz').draw() ``` ## Transpiler Stage Details Below are a description of the default transpiler stages and the problems they solve. The default passes used for each stage are described, but the specifics are configurable via the `*_method` keyword arguments for the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") and [`generate_preset_pass_manager()`](transpiler_preset#qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager ""qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager"") functions which can be used to override the methods described in this section. ### Translation Stage When writing a quantum circuit you are free to use any quantum gate (unitary operator) that you like, along with a collection of non-gate operations such as qubit measurements and reset operations. However, most quantum devices only natively support a handful of quantum gates and non-gate operations. The allowed instructions for a given backend can be found by querying the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") for the devices: ```python from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(5) print(backend.target) ``` Every quantum circuit run on the target device must be expressed using only these instructions. For example, to run a simple phase estimation circuit: ```python import numpy as np from qiskit import QuantumCircuit from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(5) qc = QuantumCircuit(2, 1) qc.h(0) qc.x(1) qc.cp(np.pi/4, 0, 1) qc.h(0) qc.measure([0], [0]) qc.draw(output='mpl') ``` ![../\_images/transpiler-4.png](/images/api/qiskit/1.0/transpiler-4.png) We have $H$, $X$, and controlled-$P$ gates, none of which are in our device’s basis gate set, and thus must be translated. We can transpile the circuit to show what it will look like in the native gate set of the target IBM Quantum device (the [`GenericBackendV2`](qiskit.providers.fake_provider.GenericBackendV2 ""qiskit.providers.fake_provider.GenericBackendV2"") class generates a fake backend with a specified number of qubits for test purposes): ```python from qiskit import transpile from qiskit import QuantumCircuit from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(5) qc = QuantumCircuit(2, 1) qc.h(0) qc.x(1) qc.cp(np.pi/4, 0, 1) qc.h(0) qc.measure([0], [0]) qc_basis = transpile(qc, backend) qc_basis.draw(output='mpl') ``` ![../\_images/transpiler-5.png](/images/api/qiskit/1.0/transpiler-5.png) A few things to highlight. First, the circuit has gotten longer with respect to the original. This can be verified by checking the depth of both circuits: ```python print('Original depth:', qc.depth(), 'Decomposed Depth:', qc_basis.depth()) ``` ```python Original depth: 4 Decomposed Depth: 10 ``` Second, although we had a single controlled gate, the fact that it was not in the basis set means that, when expanded, it requires more than a single [`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"") to implement. All said, unrolling to the basis set of gates leads to an increase in the depth of a quantum circuit and the number of gates. It is important to highlight two special cases: 1. If A swap gate is not a native gate and must be decomposed this requires three CNOT gates: ```python from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(5) print(backend.operation_names) ``` ```python ['id', 'rz', 'sx', 'x', 'cx', 'measure', 'delay'] ``` As a product of three CNOT gates, swap gates are expensive operations to perform on noisy quantum devices. However, such operations are usually necessary for embedding a circuit into the limited gate connectivities of many devices. Thus, minimizing the number of swap gates in a circuit is a primary goal in the transpilation process. 2. A Toffoli, or controlled-controlled-not gate (`ccx`), is a three-qubit gate. Given that our basis gate set includes only single- and two-qubit gates, it is obvious that this gate must be decomposed. This decomposition is quite costly: ```python from qiskit.circuit import QuantumCircuit ccx_circ = QuantumCircuit(3) ccx_circ.ccx(0, 1, 2) ccx_circ.decompose().draw(output='mpl') ``` ![../\_images/transpiler-6.png](/images/api/qiskit/1.0/transpiler-6.png) For every Toffoli gate in a quantum circuit, the hardware may execute up to six CNOT gates, and a handful of single-qubit gates. From this example, it should be clear that any algorithm that makes use of multiple Toffoli gates will end up as a circuit with large depth and will therefore be appreciably affected by noise and gate errors. ### Layout Stage Quantum circuits are abstract entities whose qubits are “virtual” representations of actual qubits used in computations. We need to be able to map these virtual qubits in a one-to-one manner to the “physical” qubits in an actual quantum device. ![../\_images/mapping.png](/images/api/qiskit/1.0/mapping.png) By default, qiskit will do this mapping for you. The choice of mapping depends on the properties of the circuit, the particular device you are targeting, and the optimization level that is chosen. The choice of initial layout is extremely important for minimizing the number of swap operations needed to map the input circuit onto the device topology and for minimizing the loss due to non-uniform noise properties across a device. Due to the importance of this stage, the preset pass managers try a few different methods to find the best layout. Typically this involves 2 steps: first, trying to find a “perfect” layout (a layout which does not require any swap operations), and then, a heuristic pass that tries to find the best layout to use if a perfect layout cannot be found. There are 2 passes typically used for the first stage: * [`VF2Layout`](qiskit.transpiler.passes.VF2Layout ""qiskit.transpiler.passes.VF2Layout""): Models layout selection as a subgraph isomorphism problem and tries to find a subgraph of the connectivity graph that is isomorphic to the graph of 2 qubit interactions in the circuit. If more than one isomorphic mapping is found a scoring heuristic is run to select the mapping which would result in the lowest average error when executing the circuit. * [`TrivialLayout`](qiskit.transpiler.passes.TrivialLayout ""qiskit.transpiler.passes.TrivialLayout""): Maps each virtual qubit to the same numbered physical qubit on the device, i.e. `[0,1,2,3,4]` -> `[0,1,2,3,4]`. This is historical behavior used only in `optimization_level=1` to try to find a perfect layout. If it fails to do so, [`VF2Layout`](qiskit.transpiler.passes.VF2Layout ""qiskit.transpiler.passes.VF2Layout"") is tried next. Next, for the heuristic stage, 2 passes are used by default: * [`SabreLayout`](qiskit.transpiler.passes.SabreLayout ""qiskit.transpiler.passes.SabreLayout""): Selects a layout by starting from an initial random layout and then repeatedly running a routing algorithm (by default [`SabreSwap`](qiskit.transpiler.passes.SabreSwap ""qiskit.transpiler.passes.SabreSwap"")) both forward and backward over the circuit, using the permutation caused by swap insertions to adjust that initial random layout. For more details you can refer to the paper describing the algorithm: [arXiv:1809.02573](https://arxiv.org/abs/1809.02573) [`SabreLayout`](qiskit.transpiler.passes.SabreLayout ""qiskit.transpiler.passes.SabreLayout"") is used to select a layout if a perfect layout isn’t found for optimization levels 1, 2, and 3. * [`TrivialLayout`](qiskit.transpiler.passes.TrivialLayout ""qiskit.transpiler.passes.TrivialLayout""): Always used for the layout at optimization level 0. * [`DenseLayout`](qiskit.transpiler.passes.DenseLayout ""qiskit.transpiler.passes.DenseLayout""): Finds the sub-graph of the device with greatest connectivity that has the same number of qubits as the circuit. Used for optimization level 1 if there are control flow operations (such as [`IfElseOp`](qiskit.circuit.IfElseOp ""qiskit.circuit.IfElseOp"")) present in the circuit. Let’s see what layouts are automatically picked at various optimization levels. The circuits returned by [`qiskit.compiler.transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") are annotated with this initial layout information, and we can view this layout selection graphically using [`qiskit.visualization.plot_circuit_layout()`](qiskit.visualization.plot_circuit_layout ""qiskit.visualization.plot_circuit_layout""): ```python from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import Fake5QV1 backend = Fake5QV1() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) ghz.draw(output='mpl') ``` ![../\_images/transpiler-7.png](/images/api/qiskit/1.0/transpiler-7.png) * **Layout Using Optimization Level 0** > ```python > from qiskit import QuantumCircuit, transpile > from qiskit.visualization import plot_circuit_layout > from qiskit.providers.fake_provider import Fake5QV1 > backend = Fake5QV1() > > ghz = QuantumCircuit(3, 3) > ghz.h(0) > ghz.cx(0,range(1,3)) > ghz.barrier() > ghz.measure(range(3), range(3)) > > new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) > plot_circuit_layout(new_circ_lv0, backend) > ``` > > ![../\_images/transpiler-8.png](/images/api/qiskit/1.0/transpiler-8.png) * **Layout Using Optimization Level 3** > ```python > from qiskit import QuantumCircuit, transpile > from qiskit.visualization import plot_circuit_layout > from qiskit.providers.fake_provider import Fake5QV1 > backend = Fake5QV1() > > ghz = QuantumCircuit(3, 3) > ghz.h(0) > ghz.cx(0,range(1,3)) > ghz.barrier() > ghz.measure(range(3), range(3)) > > new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) > plot_circuit_layout(new_circ_lv3, backend) > ``` > > ![../\_images/transpiler-9.png](/images/api/qiskit/1.0/transpiler-9.png) It is possible to override automatic layout selection by specifying an initial layout. To do so we can pass a list of integers to [`qiskit.compiler.transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") via the initial\_layout keyword argument, where the index labels the virtual qubit in the circuit and the corresponding value is the label for the physical qubit to map onto: ```python from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import Fake5QV1 backend = Fake5QV1() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) # Virtual -> physical # 0 -> 3 # 1 -> 4 # 2 -> 2 my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2]) plot_circuit_layout(my_ghz, backend) ``` ![../\_images/transpiler-10.png](/images/api/qiskit/1.0/transpiler-10.png) ### Routing Stage In order to implement a 2-qubit gate between qubits in a quantum circuit that are not directly connected on a quantum device, one or more swap gates must be inserted into the circuit to move the qubit states around until they are adjacent on the device gate map. Each swap gate typically represents an expensive and noisy operation to perform. Thus, finding the minimum number of swap gates needed to map a circuit onto a given device, is an important step (if not the most important) in the whole execution process. However, as with many important things in life, finding the optimal swap mapping is hard. In fact it is in a class of problems called NP-hard, and is thus prohibitively expensive to compute for all but the smallest quantum devices and input circuits. To get around this, by default Qiskit uses a stochastic heuristic algorithm called [`SabreSwap`](qiskit.transpiler.passes.SabreSwap ""qiskit.transpiler.passes.SabreSwap"") to compute a good, but not necessarily optimal swap mapping. The use of a stochastic method means the circuits generated by [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") are not guaranteed to be the same over repeated runs. Indeed, running the same circuit repeatedly will in general result in a distribution of circuit depths and gate counts at the output. In order to highlight this, we run a GHZ circuit 100 times, using a “bad” (disconnected) `initial_layout` in a heavy hex coupling map: ![../\_images/transpiler-11.png](/images/api/qiskit/1.0/transpiler-11.png) ```python import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler import CouplingMap coupling_map = CouplingMap.from_heavy_hex(3) backend = GenericBackendV2(coupling_map.size(), coupling_map=coupling_map) ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] for i in range(100): depths.append( transpile( ghz, backend, seed_transpiler=i, layout_method='trivial' # Fixed layout mapped in circuit order ).depth() ) plt.figure(figsize=(8, 6)) plt.hist(depths, align='left', color='#AC557C') plt.xlabel('Depth', fontsize=14) plt.ylabel('Counts', fontsize=14); ``` ![../\_images/transpiler-12.png](/images/api/qiskit/1.0/transpiler-12.png) This distribution is quite wide, signaling the difficulty the swap mapper is having in computing the best mapping. Most circuits will have a distribution of depths, perhaps not as wide as this one, due to the stochastic nature of the default swap mapper. Of course, we want the best circuit we can get, especially in cases where the depth is critical to success or failure. The [`SabreSwap`](qiskit.transpiler.passes.SabreSwap ""qiskit.transpiler.passes.SabreSwap"") pass will by default by run its algorithm in parallel with multiple seed values and select the output which uses the fewest swaps. If you would like to increase the number of trials [`SabreSwap`](qiskit.transpiler.passes.SabreSwap ""qiskit.transpiler.passes.SabreSwap"") runs you can refer to [Working with Preset Pass Managers](#working-with-preset-pass-managers) and modify the `routing` stage with a custom instance of [`SabreSwap`](qiskit.transpiler.passes.SabreSwap ""qiskit.transpiler.passes.SabreSwap"") with a larger value for the `trials` argument. Typically, following the swap mapper, the routing stage in the preset pass managers also includes running the [`VF2PostLayout`](qiskit.transpiler.passes.VF2PostLayout ""qiskit.transpiler.passes.VF2PostLayout"") pass. As its name implies, [`VF2PostLayout`](qiskit.transpiler.passes.VF2PostLayout ""qiskit.transpiler.passes.VF2PostLayout"") uses the same basic algorithm as [`VF2Layout`](qiskit.transpiler.passes.VF2Layout ""qiskit.transpiler.passes.VF2Layout""), but instead of using it to find a perfect initial layout, it is designed to run after mapping and try to find a layout on qubits with lower error rates which will result in better output fidelity when running the circuit. The details of this algorithm are described in [arXiv:2209.15512](https://arxiv.org/abs/2209.15512). ### Optimization Stage Decomposing quantum circuits into the basis gate set of the target device, and the addition of swap gates needed to match hardware topology, conspire to increase the depth and gate count of quantum circuits. Fortunately many routines for optimizing circuits by combining or eliminating gates exist. In some cases these methods are so effective the output circuits have lower depth than the inputs. In other cases, not much can be done, and the computation may be difficult to perform on noisy devices. Different gate optimizations are turned on with different `optimization_level` values. Below we show the benefits gained from setting the optimization level higher: The output from [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") varies due to the stochastic swap mapper. So the numbers below will likely change each time you run the code. ![../\_images/transpiler-13.png](/images/api/qiskit/1.0/transpiler-13.png) ```python import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(16) ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel(""Optimization Level"") ax1.set_ylabel(""Depth"") ax1.set_title(""Output Circuit Depth"") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel(""Optimization Level"") ax2.set_ylabel(""Number of gates"") ax2.legend() ax2.set_title(""Number of output circuit gates"") fig.tight_layout() plt.show() ``` ![../\_images/transpiler-14.png](/images/api/qiskit/1.0/transpiler-14.png) ### Scheduling Stage After the circuit has been translated to the target basis, mapped to the device, and optimized, a scheduling phase can be applied to optionally account for all the idle time in the circuit. At a high level, the scheduling can be thought of as inserting delays into the circuit to account for idle time on the qubits between the execution of instructions. For example, if we start with a circuit such as: ![../\_images/transpiler-15.png](/images/api/qiskit/1.0/transpiler-15.png) we can then call [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") on it with `scheduling_method` set: ```python from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(5) ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method=""asap"") circ.draw(output='mpl') ``` ![../\_images/transpiler-16.png](/images/api/qiskit/1.0/transpiler-16.png) You can see here that the transpiler inserted [`Delay`](qiskit.circuit.Delay ""qiskit.circuit.Delay"") instructions to account for idle time on each qubit. To get a better idea of the timing of the circuit we can also look at it with the `timeline.draw()` function: ![../\_images/transpiler-17.png](/images/api/qiskit/1.0/transpiler-17.png) The scheduling of a circuit involves two parts: analysis and constraint mapping, followed by a padding pass. The first part requires running a scheduling analysis pass such as `ALAPSchedulingAnalysis` or `ASAPSchedulingAnalysis` which analyzes the circuit and records the start time of each instruction in the circuit using a scheduling algorithm (“as late as possible” for `ALAPSchedulingAnalysis` and “as soon as possible” for `ASAPSchedulingAnalysis`) in the property set. Once the circuit has an initial scheduling, additional passes can be run to account for any timing constraints on the target backend, such as alignment constraints. This is typically done with the [`ConstrainedReschedule`](qiskit.transpiler.passes.ConstrainedReschedule ""qiskit.transpiler.passes.ConstrainedReschedule"") pass which will adjust the scheduling set in the property set to the constraints of the target backend. Once all the scheduling and adjustments/rescheduling are finished, a padding pass, such as [`PadDelay`](qiskit.transpiler.passes.PadDelay ""qiskit.transpiler.passes.PadDelay"") or [`PadDynamicalDecoupling`](qiskit.transpiler.passes.PadDynamicalDecoupling ""qiskit.transpiler.passes.PadDynamicalDecoupling"") is run to insert the instructions into the circuit, which completes the scheduling. #### Scheduling Analysis with control flow instructions When running scheduling analysis passes on a circuit, you must keep in mind that there are additional constraints on classical conditions and control flow instructions. This section covers the details of these additional constraints that any scheduling pass will need to account for. ##### Topological node ordering in scheduling The DAG representation of `QuantumCircuit` respects the node ordering in the classical register wires, though theoretically two conditional instructions conditioned on the same register could commute, i.e. read-access to the classical register doesn’t change its state. ```python qc = QuantumCircuit(2, 1) qc.delay(100, 0) qc.x(0).c_if(0, True) qc.x(1).c_if(0, True) ``` The scheduler SHOULD comply with the above topological ordering policy of the DAG circuit. Accordingly, the asap-scheduled circuit will become ```python ┌────────────────┐ ┌───┐ q_0: ┤ Delay(100[dt]) ├───┤ X ├────────────── ├────────────────┤ └─╥─┘ ┌───┐ q_1: ┤ Delay(100[dt]) ├─────╫────────┤ X ├─── └────────────────┘ ║ └─╥─┘ ┌────╨────┐┌────╨────┐ c: 1/══════════════════╡ c_0=0x1 ╞╡ c_0=0x1 ╞ └─────────┘└─────────┘ ``` Note that this scheduling might be inefficient in some cases, because the second conditional operation could start without waiting for the 100 dt delay. However, any additional optimization should be done in a different pass, not to break the topological ordering of the original circuit. ##### Realistic control flow scheduling (respecting microarchitecture) In the dispersive QND readout scheme, the qubit (Q) is measured by sending a microwave stimulus, followed by a resonator ring-down (depopulation). This microwave signal is recorded in the buffer memory (B) with the hardware kernel, then a discriminated (D) binary value is moved to the classical register (C). A sequence from t0 to t1 of the measure instruction interval could be modeled as follows: ```python Q ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ B ░░▒▒▒▒▒▒▒▒░░░░░░░░░ D ░░░░░░░░░░▒▒▒▒▒▒░░░ C ░░░░░░░░░░░░░░░░▒▒░ ``` However, the [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") representation is not accurate enough to represent this model. In the circuit representation, the corresponding [`circuit.Qubit`](qiskit.circuit.Qubit ""qiskit.circuit.Qubit"") is occupied by the stimulus microwave signal during the first half of the interval, and the [`Clbit`](qiskit.circuit.Clbit ""qiskit.circuit.Clbit"") is only occupied at the very end of the interval. The lack of precision representing the physical model may induce edge cases in the scheduling: ```python ┌───┐ q_0: ───┤ X ├────── └─╥─┘ ┌─┐ q_1: ─────╫─────┤M├ ┌────╨────┐└╥┘ c: 1/╡ c_0=0x1 ╞═╩═ └─────────┘ 0 ``` In this example, a user may intend to measure the state of `q_1` after the [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate"") is applied to `q_0`. This is the correct interpretation from the viewpoint of topological node ordering, i.e. The [`XGate`](qiskit.circuit.library.XGate ""qiskit.circuit.library.XGate"") node comes in front of the [`Measure`](qiskit.circuit.library.Measure ""qiskit.circuit.library.Measure"") node. However, according to the measurement model above, the data in the register is unchanged during the application of the stimulus, so two nodes are simultaneously operated. If one tries to alap-schedule this circuit, it may return following circuit: ```python ┌────────────────┐ ┌───┐ q_0: ┤ Delay(500[dt]) ├───┤ X ├────── └────────────────┘ └─╥─┘ ┌─┐ q_1: ───────────────────────╫─────┤M├ ┌────╨────┐└╥┘ c: 1/══════════════════╡ c_0=0x1 ╞═╩═ └─────────┘ 0 ``` Note that there is no delay on the `q_1` wire, and the measure instruction immediately starts after t=0, while the conditional gate starts after the delay. It looks like the topological ordering between the nodes is flipped in the scheduled view. This behavior can be understood by considering the control flow model described above, ```python : Quantum Circuit, first-measure 0 ░░░░░░░░░░░░▒▒▒▒▒▒░ 1 ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ : In wire q0 Q ░░░░░░░░░░░░░░░▒▒▒░ C ░░░░░░░░░░░░▒▒░░░░░ : In wire q1 Q ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ B ░░▒▒▒▒▒▒▒▒░░░░░░░░░ D ░░░░░░░░░░▒▒▒▒▒▒░░░ C ░░░░░░░░░░░░░░░░▒▒░ ``` Since there is no qubit register overlap between Q0 and Q1, the node ordering is determined by the shared classical register C. As you can see, the execution order is still preserved on C, i.e. read C then apply `XGate`, finally store the measured outcome in C. But because `DAGOpNode` cannot define different durations for the associated registers, the time ordering of the two nodes is inverted. This behavior can be controlled by `clbit_write_latency` and `conditional_latency`. `clbit_write_latency` determines the delay of the register write-access from the beginning of the measure instruction (t0), while `conditional_latency` determines the delay of conditional gate operations with respect to t0, which is determined by the register read-access. This information is accessible in the backend configuration and should be copied to the pass manager property set before the pass is called. Due to default latencies, the alap-scheduled circuit of above example may become ```python ┌───┐ q_0: ───┤ X ├────── └─╥─┘ ┌─┐ q_1: ─────╫─────┤M├ ┌────╨────┐└╥┘ c: 1/╡ c_0=0x1 ╞═╩═ └─────────┘ 0 ``` If the backend microarchitecture supports smart scheduling of the control flow instructions, such as separately scheduling qubits and classical registers, the insertion of the delay yields an unnecessarily longer total execution time. ```python : Quantum Circuit, first-XGate 0 ░▒▒▒░░░░░░░░░░░░░░░ 1 ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ : In wire q0 Q ░▒▒▒░░░░░░░░░░░░░░░ C ░░░░░░░░░░░░░░░░░░░ (zero latency) : In wire q1 Q ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ C ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ (zero latency, scheduled after C0 read-access) ``` However, this result is much more intuitive in the topological ordering view. If a finite conditional latency value is provided, for example, 30 dt, the circuit is scheduled as follows: ```python ┌───────────────┐ ┌───┐ q_0: ┤ Delay(30[dt]) ├───┤ X ├────── ├───────────────┤ └─╥─┘ ┌─┐ q_1: ┤ Delay(30[dt]) ├─────╫─────┤M├ └───────────────┘┌────╨────┐└╥┘ c: 1/═════════════════╡ c_0=0x1 ╞═╩═ └─────────┘ 0 ``` with the timing model: ```python : Quantum Circuit, first-xgate 0 ░░▒▒▒░░░░░░░░░░░░░░░ 1 ░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ : In wire q0 Q ░░▒▒▒░░░░░░░░░░░░░░░ C ░▒░░░░░░░░░░░░░░░░░░ (30dt latency) : In wire q1 Q ░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ C ░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ ``` See [https://arxiv.org/abs/2102.01682](https://arxiv.org/abs/2102.01682) for more details. ## Transpiler API ### Transpiler Target | | | | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"")(\[description, num\_qubits, dt, ...]) | The intent of the `Target` object is to inform Qiskit's compiler about the constraints of a particular backend so the compiler can compile an input circuit to something that works and is optimized for a device. | | [`InstructionProperties`](qiskit.transpiler.InstructionProperties ""qiskit.transpiler.InstructionProperties"")(\[duration, error, ...]) | A representation of the properties of a gate implementation. | ### Pass Manager Construction | | | | ------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager"")(\[stages]) | A pass manager pipeline built from individual stages. | | [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"")(\[passes, max\_iteration]) | Manager for a set of Passes and their scheduling during transpilation. | | [`PassManagerConfig`](qiskit.transpiler.PassManagerConfig ""qiskit.transpiler.PassManagerConfig"")(\[initial\_layout, ...]) | Pass Manager Configuration. | ### Layout and Topology | | | | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ | | [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"")(\[input\_dict]) | Two-ways dict to represent a Layout. | | [`CouplingMap`](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")(\[couplinglist, description]) | Directed graph specifying fixed coupling. | | [`TranspileLayout`](qiskit.transpiler.TranspileLayout ""qiskit.transpiler.TranspileLayout"")(initial\_layout, ...\[, ...]) | Layout attributes from output circuit from transpiler. | ### Scheduling | | | | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | | [`InstructionDurations`](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"")(\[instruction\_durations, dt]) | Helper class to provide durations of instructions for scheduling. | ### Abstract Passes | | | | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | [`TransformationPass`](qiskit.transpiler.TransformationPass ""qiskit.transpiler.TransformationPass"")(\*args, \*\*kwargs) | A transformation pass: change DAG, not property set. | | [`AnalysisPass`](qiskit.transpiler.AnalysisPass ""qiskit.transpiler.AnalysisPass"")(\*args, \*\*kwargs) | An analysis pass: change property set, not DAG. | ### Exceptions #### TranspilerError Exceptions raised during transpilation. Set the error message. #### TranspilerAccessError DEPRECATED: Exception of access error in the transpiler passes. Set the error message. #### CouplingError Base class for errors raised by the coupling graph object. Set the error message. #### LayoutError Errors raised by the layout object. Set the error message. #### CircuitTooWideForTarget Error raised if the circuit is too wide for the target. Set the error message. #### InvalidLayoutError Error raised when a user provided layout is invalid. Set the error message. ",repo/docs/api/qiskit/1.0\transpiler.mdx "--- title: passes description: API reference for qiskit.transpiler.passes in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.transpiler.passes --- # Transpiler Passes `qiskit.transpiler.passes` ## Layout Selection (Placement) | | | | ---------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | [`SetLayout`](qiskit.transpiler.passes.SetLayout ""qiskit.transpiler.passes.SetLayout"")(\*args, \*\*kwargs) | Set the `layout` property to the given layout. | | [`TrivialLayout`](qiskit.transpiler.passes.TrivialLayout ""qiskit.transpiler.passes.TrivialLayout"")(\*args, \*\*kwargs) | Choose a Layout by assigning `n` circuit qubits to device qubits `0, .., n-1`. | | [`DenseLayout`](qiskit.transpiler.passes.DenseLayout ""qiskit.transpiler.passes.DenseLayout"")(\*args, \*\*kwargs) | Choose a Layout by finding the most connected subset of qubits. | | [`SabreLayout`](qiskit.transpiler.passes.SabreLayout ""qiskit.transpiler.passes.SabreLayout"")(\*args, \*\*kwargs) | Choose a Layout via iterative bidirectional routing of the input circuit. | | [`CSPLayout`](qiskit.transpiler.passes.CSPLayout ""qiskit.transpiler.passes.CSPLayout"")(\*args, \*\*kwargs) | If possible, chooses a Layout as a CSP, using backtracking. | | [`VF2Layout`](qiskit.transpiler.passes.VF2Layout ""qiskit.transpiler.passes.VF2Layout"")(\*args, \*\*kwargs) | A pass for choosing a Layout of a circuit onto a Coupling graph, as a subgraph isomorphism problem, solved by VF2++. | | [`ApplyLayout`](qiskit.transpiler.passes.ApplyLayout ""qiskit.transpiler.passes.ApplyLayout"")(\*args, \*\*kwargs) | Transform a circuit with virtual qubits into a circuit with physical qubits. | | [`Layout2qDistance`](qiskit.transpiler.passes.Layout2qDistance ""qiskit.transpiler.passes.Layout2qDistance"")(\*args, \*\*kwargs) | Evaluate how good the layout selection was. | | [`EnlargeWithAncilla`](qiskit.transpiler.passes.EnlargeWithAncilla ""qiskit.transpiler.passes.EnlargeWithAncilla"")(\*args, \*\*kwargs) | Extend the dag with virtual qubits that are in layout but not in the circuit yet. | | [`FullAncillaAllocation`](qiskit.transpiler.passes.FullAncillaAllocation ""qiskit.transpiler.passes.FullAncillaAllocation"")(\*args, \*\*kwargs) | Allocate all idle nodes from the coupling map or target as ancilla on the layout. | | [`SabrePreLayout`](qiskit.transpiler.passes.SabrePreLayout ""qiskit.transpiler.passes.SabrePreLayout"")(\*args, \*\*kwargs) | Choose a starting layout to use for additional Sabre layout trials. | ## Routing | | | | ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | [`BasicSwap`](qiskit.transpiler.passes.BasicSwap ""qiskit.transpiler.passes.BasicSwap"")(\*args, \*\*kwargs) | Map (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates. | | [`LookaheadSwap`](qiskit.transpiler.passes.LookaheadSwap ""qiskit.transpiler.passes.LookaheadSwap"")(\*args, \*\*kwargs) | Map input circuit onto a backend topology via insertion of SWAPs. | | [`StochasticSwap`](qiskit.transpiler.passes.StochasticSwap ""qiskit.transpiler.passes.StochasticSwap"")(\*args, \*\*kwargs) | Map a DAGCircuit onto a coupling\_map adding swap gates. | | [`SabreSwap`](qiskit.transpiler.passes.SabreSwap ""qiskit.transpiler.passes.SabreSwap"")(\*args, \*\*kwargs) | Map input circuit onto a backend topology via insertion of SWAPs. | | [`Commuting2qGateRouter`](qiskit.transpiler.passes.Commuting2qGateRouter ""qiskit.transpiler.passes.Commuting2qGateRouter"")(\*args, \*\*kwargs) | A class to swap route one or more commuting gates to the coupling map. | ## Basis Change | | | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | [`BasisTranslator`](qiskit.transpiler.passes.BasisTranslator ""qiskit.transpiler.passes.BasisTranslator"")(\*args, \*\*kwargs) | Translates gates to a target basis by searching for a set of translations from a given EquivalenceLibrary. | | [`Decompose`](qiskit.transpiler.passes.Decompose ""qiskit.transpiler.passes.Decompose"")(\*args, \*\*kwargs) | Expand a gate in a circuit using its decomposition rules. | | [`TranslateParameterizedGates`](qiskit.transpiler.passes.TranslateParameterizedGates ""qiskit.transpiler.passes.TranslateParameterizedGates"")(\*args, \*\*kwargs) | Translate parameterized gates to a supported basis set. | | [`Unroll3qOrMore`](qiskit.transpiler.passes.Unroll3qOrMore ""qiskit.transpiler.passes.Unroll3qOrMore"")(\*args, \*\*kwargs) | Recursively expands 3q+ gates until the circuit only contains 2q or 1q gates. | | [`UnrollCustomDefinitions`](qiskit.transpiler.passes.UnrollCustomDefinitions ""qiskit.transpiler.passes.UnrollCustomDefinitions"")(\*args, \*\*kwargs) | Unrolls instructions with custom definitions. | ## Optimizations | | | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`Optimize1qGates`](qiskit.transpiler.passes.Optimize1qGates ""qiskit.transpiler.passes.Optimize1qGates"")(\*args, \*\*kwargs) | Optimize chains of single-qubit u1, u2, u3 gates by combining them into a single gate. | | [`Optimize1qGatesDecomposition`](qiskit.transpiler.passes.Optimize1qGatesDecomposition ""qiskit.transpiler.passes.Optimize1qGatesDecomposition"")(\*args, \*\*kwargs) | Optimize chains of single-qubit gates by combining them into a single gate. | | [`Collect1qRuns`](qiskit.transpiler.passes.Collect1qRuns ""qiskit.transpiler.passes.Collect1qRuns"")(\*args, \*\*kwargs) | Collect one-qubit subcircuits. | | [`Collect2qBlocks`](qiskit.transpiler.passes.Collect2qBlocks ""qiskit.transpiler.passes.Collect2qBlocks"")(\*args, \*\*kwargs) | Collect two-qubit subcircuits. | | [`CollectMultiQBlocks`](qiskit.transpiler.passes.CollectMultiQBlocks ""qiskit.transpiler.passes.CollectMultiQBlocks"")(\*args, \*\*kwargs) | Collect sequences of uninterrupted gates acting on groups of qubits. | | [`CollectLinearFunctions`](qiskit.transpiler.passes.CollectLinearFunctions ""qiskit.transpiler.passes.CollectLinearFunctions"")(\*args, \*\*kwargs) | Collect blocks of linear gates ([`CXGate`](qiskit.circuit.library.CXGate ""qiskit.circuit.library.CXGate"") and [`SwapGate`](qiskit.circuit.library.SwapGate ""qiskit.circuit.library.SwapGate"") gates) and replaces them by linear functions ([`LinearFunction`](qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.LinearFunction"")). | | [`CollectCliffords`](qiskit.transpiler.passes.CollectCliffords ""qiskit.transpiler.passes.CollectCliffords"")(\*args, \*\*kwargs) | Collects blocks of Clifford gates and replaces them by a [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") object. | | [`ConsolidateBlocks`](qiskit.transpiler.passes.ConsolidateBlocks ""qiskit.transpiler.passes.ConsolidateBlocks"")(\*args, \*\*kwargs) | Replace each block of consecutive gates by a single Unitary node. | | [`CXCancellation`](qiskit.transpiler.passes.CXCancellation ""qiskit.transpiler.passes.CXCancellation"")(\*args, \*\*kwargs) | Cancel back-to-back `cx` gates in dag. | | [`InverseCancellation`](qiskit.transpiler.passes.InverseCancellation ""qiskit.transpiler.passes.InverseCancellation"")(\*args, \*\*kwargs) | Cancel specific Gates which are inverses of each other when they occur back-to- back. | | [`CommutationAnalysis`](qiskit.transpiler.passes.CommutationAnalysis ""qiskit.transpiler.passes.CommutationAnalysis"")(\*args, \*\*kwargs) | Analysis pass to find commutation relations between DAG nodes. | | [`CommutativeCancellation`](qiskit.transpiler.passes.CommutativeCancellation ""qiskit.transpiler.passes.CommutativeCancellation"")(\*args, \*\*kwargs) | Cancel the redundant (self-adjoint) gates through commutation relations. | | [`CommutativeInverseCancellation`](qiskit.transpiler.passes.CommutativeInverseCancellation ""qiskit.transpiler.passes.CommutativeInverseCancellation"")(\*args, \*\*kwargs) | Cancel pairs of inverse gates exploiting commutation relations. | | [`Optimize1qGatesSimpleCommutation`](qiskit.transpiler.passes.Optimize1qGatesSimpleCommutation ""qiskit.transpiler.passes.Optimize1qGatesSimpleCommutation"")(\*args, \*\*kwargs) | Optimizes 1Q gate strings interrupted by 2Q gates by commuting the components and resynthesizing the results. | | [`RemoveDiagonalGatesBeforeMeasure`](qiskit.transpiler.passes.RemoveDiagonalGatesBeforeMeasure ""qiskit.transpiler.passes.RemoveDiagonalGatesBeforeMeasure"")(\*args, \*\*kwargs) | Remove diagonal gates (including diagonal 2Q gates) before a measurement. | | [`RemoveResetInZeroState`](qiskit.transpiler.passes.RemoveResetInZeroState ""qiskit.transpiler.passes.RemoveResetInZeroState"")(\*args, \*\*kwargs) | Remove reset gate when the qubit is in zero state. | | [`HoareOptimizer`](qiskit.transpiler.passes.HoareOptimizer ""qiskit.transpiler.passes.HoareOptimizer"")(\*args, \*\*kwargs) | This is a transpiler pass using Hoare logic circuit optimization. | | [`TemplateOptimization`](qiskit.transpiler.passes.TemplateOptimization ""qiskit.transpiler.passes.TemplateOptimization"")(\*args, \*\*kwargs) | Class for the template optimization pass. | | [`EchoRZXWeylDecomposition`](qiskit.transpiler.passes.EchoRZXWeylDecomposition ""qiskit.transpiler.passes.EchoRZXWeylDecomposition"")(\*args, \*\*kwargs) | Rewrite two-qubit gates using the Weyl decomposition. | | [`ResetAfterMeasureSimplification`](qiskit.transpiler.passes.ResetAfterMeasureSimplification ""qiskit.transpiler.passes.ResetAfterMeasureSimplification"")(\*args, \*\*kwargs) | This pass replaces reset after measure with a conditional X gate. | | [`OptimizeCliffords`](qiskit.transpiler.passes.OptimizeCliffords ""qiskit.transpiler.passes.OptimizeCliffords"")(\*args, \*\*kwargs) | Combine consecutive Cliffords over the same qubits. | | [`NormalizeRXAngle`](qiskit.transpiler.passes.NormalizeRXAngle ""qiskit.transpiler.passes.NormalizeRXAngle"")(\*args, \*\*kwargs) | Normalize theta parameter of RXGate instruction. | | [`OptimizeAnnotated`](qiskit.transpiler.passes.OptimizeAnnotated ""qiskit.transpiler.passes.OptimizeAnnotated"")(\*args, \*\*kwargs) | Optimization pass on circuits with annotated operations. | ## Calibration | | | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | [`PulseGates`](qiskit.transpiler.passes.PulseGates ""qiskit.transpiler.passes.PulseGates"")(\*args, \*\*kwargs) | Pulse gate adding pass. | | [`RZXCalibrationBuilder`](qiskit.transpiler.passes.RZXCalibrationBuilder ""qiskit.transpiler.passes.RZXCalibrationBuilder"")(\*args, \*\*kwargs) | Creates calibrations for RZXGate(theta) by stretching and compressing Gaussian square pulses in the CX gate. | | [`RZXCalibrationBuilderNoEcho`](qiskit.transpiler.passes.RZXCalibrationBuilderNoEcho ""qiskit.transpiler.passes.RZXCalibrationBuilderNoEcho"")(\*args, \*\*kwargs) | Creates calibrations for RZXGate(theta) by stretching and compressing Gaussian square pulses in the CX gate. | | [`RXCalibrationBuilder`](qiskit.transpiler.passes.RXCalibrationBuilder ""qiskit.transpiler.passes.RXCalibrationBuilder"")(\*args, \*\*kwargs) | Add single-pulse RX calibrations that are bootstrapped from the SX calibration. | ### rzx\_templates Convenience function to get the cost\_dict and templates for template matching. **Parameters** **template\_list** ([*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 instruction names. **Returns** Decomposition templates and cost values. **Return type** [*Dict*](https://docs.python.org/3/library/typing.html#typing.Dict ""(in Python v3.12)"") ## Scheduling | | | | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | [`TimeUnitConversion`](qiskit.transpiler.passes.TimeUnitConversion ""qiskit.transpiler.passes.TimeUnitConversion"")(\*args, \*\*kwargs) | Choose a time unit to be used in the following time-aware passes, and make all circuit time units consistent with that. | | [`ALAPScheduleAnalysis`](qiskit.transpiler.passes.ALAPScheduleAnalysis ""qiskit.transpiler.passes.ALAPScheduleAnalysis"")(\*args, \*\*kwargs) | ALAP Scheduling pass, which schedules the **stop** time of instructions as late as possible. | | [`ASAPScheduleAnalysis`](qiskit.transpiler.passes.ASAPScheduleAnalysis ""qiskit.transpiler.passes.ASAPScheduleAnalysis"")(\*args, \*\*kwargs) | ASAP Scheduling pass, which schedules the start time of instructions as early as possible. | | [`PadDynamicalDecoupling`](qiskit.transpiler.passes.PadDynamicalDecoupling ""qiskit.transpiler.passes.PadDynamicalDecoupling"")(\*args, \*\*kwargs) | Dynamical decoupling insertion pass. | | [`PadDelay`](qiskit.transpiler.passes.PadDelay ""qiskit.transpiler.passes.PadDelay"")(\*args, \*\*kwargs) | Padding idle time with Delay instructions. | | [`ConstrainedReschedule`](qiskit.transpiler.passes.ConstrainedReschedule ""qiskit.transpiler.passes.ConstrainedReschedule"")(\*args, \*\*kwargs) | Rescheduler pass that updates node start times to conform to the hardware alignments. | | [`ValidatePulseGates`](qiskit.transpiler.passes.ValidatePulseGates ""qiskit.transpiler.passes.ValidatePulseGates"")(\*args, \*\*kwargs) | Check custom gate length. | | [`InstructionDurationCheck`](qiskit.transpiler.passes.InstructionDurationCheck ""qiskit.transpiler.passes.InstructionDurationCheck"")(\*args, \*\*kwargs) | Duration validation pass for reschedule. | | [`SetIOLatency`](qiskit.transpiler.passes.SetIOLatency ""qiskit.transpiler.passes.SetIOLatency"")(\*args, \*\*kwargs) | Set IOLatency information to the input circuit. | | [`ALAPSchedule`](qiskit.transpiler.passes.ALAPSchedule ""qiskit.transpiler.passes.ALAPSchedule"")(\*args, \*\*kwargs) | ALAP Scheduling pass, which schedules the **stop** time of instructions as late as possible. | | [`ASAPSchedule`](qiskit.transpiler.passes.ASAPSchedule ""qiskit.transpiler.passes.ASAPSchedule"")(\*args, \*\*kwargs) | ASAP Scheduling pass, which schedules the start time of instructions as early as possible.. | | [`DynamicalDecoupling`](qiskit.transpiler.passes.DynamicalDecoupling ""qiskit.transpiler.passes.DynamicalDecoupling"")(\*args, \*\*kwargs) | Dynamical decoupling insertion pass. | | [`AlignMeasures`](qiskit.transpiler.passes.AlignMeasures ""qiskit.transpiler.passes.AlignMeasures"")(\*args, \*\*kwargs) | Measurement alignment. | ## Circuit Analysis | | | | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`Width`](qiskit.transpiler.passes.Width ""qiskit.transpiler.passes.Width"")(\*args, \*\*kwargs) | Calculate the width of a DAG circuit. | | [`Depth`](qiskit.transpiler.passes.Depth ""qiskit.transpiler.passes.Depth"")(\*args, \*\*kwargs) | Calculate the depth of a DAG circuit. | | [`Size`](qiskit.transpiler.passes.Size ""qiskit.transpiler.passes.Size"")(\*args, \*\*kwargs) | Calculate the size of a DAG circuit. | | [`CountOps`](qiskit.transpiler.passes.CountOps ""qiskit.transpiler.passes.CountOps"")(\*args, \*\*kwargs) | Count the operations in a DAG circuit. | | [`CountOpsLongestPath`](qiskit.transpiler.passes.CountOpsLongestPath ""qiskit.transpiler.passes.CountOpsLongestPath"")(\*args, \*\*kwargs) | Count the operations on the longest path in a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit""). | | [`NumTensorFactors`](qiskit.transpiler.passes.NumTensorFactors ""qiskit.transpiler.passes.NumTensorFactors"")(\*args, \*\*kwargs) | Calculate the number of tensor factors of a DAG circuit. | | [`DAGLongestPath`](qiskit.transpiler.passes.DAGLongestPath ""qiskit.transpiler.passes.DAGLongestPath"")(\*args, \*\*kwargs) | Return the longest path in a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") as a list of [`DAGOpNode`](qiskit.dagcircuit.DAGOpNode ""qiskit.dagcircuit.DAGOpNode"")s, [`DAGInNode`](qiskit.dagcircuit.DAGInNode ""qiskit.dagcircuit.DAGInNode"")s, and [`DAGOutNode`](qiskit.dagcircuit.DAGOutNode ""qiskit.dagcircuit.DAGOutNode"")s. | ## Synthesis The synthesis transpiler plugin documentation can be found in the [`qiskit.transpiler.passes.synthesis.plugin`](transpiler_synthesis_plugins#module-qiskit.transpiler.passes.synthesis.plugin ""qiskit.transpiler.passes.synthesis.plugin"") page. | | | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`UnitarySynthesis`](qiskit.transpiler.passes.UnitarySynthesis ""qiskit.transpiler.passes.UnitarySynthesis"")(\*args, \*\*kwargs) | Synthesize gates according to their basis gates. | | [`LinearFunctionsToPermutations`](qiskit.transpiler.passes.LinearFunctionsToPermutations ""qiskit.transpiler.passes.LinearFunctionsToPermutations"")(\*args, \*\*kwargs) | Promotes linear functions to permutations when possible. | | [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.HighLevelSynthesis"")(\*args, \*\*kwargs) | Synthesize higher-level objects and unroll custom definitions. | | [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.HLSConfig"")(\[use\_default\_on\_unspecified]) | The high-level-synthesis config allows to specify a list of ""methods"" used by [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.HighLevelSynthesis"") transformation pass to synthesize different types of higher-level objects. | | [`SolovayKitaev`](qiskit.transpiler.passes.SolovayKitaev ""qiskit.transpiler.passes.SolovayKitaev"")(\*args, \*\*kwargs) | Approximately decompose 1q gates to a discrete basis using the Solovay-Kitaev algorithm. | ## Post Layout (Post transpile qubit selection) | | | | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | [`VF2PostLayout`](qiskit.transpiler.passes.VF2PostLayout ""qiskit.transpiler.passes.VF2PostLayout"")(\*args, \*\*kwargs) | A pass for improving an existing Layout after transpilation of a circuit onto a Coupling graph, as a subgraph isomorphism problem, solved by VF2++. | ## Additional Passes | | | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | [`CheckMap`](qiskit.transpiler.passes.CheckMap ""qiskit.transpiler.passes.CheckMap"")(\*args, \*\*kwargs) | Check if a DAG circuit is already mapped to a coupling map. | | [`CheckGateDirection`](qiskit.transpiler.passes.CheckGateDirection ""qiskit.transpiler.passes.CheckGateDirection"")(\*args, \*\*kwargs) | Check if the two-qubit gates follow the right direction with respect to the coupling map. | | [`GateDirection`](qiskit.transpiler.passes.GateDirection ""qiskit.transpiler.passes.GateDirection"")(\*args, \*\*kwargs) | Modify asymmetric gates to match the hardware coupling direction. | | [`MergeAdjacentBarriers`](qiskit.transpiler.passes.MergeAdjacentBarriers ""qiskit.transpiler.passes.MergeAdjacentBarriers"")(\*args, \*\*kwargs) | Return a circuit with any adjacent barriers merged together. | | [`RemoveBarriers`](qiskit.transpiler.passes.RemoveBarriers ""qiskit.transpiler.passes.RemoveBarriers"")(\*args, \*\*kwargs) | Return a circuit with any barrier removed. | | [`BarrierBeforeFinalMeasurements`](qiskit.transpiler.passes.BarrierBeforeFinalMeasurements ""qiskit.transpiler.passes.BarrierBeforeFinalMeasurements"")(\*args, \*\*kwargs) | Add a barrier before final measurements. | | [`RemoveFinalMeasurements`](qiskit.transpiler.passes.RemoveFinalMeasurements ""qiskit.transpiler.passes.RemoveFinalMeasurements"")(\*args, \*\*kwargs) | Remove final measurements and barriers at the end of a circuit. | | [`DAGFixedPoint`](qiskit.transpiler.passes.DAGFixedPoint ""qiskit.transpiler.passes.DAGFixedPoint"")(\*args, \*\*kwargs) | Check if the DAG has reached a fixed point. | | [`FixedPoint`](qiskit.transpiler.passes.FixedPoint ""qiskit.transpiler.passes.FixedPoint"")(\*args, \*\*kwargs) | Check if a property reached a fixed point. | | [`MinimumPoint`](qiskit.transpiler.passes.MinimumPoint ""qiskit.transpiler.passes.MinimumPoint"")(\*args, \*\*kwargs) | Check if the DAG has reached a relative semi-stable point over previous runs | | [`ContainsInstruction`](qiskit.transpiler.passes.ContainsInstruction ""qiskit.transpiler.passes.ContainsInstruction"")(\*args, \*\*kwargs) | An analysis pass to detect if the DAG contains a specific instruction. | | [`GatesInBasis`](qiskit.transpiler.passes.GatesInBasis ""qiskit.transpiler.passes.GatesInBasis"")(\*args, \*\*kwargs) | Check if all gates in a DAG are in a given set of gates | | [`ConvertConditionsToIfOps`](qiskit.transpiler.passes.ConvertConditionsToIfOps ""qiskit.transpiler.passes.ConvertConditionsToIfOps"")(\*args, \*\*kwargs) | Convert instructions whose `condition` attribute is set to a non-`None` value into the equivalent single-statement `IfElseBlock`. | | [`UnrollForLoops`](qiskit.transpiler.passes.UnrollForLoops ""qiskit.transpiler.passes.UnrollForLoops"")(\*args, \*\*kwargs) | `UnrollForLoops` transpilation pass unrolls for-loops when possible. | | [`FilterOpNodes`](qiskit.transpiler.passes.FilterOpNodes ""qiskit.transpiler.passes.FilterOpNodes"")(\*args, \*\*kwargs) | Remove all operations that match a filter function | ",repo/docs/api/qiskit/1.0\transpiler_passes.mdx "--- title: plugin description: API reference for qiskit.transpiler.preset_passmanagers.plugin in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.transpiler.preset_passmanagers.plugin --- # Transpiler Stage Plugin Interface `qiskit.transpiler.preset_passmanagers.plugin` This module defines the plugin interface for providing custom stage implementations for the preset pass managers and the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") function. This enables external Python packages to provide [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") objects that can be used for each named stage. The plugin interfaces are built using setuptools [entry points](https://setuptools.readthedocs.io/en/latest/userguide/entry_point.html) which enable packages external to Qiskit to advertise they include a transpiler stage(s). For details on how to instead write plugins for transpiler synthesis methods, see [`qiskit.transpiler.passes.synthesis.plugin`](transpiler_synthesis_plugins#module-qiskit.transpiler.passes.synthesis.plugin ""qiskit.transpiler.passes.synthesis.plugin""). ## Plugin Stages Currently, there are 6 stages in the preset pass managers, all of which actively load external plugins via corresponding entry points. | Stage Name | Entry Point | Reserved Names | Description and expectations | | -------------- | -------------------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `init` | `qiskit.transpiler.init` | `default` | This stage runs first and is typically used for any initial logical optimization. Because most layout and routing algorithms are only designed to work with 1 and 2 qubit gates, this stage is also used to translate any gates that operate on more than 2 qubits into gates that only operate on 1 or 2 qubits. | | `layout` | `qiskit.transpiler.layout` | `trivial`, `dense`, `sabre`, `default` | The output from this stage is expected to have the `layout` property set field set with a [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") object. Additionally, the circuit is typically expected to be embedded so that it is expanded to include all qubits and the [`ApplyLayout`](qiskit.transpiler.passes.ApplyLayout ""qiskit.transpiler.passes.ApplyLayout"") pass is expected to be run to apply the layout. The embedding of the [`Layout`](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"") can be generated with [`generate_embed_passmanager()`](transpiler_preset#qiskit.transpiler.preset_passmanagers.common.generate_embed_passmanager ""qiskit.transpiler.preset_passmanagers.common.generate_embed_passmanager""). | | `routing` | `qiskit.transpiler.routing` | `basic`, `stochastic`, `lookahead`, `sabre` | The output from this stage is expected to have the circuit match the connectivity constraints of the target backend. This does not necessarily need to match the directionality of the edges in the target as a later stage typically will adjust directional gates to match that constraint (but there is no penalty for doing that in the `routing` stage). | | `translation` | `qiskit.transpiler.translation` | `translator`, `synthesis`, `unroller` | **The output of this stage is expected to have every operation be a native**instruction on the target backend. | | `optimization` | `qiskit.transpiler.optimization` | `default` | This stage is expected to perform optimization and simplification. The constraints from earlier stages still apply to the output of this stage. After the `optimization` stage is run we expect the circuit to still be executable on the target. | | `scheduling` | `qiskit.transpiler.scheduling` | `alap`, `asap`, `default` | This is the last stage run and it is expected to output a scheduled circuit such that all idle periods in the circuit are marked by explicit [`Delay`](qiskit.circuit.Delay ""qiskit.circuit.Delay"") instructions. | ## Writing Plugins To write a pass manager stage plugin there are 2 main steps. The first step is to create a subclass of the abstract plugin class [`PassManagerStagePlugin`](qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePlugin ""qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePlugin"") which is used to define how the [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") for the stage will be constructed. For example, to create a `layout` stage plugin that just runs [`VF2Layout`](qiskit.transpiler.passes.VF2Layout ""qiskit.transpiler.passes.VF2Layout"") (with increasing amount of trials, depending on the optimization level) and falls back to using [`TrivialLayout`](qiskit.transpiler.passes.TrivialLayout ""qiskit.transpiler.passes.TrivialLayout"") if `VF2Layout` is unable to find a perfect layout: ```python from qiskit.transpiler.preset_passmanagers.plugin import PassManagerStagePlugin from qiskit.transpiler.preset_passmanagers import common from qiskit.transpiler import PassManager from qiskit.transpiler.passes import VF2Layout, TrivialLayout from qiskit.transpiler.passes.layout.vf2_layout import VF2LayoutStopReason def _vf2_match_not_found(property_set): return property_set[""layout""] is None or ( property_set[""VF2Layout_stop_reason""] is not None and property_set[""VF2Layout_stop_reason""] is not VF2LayoutStopReason.SOLUTION_FOUND class VF2LayoutPlugin(PassManagerStagePlugin): def pass_manager(self, pass_manager_config, optimization_level): layout_pm = PassManager( [ VF2Layout( coupling_map=pass_manager_config.coupling_map, properties=pass_manager_config.backend_properties, max_trials=optimization_level * 10 + 1 target=pass_manager_config.target ) ] ) layout_pm.append( TrivialLayout(pass_manager_config.coupling_map), condition=_vf2_match_not_found, ) layout_pm += common.generate_embed_passmanager(pass_manager_config.coupling_map) return layout_pm ``` The second step is to expose the [`PassManagerStagePlugin`](qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePlugin ""qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePlugin"") subclass as a setuptools entry point in the package metadata. This can be done an `entry-points` table in `pyproject.toml` for the plugin package with the necessary entry points under the appropriate namespace for the stage your plugin is for. You can see the list of stages, entry points, and expectations from the stage in [Plugin Stages](#stage-table). For example, continuing from the example plugin above: ```python .. code-block:: toml ``` > \[project.entry-points.”qiskit.transpiler.layout”] “vf2” = “qiskit\_plugin\_pkg.module.plugin:VF2LayoutPlugin” There isn’t a limit to the number of plugins a single package can include as long as each plugin has a unique name. So a single package can expose multiple plugins if necessary. Refer to [Plugin Stages](#stage-table) for a list of reserved names for each stage. ## Plugin API | | | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`PassManagerStagePlugin`](qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePlugin ""qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePlugin"")() | A `PassManagerStagePlugin` is a plugin interface object for using custom stages in [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile""). | | [`PassManagerStagePluginManager`](qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePluginManager ""qiskit.transpiler.preset_passmanagers.plugin.PassManagerStagePluginManager"")() | Manager class for preset pass manager stage plugins. | ### list\_stage\_plugins Get a list of installed plugins for a stage. **Parameters** **stage\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The stage name to get the plugin names for **Returns** The list of installed plugin names for the specified stages **Return type** plugins **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If an invalid stage name is specified. ### passmanager\_stage\_plugins Return a dict with, for each stage name, the class type of the plugin. This function is useful for getting more information about a plugin: ```python from qiskit.transpiler.preset_passmanagers.plugin import passmanager_stage_plugins routing_plugins = passmanager_stage_plugins('routing') basic_plugin = routing_plugins['basic'] help(basic_plugin) ``` ```python Help on BasicSwapPassManager in module ...preset_passmanagers.builtin_plugins object: class BasicSwapPassManager(...preset_passmanagers.plugin.PassManagerStagePlugin) | Plugin class for routing stage with :class:`~.BasicSwap` | | Method resolution order: | BasicSwapPassManager | ...preset_passmanagers.plugin.PassManagerStagePlugin | abc.ABC | builtins.object ... ``` **Parameters** **stage** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The stage name to get **Returns** the key is the name of the plugin and the value is the class type for each. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If an invalid stage name is specified. ",repo/docs/api/qiskit/1.0\transpiler_plugins.mdx "--- title: preset_passmanagers description: API reference for qiskit.transpiler.preset_passmanagers in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.transpiler.preset_passmanagers --- # Preset Passmanagers `qiskit.transpiler.preset_passmanagers` This module contains functions for generating the preset pass managers for the transpiler. The preset pass managers are instances of [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager"") which are used to execute the circuit transformations as part of Qiskit’s compiler inside the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") function at the different optimization levels. The functionality here is divided into two parts, the first includes the functions used generate the entire pass manager which is used by [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") ([Preset Pass Manager Generation](#preset-pass-manager-generators)) and the second includes functions which are used to build (either entirely or in part) the stages which the preset pass managers are composed of ([Stage Generator Functions](#stage-generators)). ## Preset Pass Manager Generation ### generate\_preset\_pass\_manager Generate a preset [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") This function is used to quickly generate a preset pass manager. Preset pass managers are the default pass managers used by the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") function. This function provides a convenient and simple method to construct a standalone [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") object that mirrors what the [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") function internally builds and uses. The target constraints for the pass manager construction can be specified through a [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") instance, a [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") or [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2"") instance, or via loose constraints (`basis_gates`, `inst_map`, `coupling_map`, `backend_properties`, `instruction_durations`, `dt` or `timing_constraints`). The order of priorities for target constraints works as follows: if a `target` input is provided, it will take priority over any `backend` input or loose constraints. If a `backend` is provided together with any loose constraint from the list above, the loose constraint will take priority over the corresponding backend constraint. This behavior is independent of whether the `backend` instance is of type [`BackendV1`](qiskit.providers.BackendV1 ""qiskit.providers.BackendV1"") or [`BackendV2`](qiskit.providers.BackendV2 ""qiskit.providers.BackendV2""), as summarized in the table below. The first column in the table summarizes the potential user-provided constraints, and each cell shows whether the priority is assigned to that specific constraint input or another input (target/backend(V1)/backend(V2)). | User Provided | target | backend(V1) | backend(V2) | | -------------------------- | ------ | ---------------------- | ---------------------- | | **basis\_gates** | target | basis\_gates | basis\_gates | | **coupling\_map** | target | coupling\_map | coupling\_map | | **instruction\_durations** | target | instruction\_durations | instruction\_durations | | **inst\_map** | target | inst\_map | inst\_map | | **dt** | target | dt | dt | | **timing\_constraints** | target | timing\_constraints | timing\_constraints | | **backend\_properties** | target | backend\_properties | backend\_properties | **Parameters** * **optimization\_level** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The optimization level to generate a [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") for. This can be 0, 1, 2, or 3. 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 * **backend** ([*Backend*](qiskit.providers.Backend ""qiskit.providers.Backend"")) – An optional backend object which can be used as the source of the default values for the `basis_gates`, `inst_map`, `coupling_map`, `backend_properties`, `instruction_durations`, `timing_constraints`, and `target`. If any of those other arguments are specified in addition to `backend` they will take precedence over the value contained in the backend. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") representing a backend compilation target. The following attributes will be inferred from this argument if they are not set: `coupling_map`, `basis_gates`, `instruction_durations`, `inst_map`, `timing_constraints` and `backend_properties`. * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – List of basis gate names to unroll to (e.g: `['u1', 'u2', 'u3', 'cx']`). * **inst\_map** ([*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"")) – Mapping object that maps gate to schedules. 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. * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"") *or*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – Directed graph represented a coupling map. * **instruction\_durations** ([*InstructionDurations*](qiskit.transpiler.InstructionDurations ""qiskit.transpiler.InstructionDurations"")) – Dictionary of duration (in dt) for each instruction. * **timing\_constraints** (*TimingConstraints*) – Hardware time alignment restrictions. * **initial\_layout** ([*Layout*](qiskit.transpiler.Layout ""qiskit.transpiler.Layout"")) – Initial position of virtual qubits on physical qubits. * **layout\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The `Pass` to use for choosing initial qubit placement. Valid choices are `'trivial'`, `'dense'`, and `'sabre'`, representing [`TrivialLayout`](qiskit.transpiler.passes.TrivialLayout ""qiskit.transpiler.passes.TrivialLayout""), [`DenseLayout`](qiskit.transpiler.passes.DenseLayout ""qiskit.transpiler.passes.DenseLayout"") and [`SabreLayout`](qiskit.transpiler.passes.SabreLayout ""qiskit.transpiler.passes.SabreLayout"") respectively. This can also be the external plugin name to use for the `layout` stage of the output [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager""). 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)"")) – The pass to use for routing qubits on the architecture. Valid choices are `'basic'`, `'lookahead'`, `'stochastic'`, `'sabre'`, and `'none'` representing [`BasicSwap`](qiskit.transpiler.passes.BasicSwap ""qiskit.transpiler.passes.BasicSwap""), [`LookaheadSwap`](qiskit.transpiler.passes.LookaheadSwap ""qiskit.transpiler.passes.LookaheadSwap""), [`StochasticSwap`](qiskit.transpiler.passes.StochasticSwap ""qiskit.transpiler.passes.StochasticSwap""), [`SabreSwap`](qiskit.transpiler.passes.SabreSwap ""qiskit.transpiler.passes.SabreSwap""), and erroring if routing is required respectively. This can also be the external plugin name to use for the `routing` stage of the output [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager""). 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)"")) – The method to use for translating gates to basis gates. Valid choices `'translator'`, `'synthesis'` representing [`BasisTranslator`](qiskit.transpiler.passes.BasisTranslator ""qiskit.transpiler.passes.BasisTranslator""), and [`UnitarySynthesis`](qiskit.transpiler.passes.UnitarySynthesis ""qiskit.transpiler.passes.UnitarySynthesis"") respectively. This can also be the external plugin name to use for the `translation` stage of the output [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager""). 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)"")) – The pass to use for scheduling instructions. Valid choices are `'alap'` and `'asap'`. This can also be the external plugin name to use for the `scheduling` stage of the output [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager""). 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. * **backend\_properties** ([*BackendProperties*](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"")) – Properties returned by a backend, including information on gate errors, readout errors, qubit coherence times, etc. * **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). * **seed\_transpiler** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Sets random seed for the stochastic parts of the transpiler. * **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)"")) – 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. * **hls\_config** ([*HLSConfig*](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.HLSConfig"")) – An optional configuration class [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.HLSConfig"") that will be passed directly to [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.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)"")) – The plugin name to use for the `init` stage of the output [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager""). 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)"")) – The plugin name to use for the `optimization` stage of the output [`StagedPassManager`](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager""). 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. **Returns** The preset pass manager for the given options **Return type** [StagedPassManager](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.StagedPassManager"") **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – if an invalid value for `optimization_level` is passed in. ### level\_0\_pass\_manager Level 0 pass manager: no explicit optimization other than mapping to backend. This pass manager applies the user-given initial layout. If none is given, a trivial layout consisting of mapping the i-th virtual qubit to the i-th physical qubit is used. Any unused physical qubit is allocated as ancilla space. The pass manager then unrolls the circuit to the desired basis, and transforms the circuit to match the coupling map. **Parameters** **pass\_manager\_config** ([*PassManagerConfig*](qiskit.transpiler.PassManagerConfig ""qiskit.transpiler.passmanager_config.PassManagerConfig"")) – configuration of the pass manager. **Returns** a level 0 pass manager. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the passmanager config is invalid. **Return type** [*StagedPassManager*](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.passmanager.StagedPassManager"") ### level\_1\_pass\_manager Level 1 pass manager: light optimization by simple adjacent gate collapsing. This pass manager applies the user-given initial layout. If none is given, and a trivial layout (i-th virtual -> i-th physical) makes the circuit fit the coupling map, that is used. Otherwise, the circuit is mapped to the most densely connected coupling subgraph, and swaps are inserted to map. Any unused physical qubit is allocated as ancilla space. The pass manager then unrolls the circuit to the desired basis, and transforms the circuit to match the coupling map. Finally, optimizations in the form of adjacent gate collapse and redundant reset removal are performed. **Parameters** **pass\_manager\_config** ([*PassManagerConfig*](qiskit.transpiler.PassManagerConfig ""qiskit.transpiler.passmanager_config.PassManagerConfig"")) – configuration of the pass manager. **Returns** a level 1 pass manager. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the passmanager config is invalid. **Return type** [*StagedPassManager*](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.passmanager.StagedPassManager"") ### level\_2\_pass\_manager Level 2 pass manager: medium optimization by initial layout selection and gate cancellation using commutativity rules. This pass manager applies the user-given initial layout. If none is given, a search for a perfect layout (i.e. one that satisfies all 2-qubit interactions) is conducted. If no such layout is found, qubits are laid out on the most densely connected subset which also exhibits the best gate fidelities. The pass manager then transforms the circuit to match the coupling constraints. It is then unrolled to the basis, and any flipped cx directions are fixed. Finally, optimizations in the form of commutative gate cancellation and redundant reset removal are performed. **Parameters** **pass\_manager\_config** ([*PassManagerConfig*](qiskit.transpiler.PassManagerConfig ""qiskit.transpiler.passmanager_config.PassManagerConfig"")) – configuration of the pass manager. **Returns** a level 2 pass manager. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the passmanager config is invalid. **Return type** [*StagedPassManager*](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.passmanager.StagedPassManager"") ### level\_3\_pass\_manager Level 3 pass manager: heavy optimization by noise adaptive qubit mapping and gate cancellation using commutativity rules and unitary synthesis. This pass manager applies the user-given initial layout. If none is given, a search for a perfect layout (i.e. one that satisfies all 2-qubit interactions) is conducted. If no such layout is found, and device calibration information is available, the circuit is mapped to the qubits with best readouts and to CX gates with highest fidelity. The pass manager then transforms the circuit to match the coupling constraints. It is then unrolled to the basis, and any flipped cx directions are fixed. Finally, optimizations in the form of commutative gate cancellation, resynthesis of two-qubit unitary blocks, and redundant reset removal are performed. **Parameters** **pass\_manager\_config** ([*PassManagerConfig*](qiskit.transpiler.PassManagerConfig ""qiskit.transpiler.passmanager_config.PassManagerConfig"")) – configuration of the pass manager. **Returns** a level 3 pass manager. **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – if the passmanager config is invalid. **Return type** [*StagedPassManager*](qiskit.transpiler.StagedPassManager ""qiskit.transpiler.passmanager.StagedPassManager"") ## Stage Generator Functions ### generate\_control\_flow\_options\_check Generate a pass manager that, when run on a DAG that contains control flow, fails with an error message explaining the invalid options, and what could be used instead. **Returns** a pass manager that populates the `contains_x` properties for each of the control-flow operations, and raises an error if any of the given options do not support control flow, but a circuit with control flow is given. **Return type** [PassManager](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") ### generate\_error\_on\_control\_flow Get a pass manager that always raises an error if control flow is present in a given circuit. ### generate\_unroll\_3q Generate an unroll >3q [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") **Parameters** * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object representing the backend * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of str gate names that represent the basis gates on the backend target * **approximation\_degree** (*Optional\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – The heuristic approximation degree to use. Can be between 0 and 1. * **unitary\_synthesis\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The unitary synthesis method to use. 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)"")) – The optional dictionary plugin configuration, this is plugin specific refer to the specified plugin’s documentation for how to use. * **hls\_config** ([*HLSConfig*](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.HLSConfig"")) – An optional configuration class to use for [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.HighLevelSynthesis"") pass. Specifies how to synthesize various high-level objects. **Returns** The unroll 3q or more pass manager **Return type** [PassManager](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") ### generate\_embed\_passmanager Generate a layout embedding [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") This is used to generate a [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") object that can be used to expand and apply an initial layout to a circuit **Parameters** **coupling\_map** (*Union\[*[*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")*,* [*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The coupling map for the backend to embed the circuit to. **Returns** **The embedding passmanager that assumes the layout property** set has been set in earlier stages **Return type** [PassManager](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") ### generate\_routing\_passmanager Generate a routing [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") **Parameters** * **routing\_pass** ([*TransformationPass*](qiskit.transpiler.TransformationPass ""qiskit.transpiler.TransformationPass"")) – The pass which will perform the routing * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object representing the backend * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")) – The coupling map of the backend to route for * **vf2\_call\_limit** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The internal call limit for the vf2 post layout pass. If this is `None` or `0` the vf2 post layout will not be run. * **backend\_properties** ([*BackendProperties*](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"")) – Properties of a backend to synthesize for (e.g. gate fidelities). * **seed\_transpiler** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Sets random seed for the stochastic parts of the transpiler. * **check\_trivial** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If set to true this will condition running the [`VF2PostLayout`](qiskit.transpiler.passes.VF2PostLayout ""qiskit.transpiler.passes.VF2PostLayout"") pass after routing on whether a trivial layout was tried and was found to not be perfect. This is only needed if the constructed pass manager runs [`TrivialLayout`](qiskit.transpiler.passes.TrivialLayout ""qiskit.transpiler.passes.TrivialLayout"") as a first layout attempt and uses it if it’s a perfect layout (as is the case with preset pass manager level 1). * **use\_barrier\_before\_measurement** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If true (the default) the [`BarrierBeforeFinalMeasurements`](qiskit.transpiler.passes.BarrierBeforeFinalMeasurements ""qiskit.transpiler.passes.BarrierBeforeFinalMeasurements"") transpiler pass will be run prior to the specified pass in the `routing_pass` argument. * **vf2\_max\_trials** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The maximum number of trials to run VF2 when evaluating the vf2 post layout pass. If this is `None` or `0` the vf2 post layout will not be run. **Returns** The routing pass manager **Return type** [PassManager](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") ### generate\_pre\_op\_passmanager Generate a pre-optimization loop [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") This pass manager will check to ensure that directionality from the coupling map is respected **Parameters** * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object representing the backend * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")) – The coupling map to use * **remove\_reset\_in\_zero** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If `True` include the remove reset in zero pass in the generated PassManager **Returns** The pass manager **Return type** [PassManager](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") ### generate\_translation\_passmanager Generate a basis translation [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") **Parameters** * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – the [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object representing the backend * **basis\_gates** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – A list of str gate names that represent the basis gates on the backend target * **method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The basis translation method to use * **approximation\_degree** (*Optional\[*[*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")*]*) – The heuristic approximation degree to use. Can be between 0 and 1. * **coupling\_map** ([*CouplingMap*](qiskit.transpiler.CouplingMap ""qiskit.transpiler.CouplingMap"")) – the coupling map of the backend in case synthesis is done on a physical circuit. The directionality of the coupling\_map will be taken into account if pulse\_optimize is True/None and natural\_direction is True/None. * **unitary\_synthesis\_plugin\_config** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – The optional dictionary plugin configuration, this is plugin specific refer to the specified plugin’s documentation for how to use. * **backend\_props** ([*BackendProperties*](qiskit.providers.models.BackendProperties ""qiskit.providers.models.BackendProperties"")) – Properties of a backend to synthesize for (e.g. gate fidelities). * **unitary\_synthesis\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The unitary synthesis method to use. 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""). * **hls\_config** ([*HLSConfig*](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.HLSConfig"")) – An optional configuration class to use for [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.HighLevelSynthesis"") pass. Specifies how to synthesize various high-level objects. **Returns** The basis translation pass manager **Return type** [PassManager](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If the `method` kwarg is not a valid value ### generate\_scheduling Generate a post optimization scheduling [`PassManager`](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") **Parameters** * **instruction\_durations** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – The dictionary of instruction durations * **scheduling\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The scheduling method to use, can either be `'asap'`/`'as_soon_as_possible'` or `'alap'`/`'as_late_as_possible'` * **timing\_constraints** (*TimingConstraints*) – Hardware time alignment restrictions. * **inst\_map** ([*InstructionScheduleMap*](qiskit.pulse.InstructionScheduleMap ""qiskit.pulse.InstructionScheduleMap"")) – Mapping object that maps gate to schedule. * **target** ([*Target*](qiskit.transpiler.Target ""qiskit.transpiler.Target"")) – The [`Target`](qiskit.transpiler.Target ""qiskit.transpiler.Target"") object representing the backend **Returns** The scheduling pass manager **Return type** [PassManager](qiskit.transpiler.PassManager ""qiskit.transpiler.PassManager"") **Raises** [**TranspilerError**](transpiler#qiskit.transpiler.TranspilerError ""qiskit.transpiler.TranspilerError"") – If the `scheduling_method` kwarg is not a valid value ",repo/docs/api/qiskit/1.0\transpiler_preset.mdx "--- title: plugin description: API reference for qiskit.transpiler.passes.synthesis.plugin in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.transpiler.passes.synthesis.plugin --- # Synthesis Plugins `qiskit.transpiler.passes.synthesis.plugin` This module defines the plugin interfaces for the synthesis transpiler passes in Qiskit. These provide a hook point for external python packages to implement their own synthesis techniques and have them seamlessly exposed as opt-in options to users when they run [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile""). The plugin interfaces are built using setuptools [entry points](https://setuptools.readthedocs.io/en/latest/userguide/entry_point.html) which enable packages external to qiskit to advertise they include a synthesis plugin. See [`qiskit.transpiler.preset_passmanagers.plugin`](transpiler_plugins#module-qiskit.transpiler.preset_passmanagers.plugin ""qiskit.transpiler.preset_passmanagers.plugin"") for details on how to write plugins for transpiler stages. ## Synthesis Plugin API ### Unitary Synthesis Plugin API | | | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | [`UnitarySynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin"")() | Abstract unitary synthesis plugin class | | [`UnitarySynthesisPluginManager`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPluginManager ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPluginManager"")() | Unitary Synthesis plugin manager class | | [`unitary_synthesis_plugin_names`](qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names ""qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names"")() | Return a list of installed unitary synthesis plugin names | ### High-Level Synthesis Plugin API | | | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"")() | Abstract high-level synthesis plugin class. | | [`HighLevelSynthesisPluginManager`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPluginManager ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPluginManager"")() | Class tracking the installed high-level-synthesis plugins. | | [`high_level_synthesis_plugin_names`](qiskit.transpiler.passes.synthesis.plugin.high_level_synthesis_plugin_names ""qiskit.transpiler.passes.synthesis.plugin.high_level_synthesis_plugin_names"")(op\_name) | Return a list of plugin names installed for a given high level object name | ## Writing Plugins ### Unitary Synthesis Plugins To write a unitary synthesis plugin there are 2 main steps. The first step is to create a subclass of the abstract plugin class: [`UnitarySynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin""). The plugin class defines the interface and contract for unitary synthesis plugins. The primary method is [`run()`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin#run ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin.run"") which takes in a single positional argument, a unitary matrix as a numpy array, and is expected to return a [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") object representing the synthesized circuit from that unitary matrix. Then to inform the Qiskit transpiler about what information is necessary for the pass there are several required property methods that need to be implemented such as `supports_basis_gates` and `supports_coupling_map` depending on whether the plugin supports and/or requires that input to perform synthesis. For the full details refer to the [`UnitarySynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin"") documentation for all the required fields. An example plugin class would look something like: ```python from qiskit.transpiler.passes.synthesis import plugin from qiskit_plugin_pkg.synthesis import generate_dag_circuit_from_matrix class SpecialUnitarySynthesis(plugin.UnitarySynthesisPlugin): @property def supports_basis_gates(self): return True @property def supports_coupling_map(self): return False @property def supports_natural_direction(self): return False @property def supports_pulse_optimize(self): return False @property def supports_gate_lengths(self): return False @property def supports_gate_errors(self): return False @property def supports_gate_lengths_by_qubit(self): return False @property def supports_gate_errors_by_qubit(self): return False @property def min_qubits(self): return None @property def max_qubits(self): return None @property def supported_bases(self): return None def run(self, unitary, **options): basis_gates = options['basis_gates'] dag_circuit = generate_dag_circuit_from_matrix(unitary, basis_gates) return dag_circuit ``` If for some reason the available inputs to the [`run()`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin#run ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin.run"") method are insufficient please open an issue and we can discuss expanding the plugin interface with new opt-in inputs that can be added in a backwards compatible manner for future releases. Do note though that this plugin interface is considered stable and guaranteed to not change in a breaking manner. If changes are needed (for example to expand the available optional input options) it will be done in a way that will **not** require changes from existing plugins. All methods prefixed with `supports_` are reserved on a `UnitarySynthesisPlugin` derived class for part of the interface. You should not define any custom `supports_*` methods on a subclass that are not defined in the abstract class. The second step is to expose the [`UnitarySynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin"") as a setuptools entry point in the package metadata. This is done by simply adding an `entry-points` table in `pyproject.toml` for the plugin package with the necessary entry points under the `qiskit.unitary_synthesis` namespace. For example: ```python [project.entry-points.""qiskit.unitary_synthesis""] ""special"" = ""qiskit_plugin_pkg.module.plugin:SpecialUnitarySynthesis"" ``` There isn’t a limit to the number of plugins a single package can include as long as each plugin has a unique name. So a single package can expose multiple plugins if necessary. The name `default` is used by Qiskit itself and can’t be used in a plugin. #### Unitary Synthesis Plugin Configuration For some unitary synthesis plugins that expose multiple options and tunables the plugin interface has an option for users to provide a free form configuration dictionary. This will be passed through to the `run()` method as the `options` kwarg. If your plugin has these configuration options you should clearly document how a user should specify these configuration options and how they’re used as it’s a free form field. ### High-Level Synthesis Plugins Writing a high-level synthesis plugin is conceptually similar to writing a unitary synthesis plugin. The first step is to create a subclass of the abstract plugin class: [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin""), which defines the interface and contract for high-level synthesis plugins. The primary method is [`run()`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin#run ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin.run""). The positional argument `high_level_object` specifies the “higher-level-object” to be synthesized, which is any object of type [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation"") (including, for example, [`LinearFunction`](qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.generalized_gates.linear_function.LinearFunction"") or [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.operators.symplectic.clifford.Clifford"")). The keyword argument `target` specifies the target backend, allowing the plugin to access all target-specific information, such as the coupling map, the supported gate set, and so on. The keyword argument `coupling_map` only specifies the coupling map, and is only used when `target` is not specified. The keyword argument `qubits` specifies the list of qubits over which the higher-level-object is defined, in case the synthesis is done on the physical circuit. The value of `None` indicates that the layout has not yet been chosen and the physical qubits in the target or coupling map that this operation is operating on has not yet been determined. Additionally, plugin-specific options and tunables can be specified via `options`, which is a free form configuration dictionary. If your plugin has these configuration options you should clearly document how a user should specify these configuration options and how they’re used as it’s a free form field. The method [`run()`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin#run ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin.run"") is expected to return a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") object representing the synthesized circuit from that higher-level-object. It is also allowed to return `None` representing that the synthesis method is unable to synthesize the given higher-level-object. The actual synthesis of higher-level objects is performed by [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis"") transpiler pass. For the full details refer to the [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") documentation for all the required fields. An example plugin class would look something like: ```python from qiskit.transpiler.passes.synthesis.plugin import HighLevelSynthesisPlugin from qiskit.synthesis.clifford import synth_clifford_bm class SpecialSynthesisClifford(HighLevelSynthesisPlugin): def run(self, high_level_object, coupling_map=None, target=None, qubits=None, **options): if higher_level_object.num_qubits <= 3: return synth_clifford_bm(high_level_object) else: return None ``` The above example creates a plugin to synthesize objects of type [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") that have at most 3 qubits, using the method `synth_clifford_bm`. The second step is to expose the [`HighLevelSynthesisPlugin`](qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin ""qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin"") as a setuptools entry point in the package metadata. This is done by adding an `entry-points` table in `pyproject.toml` for the plugin package with the necessary entry points under the `qiskit.synthesis` namespace. For example: ```python [project.entry-points.""qiskit.synthesis""] ""clifford.special"" = ""qiskit_plugin_pkg.module.plugin:SpecialSynthesisClifford"" ``` The `name` consists of two parts separated by dot “.”: the name of the type of [`Operation`](qiskit.circuit.Operation ""qiskit.circuit.Operation"") to which the synthesis plugin applies (`clifford`), and the name of the plugin (`special`). There isn’t a limit to the number of plugins a single package can include as long as each plugin has a unique name. ## Using Plugins ### Unitary Synthesis Plugins To use a plugin all you need to do is install the package that includes a synthesis plugin. Then Qiskit will automatically discover the installed plugins and expose them as valid options for the appropriate [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") kwargs and pass constructors. If there are any installed plugins which can’t be loaded/imported this will be logged to Python logging. To get the installed list of installed unitary synthesis plugins you can use the [`qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names()`](qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names ""qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names"") function. ### High-level Synthesis Plugins To use a high-level synthesis plugin, you first instantiate an [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.HLSConfig"") to store the names of the plugins to use for various high-level objects. For example: ```python HLSConfig(permutation=[""acg""], clifford=[""layers""], linear_function=[""pmh""]) ``` creates a high-level synthesis configuration that uses the `acg` plugin for synthesizing [`PermutationGate`](qiskit.circuit.library.PermutationGate ""qiskit.circuit.library.PermutationGate"") objects, the `layers` plugin for synthesizing [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") objects, and the `pmh` plugin for synthesizing [`LinearFunction`](qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.LinearFunction"") objects. The keyword arguments are the [`Operation.name`](qiskit.circuit.Operation#name ""qiskit.circuit.Operation.name"") fields of the relevant objects. For example, all [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") operations have the [`name`](qiskit.circuit.Operation#name ""qiskit.circuit.Operation.name"") `clifford`, so this is used as the keyword argument. You can specify any keyword argument here that you have installed plugins to handle, including custom user objects if you have plugins installed for them. See [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.HLSConfig"") for more detail on alternate formats for configuring the plugins within each argument. For each high-level object, the list of given plugins are tried in sequence until one of them succeeds (in the example above, each list only contains a single plugin). In addition to specifying a plugin by its name, you can instead pass a `(name, options)` tuple, where the second element of the tuple is a dictionary containing options for the plugin. Once created you then pass this [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.HLSConfig"") object into the `hls_config` argument for [`transpile()`](compiler#qiskit.compiler.transpile ""qiskit.compiler.transpile"") or [`generate_preset_pass_manager()`](transpiler_preset#qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager ""qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager"") which will use the specified plugins as part of the larger compilation workflow. To get a list of installed high level synthesis plugins for any given [`Operation.name`](qiskit.circuit.Operation#name ""qiskit.circuit.Operation.name""), you can use the [`high_level_synthesis_plugin_names()`](qiskit.transpiler.passes.synthesis.plugin.high_level_synthesis_plugin_names ""qiskit.transpiler.passes.synthesis.plugin.high_level_synthesis_plugin_names"") function, passing the desired `name` as the argument: ```python high_level_synthesis_plugin_names(""clifford"") ``` will return a list of all the installed Clifford synthesis plugins. ## Available Plugins High-level synthesis plugins that are directly available in Qiskit include plugins for synthesizing [`Clifford`](qiskit.quantum_info.Clifford ""qiskit.quantum_info.Clifford"") objects, [`LinearFunction`](qiskit.circuit.library.LinearFunction ""qiskit.circuit.library.LinearFunction"") objects, and [`PermutationGate`](qiskit.circuit.library.PermutationGate ""qiskit.circuit.library.PermutationGate"") objects. Some of these plugins implicitly target all-to-all connectivity. This is not a practical limitation since [`HighLevelSynthesis`](qiskit.transpiler.passes.HighLevelSynthesis ""qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis"") typically runs before layout and routing, which will ensure that the final circuit adheres to the device connectivity by inserting additional SWAP gates. A good example is the permutation synthesis plugin `ACGSynthesisPermutation` which can synthesize any permutation with at most 2 layers of SWAP gates. On the other hand, some plugins implicitly target linear connectivity. Typically, the synthesizing circuits have larger depth and the number of gates, however no additional SWAP gates would be inserted if the following layout pass chose a consecutive line of qubits inside the topology of the device. A good example of this is the permutation synthesis plugin `KMSSynthesisPermutation` which can synthesize any permutation of `n` qubits in depth `n`. Typically, it is difficult to know in advance which of the two approaches: synthesizing circuits for all-to-all connectivity and inserting SWAP gates vs. synthesizing circuits for linear connectivity and inserting less or no SWAP gates lead a better final circuit, so it likely makes sense to try both and see which gives better results. Finally, some plugins can target a given connectivity, and hence should be run after the layout is set. In this case the synthesized circuit automatically adheres to the topology of the device. A good example of this is the permutation synthesis plugin `TokenSwapperSynthesisPermutation` which is able to synthesize arbitrary permutations with respect to arbitrary coupling maps. For more detail, please refer to description of each individual plugin. Below are the synthesis plugin classes available in Qiskit. These classes should not be used directly, but instead should be used through the plugin interface documented above. The classes are listed here to ease finding the documentation for each of the included plugins and to ease the comparison between different synthesis methods for a given object. ### Unitary Synthesis Plugins #### AQC Synthesis Plugin (in [`qiskit.transpiler.passes.synthesis.aqc_plugin`](#module-qiskit.transpiler.passes.synthesis.aqc_plugin ""qiskit.transpiler.passes.synthesis.aqc_plugin"")) | | | | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- | | [`AQCSynthesisPlugin`](qiskit.transpiler.passes.synthesis.aqc_plugin.AQCSynthesisPlugin ""qiskit.transpiler.passes.synthesis.aqc_plugin.AQCSynthesisPlugin"")() | An AQC-based Qiskit unitary synthesis plugin. | #### Unitary Synthesis Plugin (in [`qiskit.transpiler.passes.synthesis.unitary_synthesis`](#module-qiskit.transpiler.passes.synthesis.unitary_synthesis ""qiskit.transpiler.passes.synthesis.unitary_synthesis"")) | | | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- | | [`DefaultUnitarySynthesis`](qiskit.transpiler.passes.synthesis.unitary_synthesis.DefaultUnitarySynthesis ""qiskit.transpiler.passes.synthesis.unitary_synthesis.DefaultUnitarySynthesis"")() | The default unitary synthesis plugin. | #### Solovay-Kitaev Synthesis Plugin (in [`qiskit.transpiler.passes.synthesis.solovay_kitaev_synthesis`](#module-qiskit.transpiler.passes.synthesis.solovay_kitaev_synthesis ""qiskit.transpiler.passes.synthesis.solovay_kitaev_synthesis"")) | | | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | | [`SolovayKitaevSynthesis`](qiskit.transpiler.passes.synthesis.solovay_kitaev_synthesis.SolovayKitaevSynthesis ""qiskit.transpiler.passes.synthesis.solovay_kitaev_synthesis.SolovayKitaevSynthesis"")() | A Solovay-Kitaev Qiskit unitary synthesis plugin. | ### High Level Synthesis For each high-level object we give a table that lists all of its plugins available directly in Qiskit. We include the name of the plugin, the class of the plugin, the targeted connectivity map and optionally additional information. Recall the plugins should be used via the previously described [`HLSConfig`](qiskit.transpiler.passes.HLSConfig ""qiskit.transpiler.passes.HLSConfig""), for example: ```python HLSConfig(permutation=[""kms""]) ``` creates a high-level synthesis configuration that uses the `kms` plugin for synthesizing [`PermutationGate`](qiskit.circuit.library.PermutationGate ""qiskit.circuit.library.PermutationGate"") objects – i.e. those with `name = ""permutation""`. In this case, the plugin name is “kms”, the plugin class is [`KMSSynthesisPermutation`](qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisPermutation ""qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisPermutation""). This particular synthesis algorithm created a circuit adhering to the linear nearest-neighbor connectivity. #### High Level Synthesis Plugins ##### Clifford Synthesis | Plugin name | Plugin class | Targeted connectivity | Description | | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | --------------------------------------------------------------------- | | `""ag""` | [`AGSynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.AGSynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.AGSynthesisClifford"") | all-to-all | greedily optimizes CX-count | | `""bm""` | [`BMSynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.BMSynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.BMSynthesisClifford"") | all-to-all | optimal count for n=2,3; used in `""default""` for n=2,3 | | `""greedy""` | [`GreedySynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.GreedySynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.GreedySynthesisClifford"") | all-to-all | greedily optimizes CX-count; used in `""default""` for n>=4 | | `""layers""` | [`LayerSynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerSynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerSynthesisClifford"") | all-to-all | | | `""lnn""` | [`LayerLnnSynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerLnnSynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerLnnSynthesisClifford"") | linear | many CX-gates but guarantees CX-depth of at most 7\*n+2 | | `""default""` | [`DefaultSynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisClifford"") | all-to-all | usually best for optimizing CX-count (and optimal CX-count for n=2,3) | | | | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`AGSynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.AGSynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.AGSynthesisClifford"")() | Clifford synthesis plugin based on the Aaronson-Gottesman method. | | [`BMSynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.BMSynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.BMSynthesisClifford"")() | Clifford synthesis plugin based on the Bravyi-Maslov method. | | [`GreedySynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.GreedySynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.GreedySynthesisClifford"")() | Clifford synthesis plugin based on the greedy synthesis Bravyi-Hu-Maslov-Shaydulin method. | | [`LayerSynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerSynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerSynthesisClifford"")() | Clifford synthesis plugin based on the Bravyi-Maslov method to synthesize Cliffords into layers. | | [`LayerLnnSynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerLnnSynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.LayerLnnSynthesisClifford"")() | Clifford synthesis plugin based on the Bravyi-Maslov method to synthesize Cliffords into layers, with each layer synthesized adhering to LNN connectivity. | | [`DefaultSynthesisClifford`](qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisClifford ""qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisClifford"")() | The default clifford synthesis plugin. | ##### Linear Function Synthesis | Plugin name | Plugin class | Targeted connectivity | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | ----------------------------------------------------- | | `""kms""` | [`KMSSynthesisLinearFunction`](qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisLinearFunction ""qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisLinearFunction"") | linear | many CX-gates but guarantees CX-depth of at most 5\*n | | `""pmh""` | [`PMHSynthesisLinearFunction`](qiskit.transpiler.passes.synthesis.high_level_synthesis.PMHSynthesisLinearFunction ""qiskit.transpiler.passes.synthesis.high_level_synthesis.PMHSynthesisLinearFunction"") | all-to-all | greedily optimizes CX-count; used in `""default""` | | `""default""` | [`DefaultSynthesisLinearFunction`](qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisLinearFunction ""qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisLinearFunction"") | all-to-all | best for optimizing CX-count | | | | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | [`KMSSynthesisLinearFunction`](qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisLinearFunction ""qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisLinearFunction"")() | Linear function synthesis plugin based on the Kutin-Moulton-Smithline method. | | [`PMHSynthesisLinearFunction`](qiskit.transpiler.passes.synthesis.high_level_synthesis.PMHSynthesisLinearFunction ""qiskit.transpiler.passes.synthesis.high_level_synthesis.PMHSynthesisLinearFunction"")() | Linear function synthesis plugin based on the Patel-Markov-Hayes method. | | [`DefaultSynthesisLinearFunction`](qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisLinearFunction ""qiskit.transpiler.passes.synthesis.high_level_synthesis.DefaultSynthesisLinearFunction"")() | The default linear function synthesis plugin. | ##### Permutation Synthesis | Plugin name | Plugin class | Targeted connectivity | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | -------------------------------------------------------- | | `""basic""` | [`BasicSynthesisPermutation`](qiskit.transpiler.passes.synthesis.high_level_synthesis.BasicSynthesisPermutation ""qiskit.transpiler.passes.synthesis.high_level_synthesis.BasicSynthesisPermutation"") | all-to-all | optimal SWAP-count; used in `""default""` | | `""acg""` | [`ACGSynthesisPermutation`](qiskit.transpiler.passes.synthesis.high_level_synthesis.ACGSynthesisPermutation ""qiskit.transpiler.passes.synthesis.high_level_synthesis.ACGSynthesisPermutation"") | all-to-all | guarantees SWAP-depth of at most 2 | | `""kms""` | [`KMSSynthesisPermutation`](qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisPermutation ""qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisPermutation"") | linear | many SWAP-gates, but guarantees SWAP-depth of at most n | | `""token_swapper""` | [`TokenSwapperSynthesisPermutation`](qiskit.transpiler.passes.synthesis.high_level_synthesis.TokenSwapperSynthesisPermutation ""qiskit.transpiler.passes.synthesis.high_level_synthesis.TokenSwapperSynthesisPermutation"") | any | greedily optimizes SWAP-count for arbitrary connectivity | | `""default""` | [`BasicSynthesisPermutation`](qiskit.transpiler.passes.synthesis.high_level_synthesis.BasicSynthesisPermutation ""qiskit.transpiler.passes.synthesis.high_level_synthesis.BasicSynthesisPermutation"") | all-to-all | best for optimizing SWAP-count | | | | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | [`BasicSynthesisPermutation`](qiskit.transpiler.passes.synthesis.high_level_synthesis.BasicSynthesisPermutation ""qiskit.transpiler.passes.synthesis.high_level_synthesis.BasicSynthesisPermutation"")() | The permutation synthesis plugin based on sorting. | | [`ACGSynthesisPermutation`](qiskit.transpiler.passes.synthesis.high_level_synthesis.ACGSynthesisPermutation ""qiskit.transpiler.passes.synthesis.high_level_synthesis.ACGSynthesisPermutation"")() | The permutation synthesis plugin based on the Alon, Chung, Graham method. | | [`KMSSynthesisPermutation`](qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisPermutation ""qiskit.transpiler.passes.synthesis.high_level_synthesis.KMSSynthesisPermutation"")() | The permutation synthesis plugin based on the Kutin, Moulton, Smithline method. | | [`TokenSwapperSynthesisPermutation`](qiskit.transpiler.passes.synthesis.high_level_synthesis.TokenSwapperSynthesisPermutation ""qiskit.transpiler.passes.synthesis.high_level_synthesis.TokenSwapperSynthesisPermutation"")() | The permutation synthesis plugin based on the token swapper algorithm. | ",repo/docs/api/qiskit/1.0\transpiler_synthesis_plugins.mdx "--- title: utils description: API reference for qiskit.utils in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.utils --- # Utilities `qiskit.utils` ## Deprecations ### add\_deprecation\_to\_docstring Dynamically insert the deprecation message into `func`’s docstring. **Parameters** * **func** (*Callable*) – The function to modify. * **msg** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The full deprecation message. * **since** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The version the deprecation started at. * **pending** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Is the deprecation still pending? ### deprecate\_arg Decorator to indicate an argument has been deprecated in some way. This decorator may be used multiple times on the same function, once per deprecated argument. It should be placed beneath other decorators like `@staticmethod` and property decorators. **Parameters** * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The name of the deprecated argument. * **since** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The version the deprecation started at. If the deprecation is pending, set the version to when that started; but later, when switching from pending to deprecated, update since to the new version. * **deprecation\_description** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – What is being deprecated? E.g. “Setting my\_func()’s my\_arg argument to None.” If not set, will default to “\{func\_name}’s argument \{name}”. * **additional\_msg** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Put here any additional information, such as what to use instead (if new\_alias is not set). For example, “Instead, use the argument new\_arg, which is similar but does not impact the circuit’s setup.” * **pending** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Set to True if the deprecation is still pending. * **package\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The PyPI package name, e.g. “qiskit-nature”. * **new\_alias** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – If the arg has simply been renamed, set this to the new name. The decorator will dynamically update the kwargs so that when the user sets the old arg, it will be passed in as the new\_alias arg. * **predicate** (*Callable\[\[Any],* [*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*] | None*) – Only log the runtime warning if the predicate returns True. This is useful to deprecate certain values or types for an argument, e.g. lambda my\_arg: isinstance(my\_arg, dict). Regardless of if a predicate is set, the runtime warning will only log when the user specifies the argument. * **removal\_timeline** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – How soon can this deprecation be removed? Expects a value like “no sooner than 6 months after the latest release” or “in release 9.99”. **Returns** The decorated callable. **Return type** Callable ### deprecate\_arguments , *, since=None)""> Deprecated. Instead, use @deprecate\_arg. **Parameters** * **kwarg\_map** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*,* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None]*) – A dictionary of the old argument name to the new name. * **category** ([*Type*](circuit_classical#qiskit.circuit.classical.types.Type ""qiskit.circuit.classical.types.Type"")*\[*[*Warning*](https://docs.python.org/3/library/exceptions.html#Warning ""(in Python v3.12)"")*]*) – Usually either DeprecationWarning or PendingDeprecationWarning. * **since** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The version the deprecation started at. Only Optional for backwards compatibility - this should always be set. If the deprecation is pending, set the version to when that started; but later, when switching from pending to deprecated, update since to the new version. **Returns** The decorated callable. **Return type** Callable ### deprecate\_func Decorator to indicate a function has been deprecated. It should be placed beneath other decorators like @staticmethod and property decorators. When deprecating a class, set this decorator on its \_\_init\_\_ function. **Parameters** * **since** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The version the deprecation started at. If the deprecation is pending, set the version to when that started; but later, when switching from pending to deprecated, update `since` to the new version. * **additional\_msg** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – Put here any additional information, such as what to use instead. For example, “Instead, use the function `new_func` from the module `.`, which is similar but uses GPU acceleration.” * **pending** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – Set to `True` if the deprecation is still pending. * **package\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – The PyPI package name, e.g. “qiskit-nature”. * **removal\_timeline** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – How soon can this deprecation be removed? Expects a value like “no sooner than 6 months after the latest release” or “in release 9.99”. * **is\_property** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")) – If the deprecated function is a @property, set this to True so that the generated message correctly describes it as such. (This isn’t necessary for property setters, as their docstring is ignored by Python.) **Returns** The decorated callable. **Return type** Callable ### deprecate\_function , *, since=None)""> Deprecated. Instead, use @deprecate\_func. **Parameters** * **msg** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Warning message to emit. * **stacklevel** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The warning stacklevel to use, defaults to 2. * **category** ([*Type*](circuit_classical#qiskit.circuit.classical.types.Type ""qiskit.circuit.classical.types.Type"")*\[*[*Warning*](https://docs.python.org/3/library/exceptions.html#Warning ""(in Python v3.12)"")*]*) – Usually either DeprecationWarning or PendingDeprecationWarning. * **since** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *| None*) – The version the deprecation started at. Only Optional for backwards compatibility - this should always be set. If the deprecation is pending, set the version to when that started; but later, when switching from pending to deprecated, update since to the new version. **Returns** The decorated, deprecated callable. **Return type** Callable ## SI unit conversion ### apply\_prefix Given a SI unit prefix and value, apply the prefix to convert to standard SI unit. **Parameters** * **value** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") *|*[*ParameterExpression*](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"")) – The number to apply prefix to. * **unit** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – String prefix. **Returns** Converted value. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") | [ParameterExpression](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") This may induce tiny value error due to internal representation of float object. See [https://docs.python.org/3/tutorial/floatingpoint.html](https://docs.python.org/3/tutorial/floatingpoint.html) for details. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the `units` aren’t recognized. **Return type** [float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"") | [ParameterExpression](qiskit.circuit.ParameterExpression ""qiskit.circuit.ParameterExpression"") ### detach\_prefix Given a SI unit value, find the most suitable prefix to scale the value. For example, the `value = 1.3e8` will be converted into a tuple of `(130.0, ""M"")`, which represents a scaled value and auxiliary unit that may be used to display the value. In above example, that value might be displayed as `130 MHz` (unit is arbitrary here). **Example** ```python >>> value, prefix = detach_prefix(1e4) >>> print(f""{value} {prefix}Hz"") 10 kHz ``` **Parameters** * **value** ([*float*](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)"")) – The number to find prefix. * **decimal** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"") *| None*) – Optional. An arbitrary integer number to represent a precision of the value. If specified, it tries to round the mantissa and adjust the prefix to rounded value. For example, 999\_999.91 will become 999.9999 k with `decimal=4`, while 1.0 M with `decimal=3` or less. **Returns** A tuple of scaled value and prefix. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)""), [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")] This may induce tiny value error due to internal representation of float object. See [https://docs.python.org/3/tutorial/floatingpoint.html](https://docs.python.org/3/tutorial/floatingpoint.html) for details. **Raises** * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the `value` is out of range. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – If the `value` is not real number. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[float](https://docs.python.org/3/library/functions.html#float ""(in Python v3.12)""), [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")] ## Class tools ### wrap\_method Wrap the functionality the instance- or class method `cls.name` with additional behaviour `before` and `after`. This mutates `cls`, replacing the attribute `name` with the new functionality. This is useful when creating class decorators. The method is allowed to be defined on any parent class instead. If either `before` or `after` are given, they should be callables with a compatible signature to the method referred to. They will be called immediately before or after the method as appropriate, and any return value will be ignored. **Parameters** * **cls** ([*Type*](https://docs.python.org/3/library/typing.html#typing.Type ""(in Python v3.12)"")) – the class to modify. * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – the name of the method on the class to wrap. * **before** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"") *| None*) – a callable that should be called before the method that is being wrapped. * **after** ([*Callable*](https://docs.python.org/3/library/typing.html#typing.Callable ""(in Python v3.12)"") *| None*) – a callable that should be called after the method that is being wrapped. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – if the named method is not defined on the class or any parent class. ## Multiprocessing ### local\_hardware\_info Basic hardware information about the local machine. Gives actual number of CPU’s in the machine, even when hyperthreading is turned on. CPU count defaults to 1 when true count can’t be determined. **Returns** The hardware information. **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"") ### is\_main\_process Checks whether the current process is the main one A helper function for calling a custom function with python [`ProcessPoolExecutor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor ""(in Python v3.12)""). Tasks can be executed in parallel using this function. ### parallel\_map Parallel execution of a mapping of values to the function task. This is functionally equivalent to: ```python result = [task(value, *task_args, **task_kwargs) for value in values] ``` On Windows this function defaults to a serial implementation to avoid the overhead from spawning processes in Windows. **Parameters** * **task** (*func*) – Function that is to be called for each value in `values`. * **values** (*array\_like*) – List or array of values for which the `task` function is to be evaluated. * **task\_args** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")) – Optional additional arguments to the `task` function. * **task\_kwargs** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")) – Optional additional keyword argument to the `task` function. * **num\_processes** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – Number of processes to spawn. **Returns** **The result list contains the value of** **`task(value, *task_args, **task_kwargs)` for** each value in `values`. **Return type** result **Raises** [**QiskitError**](exceptions#qiskit.exceptions.QiskitError ""qiskit.exceptions.QiskitError"") – If user interrupts via keyboard. **Examples** ```python import time from qiskit.utils import parallel_map def func(_): time.sleep(0.1) return 0 parallel_map(func, list(range(10))); ``` ## Optional Dependency Checkers Qiskit has several features that are enabled only if certain *optional* dependencies are satisfied. This module, [`qiskit.utils.optionals`](#module-qiskit.utils.optionals ""qiskit.utils.optionals""), has a collection of objects that can be used to test if certain functionality is available, and optionally raise [`MissingOptionalLibraryError`](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") if the functionality is not available. ### Available Testers #### Qiskit Components | | | | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **qiskit.utils.optionals.HAS\_AER** | Qiskit Aer \<[https://qiskit.github.io/qiskit-aer/](https://qiskit.github.io/qiskit-aer/)> provides high-performance simulators for the quantum circuits constructed within Qiskit. | | **qiskit.utils.optionals.HAS\_IBMQ** | The `Qiskit IBMQ Provider` is used for accessing IBM Quantum hardware in the IBM cloud. | | **qiskit.utils.optionals.HAS\_IGNIS** | `Qiskit Ignis` provides tools for quantum hardware verification, noise characterization, and error correction. | | **qiskit.utils.optionals.HAS\_TOQM** | [Qiskit TOQM](https://github.com/qiskit-toqm/qiskit-toqm) provides transpiler passes for the [Time-optimal Qubit mapping algorithm](https://doi.org/10.1145/3445814.3446706). | #### External Python Libraries | | | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **qiskit.utils.optionals.HAS\_CONSTRAINT** | [python-constraint](https://github.com/python-constraint/python-constraint) is a constraint satisfaction problem solver, used in the [`CSPLayout`](qiskit.transpiler.passes.CSPLayout ""qiskit.transpiler.passes.CSPLayout"") transpiler pass. | | **qiskit.utils.optionals.HAS\_CPLEX** | The [IBM CPLEX Optimizer](https://www.ibm.com/analytics/cplex-optimizer) is a high-performance mathematical programming solver for linear, mixed-integer and quadratic programming. This is no longer by Qiskit, but it weas historically and the optional remains for backwards compatibility. | | **qiskit.utils.optionals.HAS\_CVXPY** | [CVXPY](https://www.cvxpy.org/) is a Python package for solving convex optimization problems. It is required for calculating diamond norms with [`quantum_info.diamond_norm()`](quantum_info#qiskit.quantum_info.diamond_norm ""qiskit.quantum_info.diamond_norm""). | | **qiskit.utils.optionals.HAS\_DOCPLEX** | [IBM Decision Optimization CPLEX Modelling](http://ibmdecisionoptimization.github.io/docplex-doc/) is a library for prescriptive analysis. Like CPLEX, this is no longer by Qiskit, but it weas historically and the optional remains for backwards compatibility. | | **qiskit.utils.optionals.HAS\_FIXTURES** | The test suite has additional features that are available if the optional [fixtures](https://launchpad.net/python-fixtures) module is installed. This generally also needs [`HAS_TESTTOOLS`](#qiskit.utils.optionals.HAS_TESTTOOLS ""qiskit.utils.optionals.HAS_TESTTOOLS"") as well. This is generally only needed for Qiskit developers. | | **qiskit.utils.optionals.HAS\_IPYTHON** | If [the IPython kernel](https://ipython.org/) is available, certain additional visualisations and line magics are made available. | | **qiskit.utils.optionals.HAS\_IPYWIDGETS** | Monitoring widgets for jobs running on external backends can be provided if [ipywidgets](https://ipywidgets.readthedocs.io/en/latest/) is available. | | **qiskit.utils.optionals.HAS\_JAX** | Some methods of gradient calculation within `opflow.gradients` require [JAX](https://github.com/google/jax) for autodifferentiation. | | **qiskit.utils.optionals.HAS\_JUPYTER** | Some of the tests require a complete [Jupyter](https://jupyter.org/) installation to test interactivity features. | | **qiskit.utils.optionals.HAS\_MATPLOTLIB** | Qiskit provides several visualisation tools in the [`visualization`](visualization#module-qiskit.visualization ""qiskit.visualization"") module. Almost all of these are built using [Matplotlib](https://matplotlib.org/), which must be installed in order to use them. | | **qiskit.utils.optionals.HAS\_NETWORKX** | No longer used by Qiskit. Internally, Qiskit now uses the high-performance [rustworkx](https://github.com/Qiskit/rustworkx) library as a core dependency, and during the change-over period, it was sometimes convenient to convert things into the Python-only [NetworkX](https://networkx.org/) format. Some tests of application modules, such as [Qiskit Nature](https://qiskit-community.github.io/qiskit-nature/) still use NetworkX. | | **qiskit.utils.optionals.HAS\_NLOPT** | [NLopt](https://nlopt.readthedocs.io/en/latest/) is a nonlinear optimization library, used by the global optimizers in the `algorithms.optimizers` module. | | **qiskit.utils.optionals.HAS\_PIL** | PIL is a Python image-manipulation library. Qiskit actually uses the [pillow](https://pillow.readthedocs.io/en/stable/) fork of PIL if it is available when generating certain visualizations, for example of both [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") and [`DAGCircuit`](qiskit.dagcircuit.DAGCircuit ""qiskit.dagcircuit.DAGCircuit"") in certain modes. | | **qiskit.utils.optionals.HAS\_PYDOT** | For some graph visualisations, Qiskit uses [pydot](https://github.com/pydot/pydot) as an interface to GraphViz (see [`HAS_GRAPHVIZ`](#qiskit.utils.optionals.HAS_GRAPHVIZ ""qiskit.utils.optionals.HAS_GRAPHVIZ"")). | | **qiskit.utils.optionals.HAS\_PYGMENTS** | Pygments is a code highlighter and formatter used by many environments that involve rich display of code blocks, including Sphinx and Jupyter. Qiskit uses this when producing rich output for these environments. | | **qiskit.utils.optionals.HAS\_PYLATEX** | Various LaTeX-based visualizations, especially the circuit drawers, need access to the [pylatexenc](https://github.com/phfaist/pylatexenc) project to work correctly. | | **qiskit.utils.optionals.HAS\_QASM3\_IMPORT** | The functions [`qasm3.load()`](qasm3#qiskit.qasm3.load ""qiskit.qasm3.load"") and [`qasm3.loads()`](qasm3#qiskit.qasm3.loads ""qiskit.qasm3.loads"") for importing OpenQASM 3 programs into [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit"") instances use [an external importer package](https://qiskit.github.io/qiskit-qasm3-import). | | **qiskit.utils.optionals.HAS\_SEABORN** | Qiskit provides several visualisation tools in the [`visualization`](visualization#module-qiskit.visualization ""qiskit.visualization"") module. Some of these are built using [Seaborn](https://seaborn.pydata.org/), which must be installed in order to use them. | | **qiskit.utils.optionals.HAS\_SKLEARN** | Some of the gradient functions in `opflow.gradients` use regularisation methods from [Scikit Learn](https://scikit-learn.org/stable/). | | **qiskit.utils.optionals.HAS\_SKQUANT** | Some of the optimisers in `algorithms.optimizers` are based on those found in [Scikit Quant](https://github.com/scikit-quant/scikit-quant), which must be installed to use them. | | **qiskit.utils.optionals.HAS\_SQSNOBFIT** | [SQSnobFit](https://pypi.org/project/SQSnobFit/) is a library for the “stable noisy optimization by branch and fit” algorithm. It is used by the `SNOBFIT` optimizer. | | **qiskit.utils.optionals.HAS\_SYMENGINE** | [Symengine](https://github.com/symengine/symengine) is a fast C++ backend for the symbolic-manipulation library [Sympy](https://www.sympy.org/en/index.html). Qiskit uses special methods from Symengine to accelerate its handling of [`Parameter`](qiskit.circuit.Parameter ""qiskit.circuit.Parameter"")s if available. | | **qiskit.utils.optionals.HAS\_TESTTOOLS** | Qiskit’s test suite has more advanced functionality available if the optional [testtools](https://pypi.org/project/testtools/) library is installed. This is generally only needed for Qiskit developers. | | **qiskit.utils.optionals.HAS\_TWEEDLEDUM** | [Tweedledum](https://github.com/boschmitt/tweedledum) is an extension library for synthesis and optimization of circuits that may involve classical oracles. Qiskit’s [`PhaseOracle`](qiskit.circuit.library.PhaseOracle ""qiskit.circuit.library.PhaseOracle"") uses this, which is used in turn by amplification algorithms via the `AmplificationProblem`. | | **qiskit.utils.optionals.HAS\_Z3** | [Z3](https://github.com/Z3Prover/z3) is a theorem prover, used in the `CrosstalkAdaptiveSchedule` and [`HoareOptimizer`](qiskit.transpiler.passes.HoareOptimizer ""qiskit.transpiler.passes.HoareOptimizer"") transpiler passes. | #### External Command-Line Tools | | | | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **qiskit.utils.optionals.HAS\_GRAPHVIZ** | For some graph visualisations, Qiskit uses the [GraphViz](https://graphviz.org/) visualisation tool via its `pydot` interface (see [`HAS_PYDOT`](#qiskit.utils.optionals.HAS_PYDOT ""qiskit.utils.optionals.HAS_PYDOT"")). | | **qiskit.utils.optionals.HAS\_PDFLATEX** | Visualisation tools that use LaTeX in their output, such as the circuit drawers, require `pdflatex` to be available. You will generally need to ensure that you have a working LaTeX installation available, and the `qcircuit.tex` package. | | **qiskit.utils.optionals.HAS\_PDFTOCAIRO** | Visualisation tools that convert LaTeX-generated files into rasterised images use the `pdftocairo` tool. This is part of the [Poppler suite of PDF tools](https://poppler.freedesktop.org/). | ### Lazy Checker Classes Each of the lazy checkers is an instance of [`LazyDependencyManager`](#qiskit.utils.LazyDependencyManager ""qiskit.utils.LazyDependencyManager"") in one of its two subclasses: [`LazyImportTester`](#qiskit.utils.LazyImportTester ""qiskit.utils.LazyImportTester"") and [`LazySubprocessTester`](#qiskit.utils.LazySubprocessTester ""qiskit.utils.LazySubprocessTester""). These should be imported from [`utils`](#module-qiskit.utils ""qiskit.utils"") directly if required, such as: ```python from qiskit.utils import LazyImportTester ``` #### LazyDependencyManager A mananger for some optional features that are expensive to import, or to verify the existence of. These objects can be used as Booleans, such as `if x`, and will evaluate `True` if the dependency they test for is available, and `False` if not. The presence of the dependency will only be tested when the Boolean is evaluated, so it can be used as a runtime test in functions and methods without requiring an import-time test. These objects also encapsulate the error handling if their dependency is not present, so you can do things such as: ```python from qiskit.utils import LazyImportManager HAS_MATPLOTLIB = LazyImportManager(""matplotlib"") @HAS_MATPLOTLIB.require_in_call def my_visualisation(): ... def my_other_visualisation(): # ... some setup ... HAS_MATPLOTLIB.require_now(""my_other_visualisation"") ... def my_third_visualisation(): if HAS_MATPLOTLIB: from matplotlib import pyplot else: ... ``` In all of these cases, `matplotlib` is not imported until the functions are entered. In the case of the decorator, `matplotlib` is tested for import when the function is called for the first time. In the second and third cases, the loader attempts to import `matplotlib` when the [`require_now()`](#qiskit.utils.LazyDependencyManager.require_now ""qiskit.utils.LazyDependencyManager.require_now"") method is called, or when the Boolean context is evaluated. For the `require` methods, an error is raised if the library is not available. This is the base class, which provides the Boolean context checking and error management. The concrete classes [`LazyImportTester`](#qiskit.utils.LazyImportTester ""qiskit.utils.LazyImportTester"") and [`LazySubprocessTester`](#qiskit.utils.LazySubprocessTester ""qiskit.utils.LazySubprocessTester"") provide convenient entry points for testing that certain symbols are importable from modules, or certain command-line tools are available, respectively. **Parameters** * **name** – the name of this optional dependency. * **callback** – a callback that is called immediately after the availability of the library is tested with the result. This will only be called once. * **install** – how to install this optional dependency. Passed to [`MissingOptionalLibraryError`](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") as the `pip_install` parameter. * **msg** – an extra message to include in the error raised if this is required. ##### \_is\_available Subclasses of [`LazyDependencyManager`](#qiskit.utils.LazyDependencyManager ""qiskit.utils.LazyDependencyManager"") should override this method to implement the actual test of availability. This method should return a Boolean, where `True` indicates that the dependency was available. This method will only ever be called once. **Return type** [bool](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"") ##### disable\_locally Create a context, during which the value of the dependency manager will be `False`. This means that within the context, any calls to this object will behave as if the dependency is not available, including raising errors. It is valid to call this method whether or not the dependency has already been evaluated. This is most useful in tests. ##### require\_in\_call Create a decorator for callables that requires that the dependency is available when the decorated function or method is called. **Parameters** **feature\_or\_callable** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or Callable*) – the name of the feature that requires these dependencies. If this function is called directly as a decorator (for example `@HAS_X.require_in_call` as opposed to `@HAS_X.require_in_call(""my feature"")`), then the feature name will be taken to be the function name, or class and method name as appropriate. **Returns** a decorator that will make its argument require this dependency before it is called. **Return type** Callable ##### require\_in\_instance A class decorator that requires the dependency is available when the class is initialised. This decorator can be used even if the class does not define an `__init__` method. **Parameters** **feature\_or\_class** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *or*[*Type*](circuit_classical#qiskit.circuit.classical.types.Type ""qiskit.circuit.classical.types.Type"")) – the name of the feature that requires these dependencies. If this function is called directly as a decorator (for example `@HAS_X.require_in_instance` as opposed to `@HAS_X.require_in_instance(""my feature"")`), then the feature name will be taken as the name of the class. **Returns** a class decorator that ensures that the wrapped feature is present if the class is initialised. **Return type** Callable ##### require\_now Eagerly attempt to import the dependencies in this object, and raise an exception if they cannot be imported. **Parameters** **feature** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – the name of the feature that is requiring these dependencies. **Raises** [**MissingOptionalLibraryError**](exceptions#qiskit.exceptions.MissingOptionalLibraryError ""qiskit.exceptions.MissingOptionalLibraryError"") – if the dependencies cannot be imported. #### LazyImportTester A lazy dependency tester for importable Python modules. Any required objects will only be imported at the point that this object is tested for its Boolean value. **Parameters** **name\_map\_or\_modules** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*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)"")*,* [*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)"")*]] |* [*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)"")*]*) – if a name map, then a dictionary where the keys are modules or packages, and the values are iterables of names to try and import from that module. It should be valid to write `from import , , ...`. If simply a string or iterable of strings, then it should be valid to write `import ` for each of them. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – if no modules are given. #### LazySubprocessTester A lazy checker that a command-line tool is available. The command will only be run once, at the point that this object is checked for its Boolean value. **Parameters** **command** ([*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)"")*\[*[*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*]*) – the strings that make up the command to be run. For example, `[""pdflatex"", ""-version""]`. **Raises** [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError ""(in Python v3.12)"") – if an empty command is given. ",repo/docs/api/qiskit/1.0\utils.mdx "--- title: visualization description: API reference for qiskit.visualization in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit.visualization --- # Visualizations `qiskit.visualization` The visualization module contain functions that visualizes measurement outcome counts, quantum states, circuits, pulses, devices and more. To use visualization functions, you are required to install visualization optionals to your development environment: ```python pip install 'qiskit[visualization]' ``` ## Common Keyword Arguments Many of the figures created by visualization functions in this module are created by [Matplotlib](https://matplotlib.org/) and accept a subset of the following common arguments. Consult the individual documentation for exact details. * `title` (`str`): a text string to use for the plot title. * `legend` (`list`): a list of strings to use for labels of the data. * `figsize` (`tuple`): figure size in inches . * `color` (`list`): a list of strings for plotting. * `ax` ([matplotlib.axes.Axes](https://matplotlib.org/stable/api/axes_api.html)): An optional `Axes` object to be used for the visualization output. If none is specified a new [matplotlib.figure.Figure](https://matplotlib.org/stable/api/figure_api.html) will be created and used. Additionally, if specified there will be no returned `Figure` since it is redundant. * `filename` (`str`): file path to save image to. The following example demonstrates the common usage of these arguments: ```python from qiskit.visualization import plot_histogram counts1 = {'00': 499, '11': 501} counts2 = {'00': 511, '11': 489} data = [counts1, counts2] plot_histogram(data) ``` ![../\_images/visualization-1.png](/images/api/qiskit/1.0/visualization-1.png) You can specify `legend`, `title`, `figsize` and `color` by passing to the kwargs. ```python from qiskit.visualization import plot_histogram counts1 = {'00': 499, '11': 501} counts2 = {'00': 511, '11': 489} data = [counts1, counts2] legend = ['First execution', 'Second execution'] title = 'New histogram' figsize = (10,10) color=['crimson','midnightblue'] plot_histogram(data, legend=legend, title=title, figsize=figsize, color=color) ``` ![../\_images/visualization-2.png](/images/api/qiskit/1.0/visualization-2.png) You can save the figure to file either by passing the file name to `filename` kwarg or use [matplotlib.figure.Figure.savefig](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.savefig) method. ```python plot_histogram(data, filename='new_hist.png') hist = plot_histogram(data) hist.savefig('new_hist.png') ``` ## Counts Visualizations This section contains functions that visualize measurement outcome counts. | | | | --------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | | [`plot_histogram`](qiskit.visualization.plot_histogram ""qiskit.visualization.plot_histogram"")(data\[, figsize, color, ...]) | Plot a histogram of input counts data. | ### Example Usage Here is an example of using [`plot_histogram()`](qiskit.visualization.plot_histogram ""qiskit.visualization.plot_histogram"") to visualize measurement outcome counts: ```python from qiskit.visualization import plot_histogram counts = {""00"": 501, ""11"": 499} plot_histogram(counts) ``` ![../\_images/visualization-3.png](/images/api/qiskit/1.0/visualization-3.png) The data can be a dictionary with bit string as key and counts as value, or more commonly a [`Counts`](qiskit.result.Counts ""qiskit.result.Counts"") object obtained from [`get_counts()`](qiskit.result.Result#get_counts ""qiskit.result.Result.get_counts""). ## Distribution Visualizations This section contains functions that visualize sampled distributions. | | | | ------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------- | | [`plot_distribution`](qiskit.visualization.plot_distribution ""qiskit.visualization.plot_distribution"")(data\[, figsize, color, ...]) | Plot a distribution from input sampled data. | ## State Visualizations This section contains functions that visualize quantum states. | | | | ------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | [`plot_bloch_vector`](qiskit.visualization.plot_bloch_vector ""qiskit.visualization.plot_bloch_vector"")(bloch\[, title, ax, ...]) | Plot the Bloch sphere. | | [`plot_bloch_multivector`](qiskit.visualization.plot_bloch_multivector ""qiskit.visualization.plot_bloch_multivector"")(state\[, title, ...]) | Plot a Bloch sphere for each qubit. | | [`plot_state_city`](qiskit.visualization.plot_state_city ""qiskit.visualization.plot_state_city"")(state\[, title, figsize, ...]) | Plot the cityscape of quantum state. | | [`plot_state_hinton`](qiskit.visualization.plot_state_hinton ""qiskit.visualization.plot_state_hinton"")(state\[, title, figsize, ...]) | Plot a hinton diagram for the density matrix of a quantum state. | | [`plot_state_paulivec`](qiskit.visualization.plot_state_paulivec ""qiskit.visualization.plot_state_paulivec"")(state\[, title, figsize, ...]) | Plot the Pauli-vector representation of a quantum state as bar graph. | | [`plot_state_qsphere`](qiskit.visualization.plot_state_qsphere ""qiskit.visualization.plot_state_qsphere"")(state\[, figsize, ax, ...]) | Plot the qsphere representation of a quantum state. | ### Example Usage Here is an example of using [`plot_state_city()`](qiskit.visualization.plot_state_city ""qiskit.visualization.plot_state_city"") to visualize a quantum state: ```python from qiskit.visualization import plot_state_city state = [[ 0.75 , 0.433j], [-0.433j, 0.25 ]] plot_state_city(state) ``` ![../\_images/visualization-4.png](/images/api/qiskit/1.0/visualization-4.png) The state can be array-like list of lists, `numpy.array`, or more commonly [`Statevector`](qiskit.quantum_info.Statevector ""qiskit.quantum_info.Statevector"") or [`DensityMatrix`](qiskit.quantum_info.DensityMatrix ""qiskit.quantum_info.DensityMatrix"") objects obtained from a [`QuantumCircuit`](qiskit.circuit.QuantumCircuit ""qiskit.circuit.QuantumCircuit""): ```python from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a Statevector state = Statevector(qc) plot_state_city(state) ``` ![../\_images/visualization-5.png](/images/api/qiskit/1.0/visualization-5.png) ```python from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a DensityMatrix state = DensityMatrix(qc) plot_state_city(state) ``` ![../\_images/visualization-6.png](/images/api/qiskit/1.0/visualization-6.png) You can find code examples for each visualization functions on the individual function API page. ## Device Visualizations | | | | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | [`plot_gate_map`](qiskit.visualization.plot_gate_map ""qiskit.visualization.plot_gate_map"")(backend\[, figsize, ...]) | Plots the gate map of a device. | | [`plot_error_map`](qiskit.visualization.plot_error_map ""qiskit.visualization.plot_error_map"")(backend\[, figsize, ...]) | Plots the error map of a given backend. | | [`plot_circuit_layout`](qiskit.visualization.plot_circuit_layout ""qiskit.visualization.plot_circuit_layout"")(circuit, backend\[, ...]) | Plot the layout of a circuit transpiled for a given target backend. | | [`plot_coupling_map`](qiskit.visualization.plot_coupling_map ""qiskit.visualization.plot_coupling_map"")(num\_qubits, ...\[, ...]) | Plots an arbitrary coupling map of qubits (embedded in a plane). | ## Circuit Visualizations | | | | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | | [`circuit_drawer`](qiskit.visualization.circuit_drawer ""qiskit.visualization.circuit_drawer"")(circuit\[, scale, filename, ...]) | Draw the quantum circuit. | ## DAG Visualizations | | | | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | [`dag_drawer`](qiskit.visualization.dag_drawer ""qiskit.visualization.dag_drawer"")(dag\[, scale, filename, style]) | Plot the directed acyclic graph (dag) to represent operation dependencies in a quantum circuit. | ## Pass Manager Visualizations | | | | ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | [`pass_manager_drawer`](qiskit.visualization.pass_manager_drawer ""qiskit.visualization.pass_manager_drawer"")(pass\_manager\[, ...]) | Draws the pass manager. | ## Timeline Visualizations | | | | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------- | | [`timeline_drawer`](qiskit.visualization.timeline_drawer ""qiskit.visualization.timeline_drawer"")(program\[, style, ...]) | Generate visualization data for scheduled circuit programs. | ## Single Qubit State Transition Visualizations | | | | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | [`visualize_transition`](qiskit.visualization.visualize_transition ""qiskit.visualization.visualize_transition"")(circuit\[, trace, ...]) | Creates animation showing transitions between states of a single qubit by applying quantum gates. | ## Array/Matrix Visualizations | | | | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | [`array_to_latex`](qiskit.visualization.array_to_latex ""qiskit.visualization.array_to_latex"")(array\[, precision, prefix, ...]) | Latex representation of a complex numpy array (with dimension 1 or 2) | ## Exceptions ### VisualizationError For visualization specific errors. Set the error message. ",repo/docs/api/qiskit/1.0\visualization.mdx "--- title: job description: API reference for qiskit_ibm_provider.job in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_provider.job --- # Job `qiskit_ibm_provider.job` Modules representing IBM Quantum jobs. ## Classes | | | | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | [`IBMCircuitJob`](qiskit_ibm_provider.job.IBMCircuitJob ""qiskit_ibm_provider.job.IBMCircuitJob"")(backend, api\_client, job\_id\[, ...]) | Representation of a job that executes on an IBM Quantum backend. | | [`IBMCompositeJob`](qiskit_ibm_provider.job.IBMCompositeJob ""qiskit_ibm_provider.job.IBMCompositeJob"")(backend, api\_client\[, ...]) | Representation of a set of jobs that execute on an IBM Quantum backend. | | [`QueueInfo`](qiskit_ibm_provider.job.QueueInfo ""qiskit_ibm_provider.job.QueueInfo"")(\[position\_in\_queue, status, ...]) | Queue information for a job. | ## Functions | | | | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | | [`job_monitor`](qiskit_ibm_provider.job.job_monitor ""qiskit_ibm_provider.job.job_monitor"")(job\[, interval, output]) | Monitor the status of an `IBMJob` instance. | ## Exception | | | | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | [`IBMJobError`](qiskit_ibm_provider.job.IBMJobError ""qiskit_ibm_provider.job.IBMJobError"")(\*message) | Base class for errors raised by the job modules. | | [`IBMJobApiError`](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"")(\*message) | Errors that occur unexpectedly when querying the server. | | [`IBMJobFailureError`](qiskit_ibm_provider.job.IBMJobFailureError ""qiskit_ibm_provider.job.IBMJobFailureError"")(\*message) | Errors raised when a job failed. | | [`IBMJobInvalidStateError`](qiskit_ibm_provider.job.IBMJobInvalidStateError ""qiskit_ibm_provider.job.IBMJobInvalidStateError"")(\*message) | Errors raised when a job is not in a valid state for the operation. | | [`IBMJobTimeoutError`](qiskit_ibm_provider.job.IBMJobTimeoutError ""qiskit_ibm_provider.job.IBMJobTimeoutError"")(\*message) | Errors raised when a job operation times out. | ",repo/docs/api/qiskit-ibm-provider/0.9\ibm_job.mdx "--- title: jupyter description: API reference for qiskit_ibm_provider.jupyter in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_provider.jupyter --- # Jupyter Tools `qiskit_ibm_provider.jupyter` A Collection of Jupyter magic functions and tools that extend the functionality of Qiskit for the IBM Quantum devices. To use these tools locally, you’ll need to install the additional dependencies for the visualization functions: ```python pip install qiskit_ibm_provider[visualization] ``` ## Detailed information on a single backend ```python from qiskit_ibm_provider import IBMProvider import qiskit_ibm_provider.jupyter provider = IBMProvider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') ``` ```python backend ``` ```python ``` ## IBM Quantum dashboard ```python from qiskit_ibm_provider import IBMProvider import qiskit_ibm_provider.jupyter %ibm_quantum_dashboard ``` ",repo/docs/api/qiskit-ibm-provider/0.9\ibm_jupyter.mdx "--- title: qiskit_ibm_provider description: API reference for qiskit_ibm_provider in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_provider --- # IBM Quantum Provider `qiskit_ibm_provider` Modules representing the Qiskit IBM Quantum Provider. ## Logging The qiskit-ibm-provider uses the `qiskit_ibm_provider` logger. Two environment variables can be used to control the logging: > * `QISKIT_IBM_PROVIDER_LOG_LEVEL`: Specifies the log level to use, for the Qiskit IBM provider modules. If an invalid level is set, the log level defaults to `WARNING`. The valid log levels are `DEBUG`, `INFO`, `WARNING`, `ERROR`, and `CRITICAL` (case-insensitive). If the environment variable is not set, then the parent logger’s level is used, which also defaults to `WARNING`. > * `QISKIT_IBM_PROVIDER_LOG_FILE`: Specifies the name of the log file to use. If specified, messages will be logged to the file only. Otherwise messages will be logged to the standard error (usually the screen). For more advanced use, you can modify the logger itself. For example, to manually set the level to `WARNING`: ```python import logging logging.getLogger('qiskit_ibm_provider').setLevel(logging.WARNING) ``` ## Functions | | | | ----------------------------------------------------------------------------------------- | ------------------------------------------ | | [`least_busy`](qiskit_ibm_provider.least_busy ""qiskit_ibm_provider.least_busy"")(backends) | Return the least busy backend from a list. | ## Classes | | | | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | [`IBMProvider`](qiskit_ibm_provider.IBMProvider ""qiskit_ibm_provider.IBMProvider"")(\[token, url, name, instance, ...]) | Provides access to the IBM Quantum services available to an account. | | [`IBMBackend`](qiskit_ibm_provider.IBMBackend ""qiskit_ibm_provider.IBMBackend"")(configuration, provider, api\_client) | Backend class interfacing with an IBM Quantum device. | | [`IBMBackendService`](qiskit_ibm_provider.IBMBackendService ""qiskit_ibm_provider.IBMBackendService"")(provider, hgp) | Backend namespace for an IBM Quantum account. | | [`Session`](qiskit_ibm_provider.Session ""qiskit_ibm_provider.Session"")(\[max\_time]) | Class for creating a flexible Qiskit Runtime session. | ## Exceptions | | | | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------- | | [`IBMError`](qiskit_ibm_provider.IBMError ""qiskit_ibm_provider.IBMError"")(\*message) | Base class for errors raised by the provider modules. | | [`IBMProviderError`](qiskit_ibm_provider.IBMProviderError ""qiskit_ibm_provider.IBMProviderError"")(\*message) | Base class for errors raise by IBMProvider. | | [`IBMProviderValueError`](qiskit_ibm_provider.IBMProviderValueError ""qiskit_ibm_provider.IBMProviderValueError"")(\*message) | Value errors raised by IBMProvider. | | [`IBMBackendError`](qiskit_ibm_provider.IBMBackendError ""qiskit_ibm_provider.IBMBackendError"")(\*message) | Base class for errors raised by the backend modules. | | [`IBMBackendApiError`](qiskit_ibm_provider.IBMBackendApiError ""qiskit_ibm_provider.IBMBackendApiError"")(\*message) | Errors that occur unexpectedly when querying the server. | | [`IBMBackendApiProtocolError`](qiskit_ibm_provider.IBMBackendApiProtocolError ""qiskit_ibm_provider.IBMBackendApiProtocolError"")(\*message) | Errors raised when an unexpected value is received from the server. | | [`IBMBackendValueError`](qiskit_ibm_provider.IBMBackendValueError ""qiskit_ibm_provider.IBMBackendValueError"")(\*message) | Value errors raised by the backend modules. | | [`IBMProviderError`](qiskit_ibm_provider.IBMProviderError ""qiskit_ibm_provider.IBMProviderError"")(\*message) | Base class for errors raise by IBMProvider. | ",repo/docs/api/qiskit-ibm-provider/0.9\ibm_provider.mdx "--- title: transpiler description: API reference for qiskit_ibm_provider.transpiler in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_provider.transpiler --- # IBM Backend Transpiler Tools `qiskit_ibm_provider.transpiler` A collection of transpiler tools for working with IBM Quantum’s next-generation backends that support advanced “dynamic circuit” capabilities. Ie., circuits with support for classical compute and control-flow/feedback based off of measurement results. ## Transpiler Passes | | | | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | [`passes`](qiskit_ibm_provider.transpiler.passes#module-qiskit_ibm_provider.transpiler.passes ""qiskit_ibm_provider.transpiler.passes"") | Transpiler Passes (qiskit\_ibm\_provider.transpiler.passes) | ",repo/docs/api/qiskit-ibm-provider/0.9\ibm_transpiler.mdx "--- title: utils description: API reference for qiskit_ibm_provider.utils in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_provider.utils --- # Utilities `qiskit_ibm_provider.utils` Utility functions related to the IBM Quantum Provider. ## Conversion | | | | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | [`seconds_to_duration`](qiskit_ibm_provider.utils.seconds_to_duration ""qiskit_ibm_provider.utils.seconds_to_duration"")(seconds) | Converts seconds in a datetime delta to a duration. | | [`utc_to_local`](qiskit_ibm_provider.utils.utc_to_local ""qiskit_ibm_provider.utils.utc_to_local"")(utc\_dt) | Convert a UTC `datetime` object or string to a local timezone `datetime`. | ## Misc Functions | | | | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | [`to_python_identifier`](qiskit_ibm_provider.utils.to_python_identifier ""qiskit_ibm_provider.utils.to_python_identifier"")(name) | Convert a name to a valid Python identifier. | | [`validate_job_tags`](qiskit_ibm_provider.utils.validate_job_tags ""qiskit_ibm_provider.utils.validate_job_tags"")(job\_tags, exception) | Validates input job tags. | ## Publisher/subscriber model Message broker for the Publisher / Subscriber mechanism ### Publisher Represents a “publisher”. Every component (class) can become a [`Publisher`](#qiskit_ibm_provider.utils.pubsub.Publisher ""qiskit_ibm_provider.utils.pubsub.Publisher"") and send events by inheriting this class. Functions can call this class like: ```python Publisher().publish(""event"", args, ... ) ``` #### publish Triggers an event, and associates some data to it, so if there are any subscribers, their callback will be called synchronously. **Return type** `None` ### Subscriber Represents a “subscriber”. Every component (class) can become a [`Subscriber`](#qiskit_ibm_provider.utils.pubsub.Subscriber ""qiskit_ibm_provider.utils.pubsub.Subscriber"") and subscribe to events, that will call callback functions when they are emitted. #### clear Unsubscribe everything **Return type** `None` #### subscribe Subscribes to an event, associating a callback function to that event, so when the event occurs, the callback will be called. This is a blocking call, so try to keep callbacks as lightweight as possible. **Return type** `bool` #### unsubscribe Unsubscribe a pair event-callback, so the callback will not be called anymore when the event occurs. **Return type** `bool` ",repo/docs/api/qiskit-ibm-provider/0.9\ibm_utils.mdx "--- title: visualization description: API reference for qiskit_ibm_provider.visualization in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_provider.visualization --- # Visualizations `qiskit_ibm_provider.visualization` To use these tools locally, you’ll need to install the additional dependencies for the visualization functions: ```python pip install qiskit_ibm_provider[visualization] ``` ## Interactive Visualizations | | | | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | | [`iplot_gate_map`](qiskit_ibm_provider.visualization.iplot_gate_map ""qiskit_ibm_provider.visualization.iplot_gate_map"")(backend\[, figsize, ...]) | Plots an interactive gate map of a device. | | [`iplot_error_map`](qiskit_ibm_provider.visualization.iplot_error_map ""qiskit_ibm_provider.visualization.iplot_error_map"")(backend\[, figsize, ...]) | Plot the error map of a device. | ",repo/docs/api/qiskit-ibm-provider/0.9\ibm_visualization.mdx "--- title: Qiskit IBM Provider API Docs description: API documentation for qiskit-ibm-provider --- # qiskit-ibm-provider API Reference * [IBM Quantum Provider (`qiskit_ibm_provider`)](ibm_provider) * [Job (`qiskit_ibm_provider.job`)](ibm_job) * [Visualizations (`qiskit_ibm_provider.visualization`)](ibm_visualization) * [Jupyter Tools (`qiskit_ibm_provider.jupyter`)](ibm_jupyter) * [Utilities (`qiskit_ibm_provider.utils`)](ibm_utils) * [IBM Backend Transpiler Tools (`qiskit_ibm_provider.transpiler`)](ibm_transpiler) ",repo/docs/api/qiskit-ibm-provider/0.9\index.mdx "--- title: IBMBackend description: API reference for qiskit_ibm_provider.IBMBackend in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.IBMBackend --- # IBMBackend Backend class interfacing with an IBM Quantum device. You can run experiments on a backend using the [`run()`](#qiskit_ibm_provider.IBMBackend.run ""qiskit_ibm_provider.IBMBackend.run"") method. The [`run()`](#qiskit_ibm_provider.IBMBackend.run ""qiskit_ibm_provider.IBMBackend.run"") method takes one or more [`QuantumCircuit`](/api/qiskit/qiskit.circuit.QuantumCircuit ""(in Qiskit v0.46)"") and returns an `IBMJob` instance that represents the submitted job. Each job has a unique job ID, which can later be used to retrieve the job. An example of this flow: ```python from qiskit import transpile from qiskit_ibm_provider import IBMProvider from qiskit.circuit.random import random_circuit provider = IBMProvider() backend = provider.backend.ibmq_vigo qx = random_circuit(n_qubits=5, depth=4) transpiled = transpile(qx, backend=backend) job = backend.run(transpiled) retrieved_job = provider.backend.retrieve_job(job.job_id()) ``` * Unlike `qiskit.execute()`, the [`run()`](#qiskit_ibm_provider.IBMBackend.run ""qiskit_ibm_provider.IBMBackend.run"") method does not transpile the circuits for you, so be sure to do so before submitting them. * You should not instantiate the `IBMBackend` class directly. Instead, use the methods provided by an [`IBMProvider`](qiskit_ibm_provider.IBMProvider ""qiskit_ibm_provider.IBMProvider"") instance to retrieve and handle backends. Other methods return information about the backend. For example, the [`status()`](#qiskit_ibm_provider.IBMBackend.status ""qiskit_ibm_provider.IBMBackend.status"") method returns a [`BackendStatus`](/api/qiskit/qiskit.providers.models.BackendStatus ""(in Qiskit v0.46)"") instance. The instance contains the `operational` and `pending_jobs` attributes, which state whether the backend is operational and also the number of jobs in the server queue for the backend, respectively: ```python status = backend.status() is_operational = status.operational jobs_in_queue = status.pending_jobs ``` **Here is list of attributes available on the `IBMBackend` class:** * name: backend name. * backend\_version: backend version in the form X.Y.Z. * num\_qubits: number of qubits. * target: A [`qiskit.transpiler.Target`](/api/qiskit/qiskit.transpiler.Target ""(in Qiskit v0.46)"") object for the backend. * basis\_gates: list of basis gates names on the backend. * gates: list of basis gates on the backend. * local: backend is local or remote. * simulator: backend is a simulator. * conditional: backend supports conditional operations. * open\_pulse: backend supports open pulse. * memory: backend supports memory. * max\_shots: maximum number of shots supported. * coupling\_map (list): The coupling map for the device * supported\_instructions (List\[str]): Instructions supported by the backend. * dynamic\_reprate\_enabled (bool): whether delay between programs can be set dynamically (ie via `rep_delay`). Defaults to False. * rep\_delay\_range (List\[float]): 2d list defining supported range of repetition delays for backend in μs. First entry is lower end of the range, second entry is higher end of the range. Optional, but will be specified when `dynamic_reprate_enabled=True`. * default\_rep\_delay (float): Value of `rep_delay` if not specified by user and `dynamic_reprate_enabled=True`. * n\_uchannels: Number of u-channels. * u\_channel\_lo: U-channel relationship on device los. * meas\_levels: Supported measurement levels. * qubit\_lo\_range: Qubit lo ranges for each qubit with form (min, max) in GHz. * meas\_lo\_range: Measurement lo ranges for each qubit with form (min, max) in GHz. * dt: Qubit drive channel timestep in nanoseconds. * dtm: Measurement drive channel timestep in nanoseconds. * rep\_times: Supported repetition times (program execution time) for backend in μs. * meas\_kernels: Supported measurement kernels. * discriminators: Supported discriminators. * hamiltonian: An optional dictionary with fields characterizing the system hamiltonian. * channel\_bandwidth (list): Bandwidth of all channels (qubit, measurement, and U) * acquisition\_latency (list): Array of dimension n\_qubits x n\_registers. Latency (in units of dt) to write a measurement result from qubit n into register slot m. * conditional\_latency (list): Array of dimension n\_channels \[d->u->m] x n\_registers. Latency (in units of dt) to do a conditional operation on channel n from register slot m * meas\_map (list): Grouping of measurement which are multiplexed * max\_circuits (int): The maximum number of experiments per job * sample\_name (str): Sample name for the backend * n\_registers (int): Number of register slots available for feedback (if conditional is True) * register\_map (list): An array of dimension n\_qubits X n\_registers that specifies whether a qubit can store a measurement in a certain register slot. * configurable (bool): True if the backend is configurable, if the backend is a simulator * credits\_required (bool): True if backend requires credits to run a job. * online\_date (datetime): The date that the device went online * display\_name (str): Alternate name field for the backend * description (str): A description for the backend * tags (list): A list of string tags to describe the backend * version: version of `Backend` class (Ex: 1, 2) * channels: An optional dictionary containing information of each channel – their purpose, type, and qubits operated on. * parametric\_pulses (list): A list of pulse shapes which are supported on the backend. For example: `['gaussian', 'constant']` * processor\_type (dict): Processor type for this backend. A dictionary of the form `{""family"": , ""revision"": , segment: }` such as `{""family"": ""Canary"", ""revision"": ""1.0"", segment: ""A""}`. > * family: Processor family of this backend. > * revision: Revision version of this processor. > * segment: Segment this processor belongs to within a larger chip. IBMBackend constructor. **Parameters** * **configuration** (`Union`\[[`QasmBackendConfiguration`](/api/qiskit/qiskit.providers.models.QasmBackendConfiguration ""(in Qiskit v0.46)""), [`PulseBackendConfiguration`](/api/qiskit/qiskit.providers.models.PulseBackendConfiguration ""(in Qiskit v0.46)"")]) – Backend configuration. * **provider** ([`IBMProvider`](qiskit_ibm_provider.IBMProvider ""qiskit_ibm_provider.ibm_provider.IBMProvider"")) – IBM Quantum account provider. * **api\_client** (`AccountClient`) – IBM Quantum client used to communicate with the server. ## Attributes ### coupling\_map Return the [`CouplingMap`](/api/qiskit/qiskit.transpiler.CouplingMap ""(in Qiskit v0.46)"") object ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals :returns: The output signal timestep in seconds. :rtype: dtm ### id\_warning\_issued ### instruction\_durations Return the [`InstructionDurations`](/api/qiskit/qiskit.transpiler.InstructionDurations ""(in Qiskit v0.46)"") object. ### instruction\_schedule\_map Return the [`InstructionScheduleMap`](/api/qiskit/qiskit.pulse.InstructionScheduleMap ""(in Qiskit v0.46)"") for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[[`Instruction`](/api/qiskit/qiskit.circuit.Instruction ""(in Qiskit v0.46)""), `Tuple`\[`int`]]] ### max\_circuits The maximum number of circuits The maximum number of circuits that can be run in a single job. If there is no limit this will return None. **Return type** `int` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. :returns: The grouping of measurements which are multiplexed :rtype: meas\_map ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of [`Instruction`](/api/qiskit/qiskit.circuit.Instruction ""(in Qiskit v0.46)"") instances that the backend supports. **Return type** `List`\[[`Instruction`](/api/qiskit/qiskit.circuit.Instruction ""(in Qiskit v0.46)"")] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_provider.IBMBackend.run ""qiskit_ibm_provider.IBMBackend.run"") method. ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### session Return session **Return type** [`Session`](qiskit_ibm_provider.Session ""qiskit_ibm_provider.session.Session"") ### target A [`qiskit.transpiler.Target`](/api/qiskit/qiskit.transpiler.Target ""(in Qiskit v0.46)"") object for the backend. :rtype: [`Target`](/api/qiskit/qiskit.transpiler.Target ""(in Qiskit v0.46)"") :returns: Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### cancel\_session Cancel session. All pending jobs will be cancelled. **Return type** `None` ### close\_session Close the session so new jobs will no longer be accepted, but existing queued or running jobs will run to completion. The session will be terminated once there are no more pending jobs. **Return type** `None` ### configuration Return the backend configuration. Backend configuration contains fixed information about the backend, such as its name, number of qubits, basis gates, coupling map, quantum volume, etc. The schema for backend configuration can be found in [Qiskit/ibm-quantum-schemas](https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/backend_configuration_schema.json). **Return type** `Union`\[[`QasmBackendConfiguration`](/api/qiskit/qiskit.providers.models.QasmBackendConfiguration ""(in Qiskit v0.46)""), [`PulseBackendConfiguration`](/api/qiskit/qiskit.providers.models.PulseBackendConfiguration ""(in Qiskit v0.46)"")] **Returns** The configuration for the backend. ### control\_channel Return the secondary drive channel for the given qubit. This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The Qubit measurement acquisition line. **Return type** List\[ControlChannel] ### defaults Return the pulse defaults for the backend. The schema for default pulse configuration can be found in [Qiskit/ibm-quantum-schemas](https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/default_pulse_configuration_schema.json). **Parameters** **refresh** (`bool`) – If `True`, re-query the server for the backend pulse defaults. Otherwise, return a cached version. **Return type** `Optional`\[[`PulseDefaults`](/api/qiskit/qiskit.providers.models.PulseDefaults ""(in Qiskit v0.46)"")] **Returns** The backend pulse defaults or `None` if the backend does not support pulse. ### drive\_channel Return the drive channel for the given qubit. **Returns** The Qubit drive channel **Return type** DriveChannel ### get\_translation\_stage\_plugin Return the default translation stage plugin name for IBM backends. **Return type** `str` ### measure\_channel Return the measure stimulus channel for the given qubit. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### open\_session Open session **Return type** [`Session`](qiskit_ibm_provider.Session ""qiskit_ibm_provider.session.Session"") ### properties Return the backend properties, subject to optional filtering. This data describes qubits properties (such as T1 and T2), gates properties (such as gate length and error), and other general properties of the backend. The schema for backend properties can be found in [Qiskit/ibm-quantum-schemas](https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/backend_properties_schema.json). **Parameters** * **refresh** (`bool`) – If `True`, re-query the server for the backend properties. Otherwise, return a cached version. * **datetime** (`Optional`\[`datetime`]) – By specifying datetime, this function returns an instance of the [`BackendProperties`](/api/qiskit/qiskit.providers.models.BackendProperties ""(in Qiskit v0.46)"") whose timestamp is closest to, but older than, the specified datetime. **Return type** `Optional`\[[`BackendProperties`](/api/qiskit/qiskit.providers.models.BackendProperties ""(in Qiskit v0.46)"")] **Returns** The backend properties or `None` if the backend properties are not currently available. **Raises** **TypeError** – If an input argument is not of the correct type. ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[[`QubitProperties`](/api/qiskit/qiskit.providers.QubitProperties ""(in Qiskit v0.46)""), `List`\[[`QubitProperties`](/api/qiskit/qiskit.providers.QubitProperties ""(in Qiskit v0.46)"")]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### run Run on the backend. If a keyword specified here is also present in the `options` attribute/object, the value specified here will be used for this run. **Parameters** * **circuits** (`Union`\[[`QuantumCircuit`](/api/qiskit/qiskit.circuit.QuantumCircuit ""(in Qiskit v0.46)""), `str`, `List`\[`Union`\[[`QuantumCircuit`](/api/qiskit/qiskit.circuit.QuantumCircuit ""(in Qiskit v0.46)""), `str`]]]) – An individual or a list of `QuantumCircuit`. * **dynamic** (`Optional`\[`bool`]) – Whether the circuit is dynamic (uses in-circuit conditionals) * **job\_tags** (`Optional`\[`List`\[`str`]]) – Tags to be assigned to the job. The tags can subsequently be used as a filter in the `jobs()` function call. * **init\_circuit** (`Optional`\[[`QuantumCircuit`](/api/qiskit/qiskit.circuit.QuantumCircuit ""(in Qiskit v0.46)"")]) – A quantum circuit to execute for initializing qubits before each circuit. If specified, `init_num_resets` is ignored. Applicable only if `dynamic=True` is specified. * **init\_num\_resets** (`Optional`\[`int`]) – The number of qubit resets to insert before each circuit execution. * **or** (*The following parameters are applicable only if dynamic=False is specified*) – * **to.** (*defaulted*) – * **header** (`Optional`\[`Dict`]) – User input that will be attached to the job and will be copied to the corresponding result header. Headers do not affect the run. This replaces the old `Qobj` header. * **shots** (`Union`\[`int`, `float`, `None`]) – Number of repetitions of each circuit, for sampling. Default: 4000 or `max_shots` from the backend configuration, whichever is smaller. * **memory** (`Optional`\[`bool`]) – 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. * **meas\_level** (`Union`\[`int`, `MeasLevel`, `None`]) – Level of the measurement output for pulse experiments. See [OpenPulse specification](https://arxiv.org/pdf/1809.03452.pdf) for details: * `0`, measurements of the raw signal (the measurement output pulse envelope) * `1`, measurement kernel is selected (a complex number obtained after applying the measurement kernel to the measurement output signal) * `2` (default), a discriminator is selected and the qubit state is stored (0 or 1) * **meas\_return** (`Union`\[`str`, `MeasReturnType`, `None`]) – 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). * **rep\_delay** (`Optional`\[`float`]) – Delay between programs in seconds. Only supported on certain backends (if `backend.configuration().dynamic_reprate_enabled=True`). If supported, `rep_delay` must be from the range supplied by the backend (`backend.configuration().rep_delay_range`). Default is given by `backend.configuration().default_rep_delay`. * **init\_qubits** (`Optional`\[`bool`]) – Whether to reset the qubits to the ground state for each shot. Default: `True`. * **use\_measure\_esp** (`Optional`\[`bool`]) – Whether to use excited state promoted (ESP) readout for measurements which are the terminal instruction to a qubit. ESP readout can offer higher fidelity than standard measurement sequences. See [here](https://arxiv.org/pdf/2008.08571.pdf). Default: `True` if backend supports ESP readout, else `False`. Backend support for ESP readout is determined by the flag `measure_esp_enabled` in `backend.configuration()`. * **noise\_model** (`Optional`\[`Any`]) – Noise model. (Simulators only) * **seed\_simulator** (`Optional`\[`int`]) – Random seed to control sampling. (Simulators only) * **\*\*run\_config** – Extra arguments used to configure the run. **Return type** `IBMJob` **Returns** The job to be executed. **Raises** * [**IBMBackendApiError**](qiskit_ibm_provider.IBMBackendApiError ""qiskit_ibm_provider.IBMBackendApiError"") – If an unexpected error occurred while submitting the job. * [**IBMBackendApiProtocolError**](qiskit_ibm_provider.IBMBackendApiProtocolError ""qiskit_ibm_provider.IBMBackendApiProtocolError"") – If an unexpected value received from the server. * [**IBMBackendValueError**](qiskit_ibm_provider.IBMBackendValueError ""qiskit_ibm_provider.IBMBackendValueError"") – * If an input parameter value is not valid. - If ESP readout is used and the backend does not support this. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. If the returned [`BackendStatus`](/api/qiskit/qiskit.providers.models.BackendStatus ""(in Qiskit v0.46)"") instance has `operational=True` but `status_msg=""internal""`, then the backend is accepting jobs but not processing them. **Return type** [`BackendStatus`](/api/qiskit/qiskit.providers.models.BackendStatus ""(in Qiskit v0.46)"") **Returns** The status of the backend. **Raises** [**IBMBackendApiProtocolError**](qiskit_ibm_provider.IBMBackendApiProtocolError ""qiskit_ibm_provider.IBMBackendApiProtocolError"") – If the status for the backend cannot be formatted properly. ### target\_history A [`qiskit.transpiler.Target`](/api/qiskit/qiskit.transpiler.Target ""(in Qiskit v0.46)"") object for the backend. :rtype: [`Target`](/api/qiskit/qiskit.transpiler.Target ""(in Qiskit v0.46)"") :returns: Target with properties found on datetime ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.IBMBackend.mdx "--- title: IBMBackendApiError description: API reference for qiskit_ibm_provider.IBMBackendApiError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.IBMBackendApiError --- # IBMBackendApiError Errors that occur unexpectedly when querying the server. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.IBMBackendApiError.mdx "--- title: IBMBackendApiProtocolError description: API reference for qiskit_ibm_provider.IBMBackendApiProtocolError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.IBMBackendApiProtocolError --- # IBMBackendApiProtocolError Errors raised when an unexpected value is received from the server. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.IBMBackendApiProtocolError.mdx "--- title: IBMBackendError description: API reference for qiskit_ibm_provider.IBMBackendError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.IBMBackendError --- # IBMBackendError Base class for errors raised by the backend modules. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.IBMBackendError.mdx "--- title: IBMBackendService description: API reference for qiskit_ibm_provider.IBMBackendService in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.IBMBackendService --- # IBMBackendService Backend namespace for an IBM Quantum account. Represent a namespace that provides backend related services for the IBM Quantum backends available to this account. An instance of this class is used as a callable attribute to the [`IBMProvider`](qiskit_ibm_provider.IBMProvider ""qiskit_ibm_provider.IBMProvider"") class. This allows a convenient way to query for all backends or to access a specific backend: ```python backends = provider.backends() # Invoke backends() to get the backends. sim_backend = provider.backend.ibmq_qasm_simulator # Get a specific backend instance. ``` Also, you are able to retrieve jobs from an account without specifying the backend name. For example, to retrieve the ten most recent jobs you have submitted, regardless of the backend they were submitted to, you could do: ```python most_recent_jobs = provider.backend.jobs(limit=10) ``` It is also possible to retrieve a single job without specifying the backend name: ```python job = provider.backend.retrieve_job() ``` IBMBackendService constructor. **Parameters** * **provider** ([`IBMProvider`](qiskit_ibm_provider.IBMProvider ""qiskit_ibm_provider.ibm_provider.IBMProvider"")) – IBM Quantum account provider. * **hgp** (`HubGroupProject`) – default hub/group/project to use for the service. ## Methods ### backends Return all backends accessible via this account, subject to optional filtering. **Parameters** * **name** (`Optional`\[`str`]) – Backend name to filter by. * **min\_num\_qubits** (`Optional`\[`int`]) – Minimum number of qubits the backend must have. * **instance** (`Optional`\[`str`]) – The provider in the hub/group/project format. * **dynamic\_circuits** (`Optional`\[`bool`]) – Filter by whether the backend supports dynamic circuits. * **filters** (`Optional`\[`Callable`\[\[`List`\[[`IBMBackend`](qiskit_ibm_provider.IBMBackend ""qiskit_ibm_provider.ibm_backend.IBMBackend"")]], `bool`]]) – More complex filters, such as lambda functions. For example: ```python IBMProvider.backends(filters=lambda b: b.max_shots > 50000) IBMProvider.backends(filters=lambda x: (""rz"" in x.basis_gates ) ``` * **\*\*kwargs** – Simple filters that require a specific value for an attribute in backend configuration, backend status, or provider credentials. Examples: ```python # Get the operational real backends IBMProvider.backends(simulator=False, operational=True) # Get the backends with at least 127 qubits IBMProvider.backends(min_num_qubits=127) # Get the backends that support OpenPulse IBMProvider.backends(open_pulse=True) ``` For the full list of backend attributes, see the IBMBackend class documentation \<[providers\_models](/api/qiskit/providers_models)> **Return type** `List`\[[`IBMBackend`](qiskit_ibm_provider.IBMBackend ""qiskit_ibm_provider.ibm_backend.IBMBackend"")] **Returns** The list of available backends that match the filter. **Raises** * [**IBMBackendValueError**](qiskit_ibm_provider.IBMBackendValueError ""qiskit_ibm_provider.IBMBackendValueError"") – If only one or two parameters from hub, group, project are specified. * **QiskitBackendNotFoundError** – If the backend is not found in any instance. ### jobs Return a list of jobs, subject to optional filtering. Retrieve jobs that match the given filters and paginate the results if desired. Note that the server has a limit for the number of jobs returned in a single call. As a result, this function might involve making several calls to the server. **Parameters** * **limit** (`Optional`\[`int`]) – Number of jobs to retrieve. `None` means no limit. Note that the number of sub-jobs within a composite job count towards the limit. * **skip** (`int`) – Starting index for the job retrieval. * **backend\_name** (`Optional`\[`str`]) – Name of the backend to retrieve jobs from. * **status** (`Union`\[`Literal`\[‘pending’, ‘completed’], `List`\[`Union`\[[`JobStatus`](/api/qiskit/qiskit.providers.JobStatus ""(in Qiskit v0.46)""), `str`]], [`JobStatus`](/api/qiskit/qiskit.providers.JobStatus ""(in Qiskit v0.46)""), `str`, `None`]) – Filter jobs with either “pending” or “completed” status. You can also specify by * **example** (*exact status. For*) – or status=\[“RUNNING”, “ERROR”]. * **status=""RUNNING""** (*status=JobStatus.RUNNING or*) – or status=\[“RUNNING”, “ERROR”]. * **start\_datetime** (`Optional`\[`datetime`]) – Filter by the given start date, in local time. This is used to find jobs whose creation dates are after (greater than or equal to) this local date/time. * **end\_datetime** (`Optional`\[`datetime`]) – Filter by the given end date, in local time. This is used to find jobs whose creation dates are before (less than or equal to) this local date/time. * **job\_tags** (`Optional`\[`List`\[`str`]]) – Filter by tags assigned to jobs. Matched jobs are associated with all tags. * **descending** (`bool`) – If `True`, return the jobs in descending order of the job creation date (i.e. newest first) until the limit is reached. * **instance** (`Optional`\[`str`]) – The provider in the hub/group/project format. * **legacy** (`bool`) – If `True`, only retrieve jobs run from the archived `qiskit-ibmq-provider`. * **Otherwise** – * **qiskit-ibm-provider.** (*only retrieve jobs run from*) – **Return type** `List`\[`IBMJob`] **Returns** A list of `IBMJob` instances. **Raises** * [**IBMBackendValueError**](qiskit_ibm_provider.IBMBackendValueError ""qiskit_ibm_provider.IBMBackendValueError"") – If a keyword value is not recognized. * **TypeError** – If the input start\_datetime or end\_datetime parameter value is not valid. ### retrieve\_job Return a single job. **Parameters** **job\_id** (`str`) – The ID of the job to retrieve. **Return type** `IBMJob` **Returns** The job with the given id. **Raises** * [**IBMBackendApiError**](qiskit_ibm_provider.IBMBackendApiError ""qiskit_ibm_provider.IBMBackendApiError"") – If an unexpected error occurred when retrieving the job. * [**IBMBackendApiProtocolError**](qiskit_ibm_provider.IBMBackendApiProtocolError ""qiskit_ibm_provider.IBMBackendApiProtocolError"") – If unexpected return value received from the server. * **IBMJobNotFoundError** – If job cannot be found. * **IBMInputValueError** – If job exists but was run from a different service. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.IBMBackendService.mdx "--- title: IBMBackendValueError description: API reference for qiskit_ibm_provider.IBMBackendValueError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.IBMBackendValueError --- # IBMBackendValueError Value errors raised by the backend modules. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.IBMBackendValueError.mdx "--- title: IBMError description: API reference for qiskit_ibm_provider.IBMError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.IBMError --- # IBMError Base class for errors raised by the provider modules. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.IBMError.mdx "--- title: IBMProvider description: API reference for qiskit_ibm_provider.IBMProvider in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.IBMProvider --- # IBMProvider Provides access to the IBM Quantum services available to an account. Authenticate against IBM Quantum for use from saved credentials or during session. Credentials can be saved to disk by calling the save\_account() method: ```python from qiskit_ibm_provider import IBMProvider IBMProvider.save_account(token=) ``` You can set the default project using the hub, group, and project keywords in save\_account(). Once credentials are saved you can simply instantiate the provider like below to load the saved account and default project: ```python from qiskit_ibm_provider import IBMProvider provider = IBMProvider() ``` Instead of saving credentials to disk, you can also set the environment variables QISKIT\_IBM\_TOKEN, QISKIT\_IBM\_URL and QISKIT\_IBM\_INSTANCE and then instantiate the provider as below: ```python from qiskit_ibm_provider import IBMProvider provider = IBMProvider() ``` You can also enable an account just for the current session by instantiating the provider with the API token: ```python from qiskit_ibm_provider import IBMProvider provider = IBMProvider(token=) ``` token is the only required attribute that needs to be set using one of the above methods. If no url is set, it defaults to ‘[https://auth.quantum-computing.ibm.com/api](https://auth.quantum-computing.ibm.com/api)’. The hub/group/project is selected based on the below selection order, in decreasing order of priority. * The hub/group/project you explicity specify when calling a service. Ex: provider.get\_backend(), etc. * The hub/group/project required for the service. * The default hub/group/project you set using save\_account(). * A premium hub/group/project in your account. * An open access hub/group/project. The IBMProvider offers the [`IBMBackendService`](qiskit_ibm_provider.IBMBackendService ""qiskit_ibm_provider.ibm_backend_service.IBMBackendService"") which gives access to the IBM Quantum devices and simulators. You can obtain an instance of the service as an attribute of the `IBMProvider` instance. For example: ```python backend_service = provider.backend ``` Since [`IBMBackendService`](qiskit_ibm_provider.IBMBackendService ""qiskit_ibm_provider.ibm_backend_service.IBMBackendService"") is the main service, some of the backend-related methods are available through this class for convenience. The [`backends()`](#qiskit_ibm_provider.IBMProvider.backends ""qiskit_ibm_provider.IBMProvider.backends"") method returns all the backends available to this account: ```python backends = provider.backends() ``` The [`get_backend()`](#qiskit_ibm_provider.IBMProvider.get_backend ""qiskit_ibm_provider.IBMProvider.get_backend"") method returns a backend that matches the filters passed as argument. An example of retrieving a backend that matches a specified name: ```python simulator_backend = provider.get_backend('ibmq_qasm_simulator') ``` IBMBackend’s are uniquely identified by their name. If you invoke [`get_backend()`](#qiskit_ibm_provider.IBMProvider.get_backend ""qiskit_ibm_provider.IBMProvider.get_backend"") twice, you will get the same IBMBackend instance, and any previously updated options will be reset to the default values. It is also possible to use the `backend` attribute to reference a backend. As an example, to retrieve the same backend from the example above: ```python simulator_backend = provider.backend.ibmq_qasm_simulator ``` The `backend` attribute can be used to autocomplete the names of backends available to this account. To autocomplete, press `tab` after `provider.backend.`. This feature may not be available if an error occurs during backend discovery. Also note that this feature is only available in interactive sessions, such as in Jupyter Notebook and the Python interpreter. IBMProvider constructor **Parameters** * **token** (`Optional`\[`str`]) – IBM Quantum API token. * **url** (`Optional`\[`str`]) – The API URL. Defaults to [https://auth.quantum-computing.ibm.com/api](https://auth.quantum-computing.ibm.com/api). * **name** (`Optional`\[`str`]) – Name of the account to load. * **instance** (`Optional`\[`str`]) – Provider in the hub/group/project format. * **proxies** (`Optional`\[`dict`]) – Proxy configuration. Supported optional keys are `urls` (a dictionary mapping protocol or protocol and host to the URL of the proxy, documented at [https://docs.python-requests.org/en/latest/api/#requests.Session.proxies](https://docs.python-requests.org/en/latest/api/#requests.Session.proxies)), `username_ntlm`, `password_ntlm` (username and password to enable NTLM user authentication) * **verify** (`Optional`\[`bool`]) – Whether to verify the server’s TLS certificate. **Returns** An instance of IBMProvider **Raises** **IBMInputValueError** – If an input is invalid. ## Attributes ### backend Return the backend service. **Return type** [`IBMBackendService`](qiskit_ibm_provider.IBMBackendService ""qiskit_ibm_provider.ibm_backend_service.IBMBackendService"") **Returns** The backend service instance. ### version ## Methods ### active\_account Return the IBM Quantum account currently in use for the session. **Return type** `Optional`\[`Dict`\[`str`, `str`]] **Returns** A dictionary with information about the account currently in the session. ### backends Return all backends accessible via this account, subject to optional filtering. **Parameters** * **name** (`Optional`\[`str`]) – Backend name to filter by. * **min\_num\_qubits** (`Optional`\[`int`]) – Minimum number of qubits the backend must have. * **instance** (`Optional`\[`str`]) – The provider in the hub/group/project format. * **filters** (`Optional`\[`Callable`\[\[`List`\[[`IBMBackend`](qiskit_ibm_provider.IBMBackend ""qiskit_ibm_provider.ibm_backend.IBMBackend"")]], `bool`]]) – More complex filters, such as lambda functions. For example: ```python IBMProvider.backends(filters=lambda b: b.max_shots > 50000) IBMProvider.backends(filters=lambda x: (""rz"" in x.basis_gates ) ``` * **\*\*kwargs** – Simple filters that require a specific value for an attribute in backend configuration, backend status, or provider credentials. Examples: ```python # Get the operational real backends IBMProvider.backends(simulator=False, operational=True) # Get the backends with at least 127 qubits IBMProvider.backends(min_num_qubits=127) # Get the backends that support OpenPulse IBMProvider.backends(open_pulse=True) ``` For the full list of backend attributes, see the IBMBackend class documentation \<[providers\_models](/api/qiskit/providers_models)> **Return type** `List`\[[`IBMBackend`](qiskit_ibm_provider.IBMBackend ""qiskit_ibm_provider.ibm_backend.IBMBackend"")] **Returns** The list of available backends that match the filter. ### delete\_account Delete a saved account from disk. **Parameters** **name** (`Optional`\[`str`]) – Name of the saved account to delete. **Return type** `bool` **Returns** True if the account was deleted. False if no account was found. ### get\_backend Return a single backend matching the specified filtering. **Parameters** * **name** (*str*) – Name of the backend. * **instance** (`Optional`\[`str`]) – The provider in the hub/group/project format. * **\*\*kwargs** – Dict used for filtering. **Returns** a backend matching the filtering. **Return type** Backend **Raises** * **QiskitBackendNotFoundError** – if no backend could be found or more than one backend matches the filtering criteria. * [**IBMProviderValueError**](qiskit_ibm_provider.IBMProviderValueError ""qiskit_ibm_provider.IBMProviderValueError"") – If only one or two parameters from hub, group, project are specified. ### instances Return the IBM Quantum instances list currently in use for the session. **Return type** `List`\[`str`] **Returns** A list with instances currently in the session. ### jobs Return a list of jobs, subject to optional filtering. Retrieve jobs that match the given filters and paginate the results if desired. Note that the server has a limit for the number of jobs returned in a single call. As a result, this function might involve making several calls to the server. **Parameters** * **limit** (`Optional`\[`int`]) – Number of jobs to retrieve. `None` means no limit. Note that the number of sub-jobs within a composite job count towards the limit. * **skip** (`int`) – Starting index for the job retrieval. * **backend\_name** (`Optional`\[`str`]) – Name of the backend to retrieve jobs from. * **status** (`Optional`\[`Literal`\[‘pending’, ‘completed’]]) – Filter jobs with either “pending” or “completed” status. * **start\_datetime** (`Optional`\[`datetime`]) – Filter by the given start date, in local time. This is used to find jobs whose creation dates are after (greater than or equal to) this local date/time. * **end\_datetime** (`Optional`\[`datetime`]) – Filter by the given end date, in local time. This is used to find jobs whose creation dates are before (less than or equal to) this local date/time. * **job\_tags** (`Optional`\[`List`\[`str`]]) – Filter by tags assigned to jobs. Matched jobs are associated with all tags. * **descending** (`bool`) – If `True`, return the jobs in descending order of the job creation date (i.e. newest first) until the limit is reached. * **instance** (`Optional`\[`str`]) – The provider in the hub/group/project format. * **legacy** (`bool`) – If `True`, only retrieve jobs run from the deprecated `qiskit-ibmq-provider`. * **Otherwise** – * **qiskit-ibm-provider.** (*only retrieve jobs run from*) – **Return type** `List`\[`IBMJob`] **Returns** A list of `IBMJob` instances. ### retrieve\_job Return a single job. **Parameters** **job\_id** (`str`) – The ID of the job to retrieve. **Return type** `IBMJob` **Returns** The job with the given id. ### save\_account Save the account to disk for future use. **Parameters** * **token** (`Optional`\[`str`]) – IBM Quantum API token. * **url** (`Optional`\[`str`]) – The API URL. Defaults to [https://auth.quantum-computing.ibm.com/api](https://auth.quantum-computing.ibm.com/api) * **instance** (`Optional`\[`str`]) – The hub/group/project. * **name** (`Optional`\[`str`]) – Name of the account to save. * **proxies** (`Optional`\[`dict`]) – Proxy configuration. Supported optional keys are `urls` (a dictionary mapping protocol or protocol and host to the URL of the proxy, documented at [https://docs.python-requests.org/en/latest/api/#requests.Session.proxies](https://docs.python-requests.org/en/latest/api/#requests.Session.proxies)), `username_ntlm`, `password_ntlm` (username and password to enable NTLM user authentication) * **verify** (`Optional`\[`bool`]) – Verify the server’s TLS certificate. * **overwrite** (`Optional`\[`bool`]) – `True` if the existing account is to be overwritten. **Return type** `None` ### saved\_accounts List the accounts saved on disk. **Parameters** * **default** (`Optional`\[`bool`]) – If set to True, only default accounts are returned. * **name** (`Optional`\[`str`]) – If set, only accounts with the given name are returned. **Return type** `dict` **Returns** A dictionary with information about the accounts saved on disk. **Raises** **ValueError** – If an invalid account is found on disk. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.IBMProvider.mdx "--- title: IBMProviderError description: API reference for qiskit_ibm_provider.IBMProviderError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.IBMProviderError --- # IBMProviderError Base class for errors raise by IBMProvider. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.IBMProviderError.mdx "--- title: IBMProviderValueError description: API reference for qiskit_ibm_provider.IBMProviderValueError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.IBMProviderValueError --- # IBMProviderValueError Value errors raised by IBMProvider. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.IBMProviderValueError.mdx "--- title: IBMCircuitJob description: API reference for qiskit_ibm_provider.job.IBMCircuitJob in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.job.IBMCircuitJob --- # IBMCircuitJob Representation of a job that executes on an IBM Quantum backend. The job may be executed on a simulator or a real device. A new `IBMCircuitJob` instance is returned when you call `IBMBackend.run()` to submit a job to a particular backend. If the job is successfully submitted, you can inspect the job’s status by calling [`status()`](#qiskit_ibm_provider.job.IBMCircuitJob.status ""qiskit_ibm_provider.job.IBMCircuitJob.status""). Job status can be one of the [`JobStatus`](/api/qiskit/qiskit.providers.JobStatus ""(in Qiskit v0.46)"") members. For example: ```python from qiskit.providers.jobstatus import JobStatus job = backend.run(...) try: job_status = job.status() # Query the backend server for job status. if job_status is JobStatus.RUNNING: print(""The job is still running"") except IBMJobApiError as ex: print(""Something wrong happened!: {}"".format(ex)) ``` An error may occur when querying the remote server to get job information. The most common errors are temporary network failures and server errors, in which case an [`IBMJobApiError`](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") is raised. These errors usually clear quickly, so retrying the operation is likely to succeed. Some of the methods in this class are blocking, which means control may not be returned immediately. [`result()`](#qiskit_ibm_provider.job.IBMCircuitJob.result ""qiskit_ibm_provider.job.IBMCircuitJob.result"") is an example of a blocking method: ```python job = backend.run(...) try: job_result = job.result() # It will block until the job finishes. print(""The job finished with result {}"".format(job_result)) except JobError as ex: print(""Something wrong happened!: {}"".format(ex)) ``` Job information retrieved from the server is attached to the `IBMCircuitJob` instance as attributes. Given that Qiskit and the server can be updated independently, some of these attributes might be deprecated or experimental. Supported attributes can be retrieved via methods. For example, you can use [`creation_date()`](#qiskit_ibm_provider.job.IBMCircuitJob.creation_date ""qiskit_ibm_provider.job.IBMCircuitJob.creation_date"") to retrieve the job creation date, which is a supported attribute. IBMCircuitJob constructor. **Parameters** * **backend** ([`IBMBackend`](qiskit_ibm_provider.IBMBackend ""qiskit_ibm_provider.ibm_backend.IBMBackend"")) – The backend instance used to run this job. * **api\_client** (`AccountClient`) – Object for connecting to the server. * **job\_id** (`str`) – Job ID. * **creation\_date** (`Optional`\[`str`]) – Job creation date. * **status** (`Optional`\[`str`]) – Job status returned by the server. * **runtime\_client** (`Optional`\[`RuntimeClient`]) – Object for connecting to the runtime server * **kind** (`Optional`\[`str`]) – Job type. * **name** (`Optional`\[`str`]) – Job name. * **time\_per\_step** (`Optional`\[`dict`]) – Time spent for each processing step. * **result** (`Optional`\[`dict`]) – Job result. * **error** (`Optional`\[`dict`]) – Job error. * **tags** (`Optional`\[`List`\[`str`]]) – Job tags. * **run\_mode** (`Optional`\[`str`]) – Scheduling mode the job runs in. * **client\_info** (`Optional`\[`Dict`\[`str`, `str`]]) – Client information from the API. * **kwargs** (`Any`) – Additional job attributes. ## Attributes ### client\_version Return version of the client used for this job. **Return type** `Dict`\[`str`, `str`] **Returns** **Client version in dictionary format, where the key is the name** of the client and the value is the version. ### usage\_estimation Return usage estimation information for this job. **Return type** `Dict`\[`str`, `Any`] **Returns** `quantum_seconds` which is the estimated quantum time of the job in seconds. Quantum time represents the time that the QPU complex is occupied exclusively by the job. ### version ## Methods ### backend Return the backend where this job was executed. **Return type** [`Backend`](/api/qiskit/qiskit.providers.Backend ""(in Qiskit v0.46)"") ### backend\_options Return the backend configuration options used for this job. Options that are not applicable to the job execution are not returned. Some but not all of the options with default values are returned. You can use [`qiskit_ibm_provider.IBMBackend.options`](qiskit_ibm_provider.IBMBackend#options ""qiskit_ibm_provider.IBMBackend.options"") to see all backend options. **Return type** `Dict` **Returns** Backend options used for this job. An empty dictionary is returned if the options cannot be retrieved. ### cancel Attempt to cancel the job. Depending on the state the job is in, it might be impossible to cancel the job. **Return type** `bool` **Returns** `True` if the job is cancelled, else `False`. **Raises** * [**IBMJobInvalidStateError**](qiskit_ibm_provider.job.IBMJobInvalidStateError ""qiskit_ibm_provider.job.IBMJobInvalidStateError"") – If the job is in a state that cannot be cancelled. * [**IBMJobError**](qiskit_ibm_provider.job.IBMJobError ""qiskit_ibm_provider.job.IBMJobError"") – If unable to cancel job. ### cancelled Return whether the job has been cancelled. **Return type** `bool` ### circuits Return the circuits for this job. **Return type** `List`\[[`QuantumCircuit`](/api/qiskit/qiskit.circuit.QuantumCircuit ""(in Qiskit v0.46)"")] **Returns** The circuits or for this job. An empty list is returned if the circuits cannot be retrieved (for example, if the job uses an old format that is no longer supported). ### creation\_date Return job creation date, in local time. **Return type** `datetime` **Returns** The job creation date as a datetime object, in local time. ### done Return whether the job has successfully run. **Return type** `bool` ### error\_message Provide details about the reason of failure. **Return type** `Optional`\[`str`] **Returns** An error report if the job failed or `None` otherwise. ### header Return the user header specified for this job. **Return type** `Dict` **Returns** User header specified for this job. An empty dictionary is returned if the header cannot be retrieved. ### in\_final\_state Return whether the job is in a final job state such as `DONE` or `ERROR`. **Return type** `bool` ### job\_id Return the job ID assigned by the server. **Return type** `str` **Returns** Job ID. ### name Return the name assigned to this job. **Return type** `Optional`\[`str`] **Returns** Job name or `None` if no name was assigned to this job. ### properties Return the backend properties for this job. **Parameters** **refresh** (`bool`) – If `True`, re-query the server for the backend properties. Otherwise, return a cached version. **Return type** `Optional`\[[`BackendProperties`](/api/qiskit/qiskit.providers.models.BackendProperties ""(in Qiskit v0.46)"")] **Returns** The backend properties used for this job, at the time the job was run, or `None` if properties are not available. ### queue\_info Return queue information for this job. The queue information may include queue position, estimated start and end time, and dynamic priorities for the hub, group, and project. See [`QueueInfo`](qiskit_ibm_provider.job.QueueInfo ""qiskit_ibm_provider.job.QueueInfo"") for more information. The queue information is calculated after the job enters the queue. Therefore, some or all of the information may not be immediately available, and this method may return `None`. **Return type** `Optional`\[[`QueueInfo`](qiskit_ibm_provider.job.QueueInfo ""qiskit_ibm_provider.job.queueinfo.QueueInfo"")] **Returns** A [`QueueInfo`](qiskit_ibm_provider.job.QueueInfo ""qiskit_ibm_provider.job.QueueInfo"") instance that contains queue information for this job, or `None` if queue information is unknown or not applicable. ### queue\_position Return the position of the job in the server queue. The position returned is within the scope of the provider and may differ from the global queue position. **Parameters** **refresh** (`bool`) – If `True`, re-query the server to get the latest value. Otherwise return the cached value. **Return type** `Optional`\[`int`] **Returns** Position in the queue or `None` if position is unknown or not applicable. ### refresh Obtain the latest job information from the server. This method may add additional attributes to this job instance, if new information becomes available. **Raises** [**IBMJobApiError**](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") – If an unexpected error occurred when communicating with the server. **Return type** `None` ### result Return the result of the job. Some IBM Quantum job results can only be read once. A second attempt to query the server for the same job will fail, since the job has already been “consumed”. The first call to this method in an `IBMCircuitJob` instance will query the server and consume any available job results. Subsequent calls to that instance’s `result()` will also return the results, since they are cached. However, attempting to retrieve the results again in another instance or session might fail due to the job results having been consumed. When partial=True, this method will attempt to retrieve partial results of failed jobs. In this case, precaution should be taken when accessing individual experiments, as doing so might cause an exception. The `success` attribute of the returned [`Result`](/api/qiskit/qiskit.result.Result ""(in Qiskit v0.46)"") instance can be used to verify whether it contains partial results. For example, if one of the experiments in the job failed, trying to get the counts of the unsuccessful experiment would raise an exception since there are no counts to return: ```python try: counts = result.get_counts(""failed_experiment"") except QiskitError: print(""Experiment failed!"") ``` If the job failed, you can use [`error_message()`](#qiskit_ibm_provider.job.IBMCircuitJob.error_message ""qiskit_ibm_provider.job.IBMCircuitJob.error_message"") to get more information. **Parameters** * **timeout** (`Optional`\[`float`]) – Number of seconds to wait for job. * **refresh** (`bool`) – If `True`, re-query the server for the result. Otherwise return the cached value. **Return type** [`Result`](/api/qiskit/qiskit.result.Result ""(in Qiskit v0.46)"") **Returns** Job result. **Raises** * [**IBMJobInvalidStateError**](qiskit_ibm_provider.job.IBMJobInvalidStateError ""qiskit_ibm_provider.job.IBMJobInvalidStateError"") – If the job was cancelled. * [**IBMJobFailureError**](qiskit_ibm_provider.job.IBMJobFailureError ""qiskit_ibm_provider.job.IBMJobFailureError"") – If the job failed. * [**IBMJobApiError**](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") – If an unexpected error occurred when communicating with the server. ### running Return whether the job is actively running. **Return type** `bool` ### scheduling\_mode Return the scheduling mode the job is in. **Return type** `Optional`\[`str`] **Returns** The scheduling mode the job is in or `None` if the information is not available. ### status Query the server for the latest job status. This method is not designed to be invoked repeatedly in a loop for an extended period of time. Doing so may cause the server to reject your request. Use [`wait_for_final_state()`](#qiskit_ibm_provider.job.IBMCircuitJob.wait_for_final_state ""qiskit_ibm_provider.job.IBMCircuitJob.wait_for_final_state"") if you want to wait for the job to finish. If the job failed, you can use [`error_message()`](#qiskit_ibm_provider.job.IBMCircuitJob.error_message ""qiskit_ibm_provider.job.IBMCircuitJob.error_message"") to get more information. **Return type** [`JobStatus`](/api/qiskit/qiskit.providers.JobStatus ""(in Qiskit v0.46)"") **Returns** The status of the job. **Raises** [**IBMJobApiError**](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") – If an unexpected error occurred when communicating with the server. ### submit Unsupported method. This method is not supported, please use `run()` to submit a job. **Raises** **NotImplementedError** – Upon invocation. **Return type** `None` ### tags Return the tags assigned to this job. **Return type** `List`\[`str`] **Returns** Tags assigned to this job. ### time\_per\_step Return the date and time information on each step of the job processing. The output dictionary contains the date and time information on each step of the job processing, in local time. The keys of the dictionary are the names of the steps, and the values are the date and time data, as a datetime object with local timezone info. For example: ```python {'CREATING': datetime(2020, 2, 13, 15, 19, 25, 717000, tzinfo=tzlocal(), 'CREATED': datetime(2020, 2, 13, 15, 19, 26, 467000, tzinfo=tzlocal(), 'VALIDATING': datetime(2020, 2, 13, 15, 19, 26, 527000, tzinfo=tzlocal()} ``` **Return type** `Optional`\[`Dict`] **Returns** Date and time information on job processing steps, in local time, or `None` if the information is not yet available. ### update\_name Update the name associated with this job. **Parameters** **name** (`str`) – The new name for this job. **Return type** `str` **Returns** The new name associated with this job. ### update\_tags Update the tags associated with this job. **Parameters** **new\_tags** (`List`\[`str`]) – New tags to assign to the job. **Return type** `List`\[`str`] **Returns** The new tags associated with this job. **Raises** * [**IBMJobApiError**](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") – If an unexpected error occurred when communicating with the server or updating the job tags. * [**IBMJobInvalidStateError**](qiskit_ibm_provider.job.IBMJobInvalidStateError ""qiskit_ibm_provider.job.IBMJobInvalidStateError"") – If none of the input parameters are specified or if any of the input parameters are invalid. ### wait\_for\_final\_state **Use the websocket server to wait for the final the state of a job. The server** will remain open if the job is still running and the connection will be terminated once the job completes. Then update and return the status of the job. **Parameters** **timeout** (`Optional`\[`float`]) – Seconds to wait for the job. If `None`, wait indefinitely. **Raises** [**IBMJobTimeoutError**](qiskit_ibm_provider.job.IBMJobTimeoutError ""qiskit_ibm_provider.job.IBMJobTimeoutError"") – If the job does not complete within given timeout. **Return type** `None` ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.job.IBMCircuitJob.mdx "--- title: IBMCompositeJob description: API reference for qiskit_ibm_provider.job.IBMCompositeJob in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.job.IBMCompositeJob --- # IBMCompositeJob Representation of a set of jobs that execute on an IBM Quantum backend. An `IBMCompositeJob` instance is returned when you call `IBMBackend.run()` to submit a list of circuits whose length exceeds the maximum allowed by the backend or by the `max_circuits_per_job` parameter. This `IBMCompositeJob` instance manages all the sub-jobs for you and can be used like a traditional job instance. For example, you can continue to use methods like [`status()`](#qiskit_ibm_provider.job.IBMCompositeJob.status ""qiskit_ibm_provider.job.IBMCompositeJob.status"") and [`result()`](#qiskit_ibm_provider.job.IBMCompositeJob.result ""qiskit_ibm_provider.job.IBMCompositeJob.result"") to get the job status and result, respectively. You can also retrieve a previously executed `IBMCompositeJob` using the `job()` and [`jobs()`](qiskit_ibm_provider.IBMBackendService#jobs ""qiskit_ibm_provider.IBMBackendService.jobs"") methods, like you would with traditional jobs. `IBMCompositeJob` also allows you to re-run failed jobs, using the [`rerun_failed()`](#qiskit_ibm_provider.job.IBMCompositeJob.rerun_failed ""qiskit_ibm_provider.job.IBMCompositeJob.rerun_failed"") method. This method will re-submit all failed or cancelled sub-jobs. Any circuits that failed to be submitted (e.g. due to server error) will only be re-submitted if the circuits are known. That is, if this `IBMCompositeJob` was returned by [`qiskit_ibm_provider.IBMBackend.run()`](qiskit_ibm_provider.IBMBackend#run ""qiskit_ibm_provider.IBMBackend.run"") and not retrieved from the server. Some of the methods in this class are blocking, which means control may not be returned immediately. [`result()`](#qiskit_ibm_provider.job.IBMCompositeJob.result ""qiskit_ibm_provider.job.IBMCompositeJob.result"") is an example of a blocking method, and control will return only after all sub-jobs finish. `IBMCompositeJob` uses job tags to identify sub-jobs. It is therefore important to preserve these tags. All tags used internally by `IBMCompositeJob` start with `ibm_composite_job_`. IBMCompositeJob constructor. **Parameters** * **backend** ([`IBMBackend`](qiskit_ibm_provider.IBMBackend ""qiskit_ibm_provider.ibm_backend.IBMBackend"")) – The backend instance used to run this job. * **api\_client** (`AccountClient`) – Object for connecting to the server. * **job\_id** (`Optional`\[`str`]) – Job ID. * **creation\_date** (`Optional`\[`datetime`]) – Job creation date. * **jobs** (`Optional`\[`List`\[[`IBMCircuitJob`](qiskit_ibm_provider.job.IBMCircuitJob ""qiskit_ibm_provider.job.ibm_circuit_job.IBMCircuitJob"")]]) – A list of sub-jobs. * **circuits\_list** (`Optional`\[`List`\[`List`\[[`QuantumCircuit`](/api/qiskit/qiskit.circuit.QuantumCircuit ""(in Qiskit v0.46)"")]]]) – Circuits for this job. * **run\_config** (`Optional`\[`Dict`]) – Runtime configuration for this job. * **name** (`Optional`\[`str`]) – Job name. * **tags** (`Optional`\[`List`\[`str`]]) – Job tags. * **client\_version** (`Optional`\[`Dict`]) – Client used for the job. **Raises** [**IBMJobInvalidStateError**](qiskit_ibm_provider.job.IBMJobInvalidStateError ""qiskit_ibm_provider.job.IBMJobInvalidStateError"") – If one or more subjobs is missing. ## Attributes ### client\_version Return version of the client used for this job. **Return type** `Dict`\[`str`, `str`] **Returns** **Client version in dictionary format, where the key is the name** of the client and the value is the version. An empty dictionary is returned if the information is not yet known. ### version ## Methods ### backend Return the backend where this job was executed. **Return type** [`Backend`](/api/qiskit/qiskit.providers.Backend ""(in Qiskit v0.46)"") ### backend\_options Return the backend configuration options used for this job. Options that are not applicable to the job execution are not returned. Some but not all of the options with default values are returned. You can use [`qiskit_ibm_provider.IBMBackend.options`](qiskit_ibm_provider.IBMBackend#options ""qiskit_ibm_provider.IBMBackend.options"") to see all backend options. **Return type** `Dict`\[`str`, `Any`] **Returns** Backend options used for this job. ### block\_for\_submit Block until all sub-jobs are submitted. **Return type** `None` ### cancel Attempt to cancel the job. Depending on the state the job is in, it might be impossible to cancel the job. **Return type** `bool` **Returns** `True` if the job is cancelled, else `False`. **Raises** [**IBMJobApiError**](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") – If an unexpected error occurred when communicating with the server. ### cancelled Return whether the job has been cancelled. **Return type** `bool` ### circuits Return the circuits for this job. **Return type** `List`\[[`QuantumCircuit`](/api/qiskit/qiskit.circuit.QuantumCircuit ""(in Qiskit v0.46)"")] **Returns** The circuits for this job. ### creation\_date Return job creation date, in local time. **Return type** `Optional`\[`datetime`] **Returns** The job creation date as a datetime object, in local time, or `None` if job submission hasn’t finished or failed. ### done Return whether the job has successfully run. **Return type** `bool` ### error\_message Provide details about the reason of failure. This method blocks until the job finishes. **Return type** `Optional`\[`str`] **Returns** An error report if the job failed or `None` otherwise. ### from\_jobs Return an instance of this class. The input job ID is used to query for sub-job information from the server. **Parameters** * **job\_id** (`str`) – Job ID. * **jobs** (`List`\[[`IBMCircuitJob`](qiskit_ibm_provider.job.IBMCircuitJob ""qiskit_ibm_provider.job.ibm_circuit_job.IBMCircuitJob"")]) – A list of circuit jobs that belong to this composite job. * **api\_client** (`AccountClient`) – Client to use to communicate with the server. **Return type** [`IBMCompositeJob`](#qiskit_ibm_provider.job.IBMCompositeJob ""qiskit_ibm_provider.job.ibm_composite_job.IBMCompositeJob"") **Returns** An instance of this class. ### header Return the user header specified for this job. **Return type** `Dict` **Returns** User header specified for this job. An empty dictionary is returned if the header cannot be retrieved. ### in\_final\_state Return whether the job is in a final job state such as `DONE` or `ERROR`. **Return type** `bool` ### job\_id Return a unique id identifying the job. **Return type** `str` ### name Return the name assigned to this job. **Return type** `Optional`\[`str`] **Returns** Job name or `None` if no name was assigned to this job. ### properties Return the backend properties for this job. > **Args:** > > **refresh: If `True`, re-query the server for the backend properties.** > > Otherwise, return a cached version. This method blocks until all sub-jobs are submitted. **Return type** `Union`\[`List`\[[`BackendProperties`](/api/qiskit/qiskit.providers.models.BackendProperties ""(in Qiskit v0.46)"")], [`BackendProperties`](/api/qiskit/qiskit.providers.models.BackendProperties ""(in Qiskit v0.46)""), `None`] **Returns** The backend properties used for this job, or `None` if properties are not available. A list of backend properties is returned if the sub-jobs used different properties. **Raises** [**IBMJobApiError**](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") – If an unexpected error occurred when communicating with the server. ### queue\_info Return queue information for this job. This method returns the queue information of the sub-job that is last in queue. The queue information may include queue position, estimated start and end time, and dynamic priorities for the hub, group, and project. See [`QueueInfo`](qiskit_ibm_provider.job.QueueInfo ""qiskit_ibm_provider.job.QueueInfo"") for more information. The queue information is calculated after the job enters the queue. Therefore, some or all of the information may not be immediately available, and this method may return `None`. **Return type** `Optional`\[[`QueueInfo`](qiskit_ibm_provider.job.QueueInfo ""qiskit_ibm_provider.job.queueinfo.QueueInfo"")] **Returns** A [`QueueInfo`](qiskit_ibm_provider.job.QueueInfo ""qiskit_ibm_provider.job.QueueInfo"") instance that contains queue information for this job, or `None` if queue information is unknown or not applicable. ### queue\_position Return the position of the job in the server queue. This method returns the queue position of the sub-job that is last in queue. The position returned is within the scope of the provider and may differ from the global queue position. **Parameters** **refresh** (`bool`) – If `True`, re-query the server to get the latest value. Otherwise return the cached value. **Return type** `Optional`\[`int`] **Returns** Position in the queue or `None` if position is unknown or not applicable. ### refresh Obtain the latest job information from the server. This method may add additional attributes to this job instance, if new information becomes available. **Raises** [**IBMJobApiError**](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") – If an unexpected error occurred when communicating with the server. **Return type** `None` ### report Return a report on current sub-job statuses. **Parameters** **detailed** (`bool`) – If `True`, return a detailed report. Otherwise return a summary report. **Return type** `str` **Returns** A report on sub-job statuses. ### rerun\_failed Re-submit all failed sub-jobs. All sub-jobs that are in “ERROR” or “CANCELLED” states will be re-submitted. Sub-jobs that failed to be submitted will only be re-submitted if the circuits are known. That is, if this `IBMCompositeJob` was returned by [`qiskit_ibm_provider.IBMBackend.run()`](qiskit_ibm_provider.IBMBackend#run ""qiskit_ibm_provider.IBMBackend.run"") and not retrieved from the server. **Return type** `None` ### result Return the result of the job. This method blocks until all sub-jobs finish. Some IBM Quantum job results can only be read once. A second attempt to query the server for the same job will fail, since the job has already been “consumed”. The first call to this method in an `IBMCompositeJob` instance will query the server and consume any available job results. Subsequent calls to that instance’s `result()` will also return the results, since they are cached. However, attempting to retrieve the results again in another instance or session might fail due to the job results having been consumed. When partial=True, this method will attempt to retrieve partial results of failed jobs. In this case, precaution should be taken when accessing individual experiments, as doing so might cause an exception. The `success` attribute of the returned [`Result`](/api/qiskit/qiskit.result.Result ""(in Qiskit v0.46)"") instance can be used to verify whether it contains partial results. For example, if one of the circuits in the job failed, trying to get the counts of the unsuccessful circuit would raise an exception since there are no counts to return: ```python try: counts = result.get_counts(""failed_circuit"") except QiskitError: print(""Circuit execution failed!"") ``` If the job failed, you can use [`error_message()`](#qiskit_ibm_provider.job.IBMCompositeJob.error_message ""qiskit_ibm_provider.job.IBMCompositeJob.error_message"") to get more information. **Parameters** * **timeout** (`Optional`\[`float`]) – Number of seconds to wait for job. * **wait** (`float`) – Time in seconds between queries. * **partial** (`bool`) – If `True`, return partial results if possible. Partial results refer to experiments within a sub-job, not individual sub-jobs. That is, this method will still block until all sub-jobs finish even if partial is set to `True`. * **refresh** (`bool`) – If `True`, re-query the server for the result. Otherwise return the cached value. **Return type** [`Result`](/api/qiskit/qiskit.result.Result ""(in Qiskit v0.46)"") **Returns** Job result. **Raises** * [**IBMJobInvalidStateError**](qiskit_ibm_provider.job.IBMJobInvalidStateError ""qiskit_ibm_provider.job.IBMJobInvalidStateError"") – If the job was cancelled. * [**IBMJobFailureError**](qiskit_ibm_provider.job.IBMJobFailureError ""qiskit_ibm_provider.job.IBMJobFailureError"") – If the job failed. * [**IBMJobApiError**](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") – If an unexpected error occurred when communicating with the server. ### running Return whether the job is actively running. **Return type** `bool` ### scheduling\_mode Return the scheduling mode the job is in. The scheduling mode indicates how the job is scheduled to run. For example, `fairshare` indicates the job is scheduled using a fairshare algorithm. `fairshare` is returned if any of the sub-jobs has scheduling mode of `fairshare`. This information is only available if the job status is `RUNNING` or `DONE`. **Return type** `Optional`\[`str`] **Returns** The scheduling mode the job is in or `None` if the information is not available. ### status Query the server for the latest job status. This method is not designed to be invoked repeatedly in a loop for an extended period of time. Doing so may cause the server to reject your request. Use [`wait_for_final_state()`](#qiskit_ibm_provider.job.IBMCompositeJob.wait_for_final_state ""qiskit_ibm_provider.job.IBMCompositeJob.wait_for_final_state"") if you want to wait for the job to finish. If the job failed, you can use [`error_message()`](#qiskit_ibm_provider.job.IBMCompositeJob.error_message ""qiskit_ibm_provider.job.IBMCompositeJob.error_message"") to get more information. Since this job contains multiple sub-jobs, the returned status is mapped in the following order: > * INITIALIZING - if any sub-job is being initialized. > * VALIDATING - if any sub-job is being validated. > * QUEUED - if any sub-job is queued. > * RUNNING - if any sub-job is still running. > * ERROR - if any sub-job incurred an error. > * CANCELLED - if any sub-job is cancelled. > * DONE - if all sub-jobs finished. **Return type** [`JobStatus`](/api/qiskit/qiskit.providers.JobStatus ""(in Qiskit v0.46)"") **Returns** The status of the job. **Raises** [**IBMJobApiError**](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") – If an unexpected error occurred when communicating with the server. ### sub\_job Retrieve the job used to submit the specified circuit. **Parameters** **circuit\_index** (`int`) – Index of the circuit whose job is to be returned. **Return type** `Optional`\[[`IBMCircuitJob`](qiskit_ibm_provider.job.IBMCircuitJob ""qiskit_ibm_provider.job.ibm_circuit_job.IBMCircuitJob"")] **Returns** The Job submitted for the circuit, or `None` if the job has not been submitted or the submit failed. **Raises** [**IBMJobInvalidStateError**](qiskit_ibm_provider.job.IBMJobInvalidStateError ""qiskit_ibm_provider.job.IBMJobInvalidStateError"") – If the circuit index is out of range. ### sub\_jobs Return all submitted sub-jobs. **Parameters** **block\_for\_submit** (`bool`) – `True` if this method should block until all sub-jobs are submitted. `False` if the method should return immediately with submitted sub-jobs, if any. **Return type** `List`\[[`IBMCircuitJob`](qiskit_ibm_provider.job.IBMCircuitJob ""qiskit_ibm_provider.job.ibm_circuit_job.IBMCircuitJob"")] **Returns** All submitted sub-jobs. ### submit Unsupported method. This method is not supported, please use `run()` to submit a job. **Raises** **NotImplementedError** – Upon invocation. **Return type** `None` ### tags Return the tags assigned to this job. **Return type** `List`\[`str`] **Returns** Tags assigned to this job. ### time\_per\_step Return the date and time information on each step of the job processing. The output dictionary contains the date and time information on each step of the job processing, in local time. The keys of the dictionary are the names of the steps, and the values are the date and time data, as a datetime object with local timezone info. For example: ```python {'CREATING': datetime(2020, 2, 13, 15, 19, 25, 717000, tzinfo=tzlocal(), 'CREATED': datetime(2020, 2, 13, 15, 19, 26, 467000, tzinfo=tzlocal(), 'VALIDATING': datetime(2020, 2, 13, 15, 19, 26, 527000, tzinfo=tzlocal()} ``` **Return type** `Optional`\[`Dict`] **Returns** Date and time information on job processing steps, in local time, or `None` if the information is not yet available. ### update\_name Update the name associated with this job. This method blocks until all sub-jobs are submitted. **Parameters** **name** (`str`) – The new name for this job. **Return type** `str` **Returns** The new name associated with this job. **Raises** * [**IBMJobApiError**](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") – If an unexpected error occurred when communicating with the server or updating the job name. * [**IBMJobInvalidStateError**](qiskit_ibm_provider.job.IBMJobInvalidStateError ""qiskit_ibm_provider.job.IBMJobInvalidStateError"") – If the input job name is not a string. ### update\_tags Update the tags associated with this job. This method blocks until all sub-jobs are submitted. **Parameters** **new\_tags** (`List`\[`str`]) – New tags to assign to the job. **Return type** `List`\[`str`] **Returns** The new tags associated with this job. **Raises** * [**IBMJobApiError**](qiskit_ibm_provider.job.IBMJobApiError ""qiskit_ibm_provider.job.IBMJobApiError"") – If an unexpected error occurred when communicating with the server or updating the job tags. * [**IBMJobInvalidStateError**](qiskit_ibm_provider.job.IBMJobInvalidStateError ""qiskit_ibm_provider.job.IBMJobInvalidStateError"") – If none of the input parameters are specified or if any of the input parameters are invalid. ### wait\_for\_final\_state Wait until the job progresses to a final state such as `DONE` or `ERROR`. **Parameters** * **timeout** (`Optional`\[`float`]) – Seconds to wait for the job. If `None`, wait indefinitely. * **wait** (`Optional`\[`float`]) – Seconds to wait between invoking the callback function. If `None`, the callback function is invoked only if job status or queue position has changed. * **callback** (`Optional`\[`Callable`]) – Callback function invoked after each querying iteration. The following positional arguments are provided to the callback function: > * job\_id: Job ID > * job\_status: Status of the job from the last query. > * job: This `IBMCompositeJob` instance. In addition, the following keyword arguments are also provided: > * queue\_info: A [`QueueInfo`](qiskit_ibm_provider.job.QueueInfo ""qiskit_ibm_provider.job.QueueInfo"") instance with job queue information, or `None` if queue information is unknown or not applicable. You can use the `to_dict()` method to convert the [`QueueInfo`](qiskit_ibm_provider.job.QueueInfo ""qiskit_ibm_provider.job.QueueInfo"") instance to a dictionary, if desired. **Raises** [**IBMJobTimeoutError**](qiskit_ibm_provider.job.IBMJobTimeoutError ""qiskit_ibm_provider.job.IBMJobTimeoutError"") – if the job does not reach a final state before the specified timeout. **Return type** `None` ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.job.IBMCompositeJob.mdx "--- title: IBMJobApiError description: API reference for qiskit_ibm_provider.job.IBMJobApiError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.job.IBMJobApiError --- # IBMJobApiError Errors that occur unexpectedly when querying the server. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.job.IBMJobApiError.mdx "--- title: IBMJobError description: API reference for qiskit_ibm_provider.job.IBMJobError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.job.IBMJobError --- # IBMJobError Base class for errors raised by the job modules. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.job.IBMJobError.mdx "--- title: IBMJobFailureError description: API reference for qiskit_ibm_provider.job.IBMJobFailureError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.job.IBMJobFailureError --- # IBMJobFailureError Errors raised when a job failed. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.job.IBMJobFailureError.mdx "--- title: IBMJobInvalidStateError description: API reference for qiskit_ibm_provider.job.IBMJobInvalidStateError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.job.IBMJobInvalidStateError --- # IBMJobInvalidStateError Errors raised when a job is not in a valid state for the operation. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.job.IBMJobInvalidStateError.mdx "--- title: IBMJobTimeoutError description: API reference for qiskit_ibm_provider.job.IBMJobTimeoutError in_page_toc_min_heading_level: 1 python_api_type: exception python_api_name: qiskit_ibm_provider.job.IBMJobTimeoutError --- # IBMJobTimeoutError Errors raised when a job operation times out. Set the error message. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.job.IBMJobTimeoutError.mdx "--- title: job_monitor description: API reference for qiskit_ibm_provider.job.job_monitor in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit_ibm_provider.job.job_monitor --- # job\_monitor )""> Monitor the status of an `IBMJob` instance. **Parameters** * **job** (`IBMJob`) – Job to monitor. * **interval** (`Optional`\[`float`]) – Time interval between status queries. * **output** (`TextIO`) – The file like object to write status messages to. By default this is sys.stdout. **Return type** `None` ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.job.job_monitor.mdx "--- title: QueueInfo description: API reference for qiskit_ibm_provider.job.QueueInfo in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.job.QueueInfo --- # QueueInfo Queue information for a job. QueueInfo constructor. **Parameters** * **position** – Position in the queue. * **status** (`Optional`\[`str`]) – Job status. * **estimated\_start\_time** (`Union`\[`str`, `datetime`, `None`]) – Estimated start time for the job, in UTC. * **estimated\_complete\_time** – Estimated complete time for the job, in UTC. * **hub\_priority** (`Optional`\[`float`]) – Dynamic priority for the hub. * **group\_priority** (`Optional`\[`float`]) – Dynamic priority for the group. * **project\_priority** (`Optional`\[`float`]) – Dynamic priority for the project. * **job\_id** (`Optional`\[`str`]) – Job ID. * **kwargs** (`Any`) – Additional attributes. ## Attributes ### estimated\_complete\_time Return estimated complete time in local time. **Return type** `Optional`\[`datetime`] ### estimated\_start\_time Return estimated start time in local time. **Return type** `Optional`\[`datetime`] ## Methods ### format Build a user-friendly report for the job queue information. **Return type** `str` **Returns** The job queue information report. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.job.QueueInfo.mdx "--- title: least_busy description: API reference for qiskit_ibm_provider.least_busy in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit_ibm_provider.least_busy --- # least\_busy Return the least busy backend from a list. Return the least busy available backend for those that have a `pending_jobs` in their `status`. Note that local backends may not have this attribute. **Parameters** **backends** (`List`\[[`Backend`](/api/qiskit/qiskit.providers.Backend ""(in Qiskit v0.46)"")]) – The backends to choose from. **Return type** [`Backend`](/api/qiskit/qiskit.providers.Backend ""(in Qiskit v0.46)"") **Returns** The backend with the fewest number of pending jobs. **Raises** [**IBMError**](qiskit_ibm_provider.IBMError ""qiskit_ibm_provider.IBMError"") – If the backends list is empty, or if none of the backends is available, or if a backend in the list does not have the `pending_jobs` attribute in its status. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.least_busy.mdx "--- title: Session description: API reference for qiskit_ibm_provider.Session in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.Session --- # Session Class for creating a flexible Qiskit Runtime session. A Qiskit Runtime `session` allows you to group a collection of iterative calls to the quantum computer. A session is started when the first job within the session is started. Subsequent jobs within the session are prioritized by the scheduler. Data used within a session, such as transpiled circuits, is also cached to avoid unnecessary overhead. You can open a Qiskit Runtime session using this `Session` class and submit one or more jobs. **For example::** from qiskit\_ibm\_provider import IBMProvider \# Bell Circuit qr = QuantumRegister(2, name=”qr”) cr = ClassicalRegister(2, name=”cr”) qc = QuantumCircuit(qr, cr, name=”bell”) qc.h(qr\[0]) qc.cx(qr\[0], qr\[1]) qc.measure(qr, cr) backend = IBMProvider().get\_backend(“ibmq\_qasm\_simulator”) backend.open\_session() job = backend.run(qc) print(f”Job ID: \{job.job\_id()}”) print(f”Result: \{job.result()}”) # Close the session only if all jobs are finished and # you don’t need to run more in the session. backend.cancel\_session() Session can also be used as a context manager: ```python with backend.open_session() as session: job = backend.run(qc) assert job.job_id() == session.session_id ``` Session constructor. **Parameters** **max\_time** (`Union`\[`int`, `str`, `None`]) – (EXPERIMENTAL setting, can break between releases without warning) Maximum amount of time, a runtime session can be open before being forcibly closed. Can be specified as seconds (int) or a string like “2h 30m 40s”. This value must be in between 300 seconds and the [system imposed maximum](https://qiskit.org/documentation/partners/qiskit_ibm_runtime/faqs/max_execution_time.html). **Raises** **ValueError** – If an input value is invalid. ## Attributes ### active Return the status of the session. **Return type** `bool` **Returns** True if the session is active, False otherwise. ### session\_id Return the session ID. **Return type** `str` **Returns** Session ID. None until a job runs in the session. ## Methods ### cancel Set the session.\_active status to False **Return type** `None` ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.Session.mdx "--- title: basis description: API reference for qiskit_ibm_provider.transpiler.passes.basis in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_provider.transpiler.passes.basis --- # basis ## Basis `qiskit_ibm_provider.transpiler.passes.basis` Passes to layout circuits to IBM backend’s instruction sets. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.transpiler.passes.basis.mdx "--- title: passes description: API reference for qiskit_ibm_provider.transpiler.passes in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_provider.transpiler.passes --- # passes ## Transpiler Passes `qiskit_ibm_provider.transpiler.passes` A collection of transpiler passes for IBM backends. | | | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | [`basis`](qiskit_ibm_provider.transpiler.passes.basis#module-qiskit_ibm_provider.transpiler.passes.basis ""qiskit_ibm_provider.transpiler.passes.basis"") | Basis (qiskit\_ibm\_provider.transpiler.passes.basis) | | [`scheduling`](qiskit_ibm_provider.transpiler.passes.scheduling#module-qiskit_ibm_provider.transpiler.passes.scheduling ""qiskit_ibm_provider.transpiler.passes.scheduling"") | Scheduling (qiskit\_ibm\_provider.transpiler.passes.scheduling) | ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.transpiler.passes.mdx "--- title: ALAPScheduleAnalysis description: API reference for qiskit_ibm_provider.transpiler.passes.scheduling.ALAPScheduleAnalysis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.transpiler.passes.scheduling.ALAPScheduleAnalysis --- # ALAPScheduleAnalysis Dynamic circuits as-late-as-possible (ALAP) scheduling analysis pass. This is a scheduler designed to work for the unique scheduling constraints of the dynamic circuits backends due to the limitations imposed by hardware. This is expected to evolve over time as the dynamic circuit backends also change. In its current form this is similar to Qiskit’s ALAP scheduler in which instructions start as late as possible. The primary differences are that: * **Resets and control-flow currently trigger the end of a “quantum block”. The period between the end** of the block and the next is *nondeterministic* ie., we do not know when the next block will begin (as we could be evaluating a classical function of nondeterministic length) and therefore the next block starts at a *relative* t=0. * During a measurement it is possible to apply gates in parallel on disjoint qubits. * Measurements and resets on disjoint qubits happen simultaneously and are part of the same block. Scheduler for dynamic circuit backends. **Parameters** **durations** ([`InstructionDurations`](/api/qiskit/qiskit.transpiler.InstructionDurations ""(in Qiskit v0.46)"")) – Durations of instructions to be used in scheduling. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### \_\_call\_\_ Runs the pass on circuit. **Parameters** * **circuit** (*QuantumCircuit*) – The dag on which the pass is run. * **property\_set** (*PropertySet | dict | None*) – Input/output property set. An analysis pass might change the property set in-place. **Return type** QuantumCircuit **Returns** If on transformation pass, the resulting QuantumCircuit. If analysis pass, the input circuit. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** (`Any`) – Qiskit IR to optimize. * **state** ([`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")) – State associated with workflow execution by the pass manager itself. * **callback** (`Optional`\[`Callable`]) – A callback function which is caller per execution of optimization task. **Return type** `tuple`\[`Any`, [`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")] **Returns** Optimized Qiskit IR and state of the workflow. ### name Name of the pass. **Return type** `str` ### run Run the ASAPSchedule pass on dag. :type dag: [`DAGCircuit`](/api/qiskit/qiskit.dagcircuit.DAGCircuit ""(in Qiskit v0.46)"") :param dag: DAG to schedule. :type dag: DAGCircuit **Raises** * **TranspilerError** – if the circuit is not mapped on physical qubits. * **TranspilerError** – if conditional bit is added to non-supported instruction. **Return type** `None` **Returns** The scheduled DAGCircuit. ### update\_status Update workflow status. **Parameters** * **state** ([`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")) – Pass manager state to update. * **run\_state** (`RunState`) – Completion status of current task. **Return type** [`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"") **Returns** Updated pass manager state. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.transpiler.passes.scheduling.ALAPScheduleAnalysis.mdx "--- title: ASAPScheduleAnalysis description: API reference for qiskit_ibm_provider.transpiler.passes.scheduling.ASAPScheduleAnalysis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.transpiler.passes.scheduling.ASAPScheduleAnalysis --- # ASAPScheduleAnalysis Dynamic circuits as-soon-as-possible (ASAP) scheduling analysis pass. This is a scheduler designed to work for the unique scheduling constraints of the dynamic circuits backends due to the limitations imposed by hardware. This is expected to evolve over time as the dynamic circuit backends also change. In its current form this is similar to Qiskit’s ASAP scheduler in which instructions start as early as possible. The primary differences are that: * **Resets and control-flow currently trigger the end of a “quantum block”. The period between the end** of the block and the next is *nondeterministic* ie., we do not know when the next block will begin (as we could be evaluating a classical function of nondeterministic length) and therefore the next block starts at a *relative* t=0. * During a measurement it is possible to apply gates in parallel on disjoint qubits. * Measurements and resets on disjoint qubits happen simultaneously and are part of the same block. Scheduler for dynamic circuit backends. **Parameters** **durations** ([`InstructionDurations`](/api/qiskit/qiskit.transpiler.InstructionDurations ""(in Qiskit v0.46)"")) – Durations of instructions to be used in scheduling. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### \_\_call\_\_ Runs the pass on circuit. **Parameters** * **circuit** (*QuantumCircuit*) – The dag on which the pass is run. * **property\_set** (*PropertySet | dict | None*) – Input/output property set. An analysis pass might change the property set in-place. **Return type** QuantumCircuit **Returns** If on transformation pass, the resulting QuantumCircuit. If analysis pass, the input circuit. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** (`Any`) – Qiskit IR to optimize. * **state** ([`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")) – State associated with workflow execution by the pass manager itself. * **callback** (`Optional`\[`Callable`]) – A callback function which is caller per execution of optimization task. **Return type** `tuple`\[`Any`, [`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")] **Returns** Optimized Qiskit IR and state of the workflow. ### name Name of the pass. **Return type** `str` ### run Run the ALAPSchedule pass on dag. :type dag: [`DAGCircuit`](/api/qiskit/qiskit.dagcircuit.DAGCircuit ""(in Qiskit v0.46)"") :param dag: DAG to schedule. :type dag: DAGCircuit **Raises** * **TranspilerError** – if the circuit is not mapped on physical qubits. * **TranspilerError** – if conditional bit is added to non-supported instruction. **Return type** [`DAGCircuit`](/api/qiskit/qiskit.dagcircuit.DAGCircuit ""(in Qiskit v0.46)"") **Returns** The scheduled DAGCircuit. ### update\_status Update workflow status. **Parameters** * **state** ([`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")) – Pass manager state to update. * **run\_state** (`RunState`) – Completion status of current task. **Return type** [`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"") **Returns** Updated pass manager state. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.transpiler.passes.scheduling.ASAPScheduleAnalysis.mdx "--- title: BlockBasePadder description: API reference for qiskit_ibm_provider.transpiler.passes.scheduling.BlockBasePadder in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.transpiler.passes.scheduling.BlockBasePadder --- # BlockBasePadder The base class of padding pass. This pass requires one of scheduling passes to be executed before itself. Since there are multiple scheduling strategies, the selection of scheduling pass is left in the hands of the pass manager designer. Once a scheduling analysis pass is run, `node_start_time` is generated in the `property_set`. This information is represented by a python dictionary of the expected instruction execution times keyed on the node instances. The padding pass expects all `DAGOpNode` in the circuit to be scheduled. This base class doesn’t define any sequence to interleave, but it manages the location where the sequence is inserted, and provides a set of information necessary to construct the proper sequence. Thus, a subclass of this pass just needs to implement `_pad()` method, in which the subclass constructs a circuit block to insert. This mechanism removes lots of boilerplate logic to manage whole DAG circuits. Note that padding pass subclasses should define interleaving sequences satisfying: > * Interleaved sequence does not change start time of other nodes > * Interleaved sequence should have total duration of the provided `time_interval`. Any manipulation violating these constraints may prevent this base pass from correctly tracking the start time of each instruction, which may result in violation of hardware alignment constraints. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### \_\_call\_\_ Runs the pass on circuit. **Parameters** * **circuit** (*QuantumCircuit*) – The dag on which the pass is run. * **property\_set** (*PropertySet | dict | None*) – Input/output property set. An analysis pass might change the property set in-place. **Return type** QuantumCircuit **Returns** If on transformation pass, the resulting QuantumCircuit. If analysis pass, the input circuit. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** (`Any`) – Qiskit IR to optimize. * **state** ([`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")) – State associated with workflow execution by the pass manager itself. * **callback** (`Optional`\[`Callable`]) – A callback function which is caller per execution of optimization task. **Return type** `tuple`\[`Any`, [`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")] **Returns** Optimized Qiskit IR and state of the workflow. ### name Name of the pass. **Return type** `str` ### run Run the padding pass on `dag`. **Parameters** **dag** ([`DAGCircuit`](/api/qiskit/qiskit.dagcircuit.DAGCircuit ""(in Qiskit v0.46)"")) – DAG to be checked. **Returns** DAG with idle time filled with instructions. **Return type** DAGCircuit **Raises** **TranspilerError** – When a particular node is not scheduled, likely some transform pass is inserted before this node is called. ### update\_status Update workflow status. **Parameters** * **state** ([`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")) – Pass manager state to update. * **run\_state** (`RunState`) – Completion status of current task. **Return type** [`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"") **Returns** Updated pass manager state. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.transpiler.passes.scheduling.BlockBasePadder.mdx "--- title: DynamicCircuitInstructionDurations description: API reference for qiskit_ibm_provider.transpiler.passes.scheduling.DynamicCircuitInstructionDurations in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.transpiler.passes.scheduling.DynamicCircuitInstructionDurations --- # DynamicCircuitInstructionDurations For dynamic circuits the IBM Qiskit backend currently reports instruction durations that differ compared with those required for the legacy Qobj-based path. For now we use this class to report updated InstructionDurations. TODO: This would be mitigated by a specialized Backend/Target for dynamic circuit backends. Dynamic circuit instruction durations. ## Attributes ### MEASURE\_PATCH\_CYCLES ### MEASURE\_PATCH\_ODD\_OFFSET ## Methods ### from\_backend Construct a `DynamicInstructionDurations` object from the backend. **Parameters** **backend** ([`Backend`](/api/qiskit/qiskit.providers.Backend ""(in Qiskit v0.46)"")) – backend from which durations (gate lengths) and dt are extracted. **Returns** The InstructionDurations constructed from backend. **Return type** DynamicInstructionDurations ### from\_target Construct a `DynamicInstructionDurations` object from the target. **Parameters** **target** ([`Target`](/api/qiskit/qiskit.transpiler.Target ""(in Qiskit v0.46)"")) – target from which durations (gate lengths) and dt are extracted. **Returns** The InstructionDurations constructed from backend. **Return type** DynamicInstructionDurations ### get Get the duration of the instruction with the name, qubits, and parameters. Some instructions may have a parameter dependent duration. **Parameters** * **inst** (*str |* [*qiskit.circuit.Instruction*](/api/qiskit/qiskit.circuit.Instruction ""(in Qiskit v0.46)"")) – An instruction or its name to be queried. * **qubits** (*int | list\[int]*) – Qubit indices that the instruction acts on. * **unit** (*str*) – The unit of duration to be returned. It must be ‘s’ or ‘dt’. * **parameters** (*list\[float] | None*) – The value of the parameters of the desired instruction. **Returns** The duration of the instruction on the qubits. **Return type** float|int **Raises** **TranspilerError** – No duration is defined for the instruction. ### units\_used Get the set of all units used in this instruction durations. **Return type** `set`\[`str`] **Returns** Set of units used in this instruction durations. ### update Update self with inst\_durations (inst\_durations overwrite self). Overrides the default durations for certain hardcoded instructions. **Parameters** * **inst\_durations** (`Union`\[`List`\[`Tuple`\[`str`, `Optional`\[`Iterable`\[`int`]], `float`, `Optional`\[`Iterable`\[`float`]], `str`]], `List`\[`Tuple`\[`str`, `Optional`\[`Iterable`\[`int`]], `float`, `Optional`\[`Iterable`\[`float`]]]], `List`\[`Tuple`\[`str`, `Optional`\[`Iterable`\[`int`]], `float`, `str`]], `List`\[`Tuple`\[`str`, `Optional`\[`Iterable`\[`int`]], `float`]], [`InstructionDurations`](/api/qiskit/qiskit.transpiler.InstructionDurations ""(in Qiskit v0.46)""), `None`]) – Instruction durations to be merged into self (overwriting self). * **dt** (`Optional`\[`float`]) – Sampling duration in seconds of the target backend. **Returns** The updated InstructionDurations. **Return type** InstructionDurations **Raises** **TranspilerError** – If the format of instruction\_durations is invalid. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.transpiler.passes.scheduling.DynamicCircuitInstructionDurations.mdx "--- title: scheduling description: API reference for qiskit_ibm_provider.transpiler.passes.scheduling in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_provider.transpiler.passes.scheduling --- # scheduling ## Scheduling `qiskit_ibm_provider.transpiler.passes.scheduling` A collection of scheduling passes for working with IBM Quantum’s next-generation backends that support advanced “dynamic circuit” capabilities. Ie., circuits with support for classical control-flow/feedback based off of measurement results. You should not mix these scheduling passes with Qiskit’s builtin scheduling passes as they will negatively interact with the scheduling routines for dynamic circuits. This includes setting `scheduling_method` in [`transpile()`](/api/qiskit/compiler#qiskit.compiler.transpile ""(in Qiskit v0.46)"") or [`generate_preset_pass_manager()`](/api/qiskit/transpiler_preset#qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager ""(in Qiskit v0.46)""). Below we demonstrate how to schedule and pad a teleportation circuit with delays for a dynamic circuit backend’s execution model: ```python from qiskit.circuit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.transpiler.passmanager import PassManager from qiskit_ibm_provider.transpiler.passes.scheduling import DynamicCircuitInstructionDurations from qiskit_ibm_provider.transpiler.passes.scheduling import ALAPScheduleAnalysis from qiskit_ibm_provider.transpiler.passes.scheduling import PadDelay try: from qiskit.providers.fake_provider import Fake7QPulseV1 except ImportError: from qiskit.providers.fake_provider import FakeJakarta as Fake7QPulseV1 backend = Fake7QPulseV1() # Temporary workaround for mock backends. For real backends this is not required. backend.configuration().basis_gates.append(""if_else"") # Use this duration class to get appropriate durations for dynamic # circuit backend scheduling durations = DynamicCircuitInstructionDurations.from_backend(backend) # Generate the main Qiskit transpile passes. pm = generate_preset_pass_manager(optimization_level=1, backend=backend) # Configure the as-late-as-possible scheduling pass pm.scheduling = PassManager([ALAPScheduleAnalysis(durations), PadDelay()]) qr = QuantumRegister(3) crz = ClassicalRegister(1, name=""crz"") crx = ClassicalRegister(1, name=""crx"") result = ClassicalRegister(1, name=""result"") teleport = QuantumCircuit(qr, crz, crx, result, name=""Teleport"") teleport.h(qr[1]) teleport.cx(qr[1], qr[2]) teleport.cx(qr[0], qr[1]) teleport.h(qr[0]) teleport.measure(qr[0], crz) teleport.measure(qr[1], crx) with teleport.if_test((crz, 1)): teleport.z(qr[2]) with teleport.if_test((crx, 1)): teleport.x(qr[2]) teleport.measure(qr[2], result) # Transpile. scheduled_teleport = pm.run(teleport) scheduled_teleport.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_1\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_1_0.png) Instead of padding with delays we may also insert a dynamical decoupling sequence using the [`PadDynamicalDecoupling`](qiskit_ibm_provider.transpiler.passes.scheduling.PadDynamicalDecoupling ""qiskit_ibm_provider.transpiler.passes.scheduling.PadDynamicalDecoupling"") pass as shown below: ```python from qiskit.circuit.library import XGate from qiskit_ibm_provider.transpiler.passes.scheduling import PadDynamicalDecoupling dd_sequence = [XGate(), XGate()] pm = generate_preset_pass_manager(optimization_level=1, backend=backend) pm.scheduling = PassManager( [ ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence), ] ) dd_teleport = pm.run(teleport) dd_teleport.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_2\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_2_0.png) When compiling a circuit with Qiskit, it is more efficient and more robust to perform all the transformations in a single transpilation. This has been done above by extending Qiskit’s preset pass managers. For example, Qiskit’s [`transpile()`](/api/qiskit/compiler#qiskit.compiler.transpile ""(in Qiskit v0.46)"") function internally builds its pass set by using [`generate_preset_pass_manager()`](/api/qiskit/transpiler_preset#qiskit.transpiler.preset_passmanagers.generate_preset_pass_manager ""(in Qiskit v0.46)""). This returns instances of [`StagedPassManager`](/api/qiskit/qiskit.transpiler.StagedPassManager ""(in Qiskit v0.46)""), which can be extended. ### Scheduling old format `c_if` conditioned gates Scheduling with old format `c_if` conditioned gates is not supported. ```python qc_c_if = QuantumCircuit(1, 1) qc_c_if.x(0).c_if(0, 1) qc_c_if.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_3\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_3_0.png) The [`IBMBackend`](qiskit_ibm_provider.IBMBackend ""qiskit_ibm_provider.IBMBackend"") configures a translation plugin `IBMTranslationPlugin` to automatically apply transformations and optimizations for IBM hardware backends when invoking [`transpile()`](/api/qiskit/compiler#qiskit.compiler.transpile ""(in Qiskit v0.46)""). This will automatically convert all old style `c_if` conditioned gates to new-style control-flow. We may then schedule the transpiled circuit without further modification. ```python # Temporary workaround for mock backends. For real backends this is not required. backend.get_translation_stage_plugin = lambda: ""ibm_dynamic_circuits"" pm = generate_preset_pass_manager(optimization_level=1, backend=backend) pm.scheduling = PassManager( [ ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence), ] ) qc_if_dd = pm.run(qc_c_if, backend) qc_if_dd.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_4\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_4_0.png) If you are not using the transpiler plugin stages to work around this please manually run the pass [`qiskit.transpiler.passes.ConvertConditionsToIfOps`](/api/qiskit/qiskit.transpiler.passes.ConvertConditionsToIfOps ""(in Qiskit v0.46)"") prior to your scheduling pass. ```python from qiskit.transpiler.passes import ConvertConditionsToIfOps pm = generate_preset_pass_manager(optimization_level=1, backend=backend) pm.scheduling = PassManager( [ ConvertConditionsToIfOps(), ALAPScheduleAnalysis(durations), PadDelay(), ] ) qc_if_dd = pm.run(qc_c_if) qc_if_dd.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_5\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_5_0.png) ### Exploiting IBM backend’s local parallel “fast-path” IBM quantum hardware supports a localized “fast-path” which enables a block of gates applied to a *single qubit* that are conditional on an immediately predecessor measurement *of the same qubit* to be completed with lower latency. The hardware is also able to do this in *parallel* on disjoint qubits that satisfy this condition. For example, the conditional gates below are performed in parallel with lower latency as the measurements flow directly into the conditional blocks which in turn only apply gates to the same measurement qubit. ```python qc = QuantumCircuit(2, 2) qc.measure(0, 0) qc.measure(1, 1) # Conditional blocks will be performed in parallel in the hardware with qc.if_test((0, 1)): qc.x(0) with qc.if_test((1, 1)): qc.x(1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_6\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_6_0.png) The circuit below will not use the fast-path as the conditional gate is on a different qubit than the measurement qubit. ```python qc = QuantumCircuit(2, 2) qc.measure(0, 0) with qc.if_test((0, 1)): qc.x(1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_7\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_7_0.png) Similarly, the circuit below contains gates on multiple qubits and will not be performed using the fast-path. ```python qc = QuantumCircuit(2, 2) qc.measure(0, 0) with qc.if_test((0, 1)): qc.x(0) qc.x(1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_8\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_8_0.png) A fast-path block may contain multiple gates as long as they are on the fast-path qubit. If there are multiple fast-path blocks being performed in parallel each block will be padded out to the duration of the longest block. ```python qc = QuantumCircuit(2, 2) qc.measure(0, 0) qc.measure(1, 1) # Conditional blocks will be performed in parallel in the hardware with qc.if_test((0, 1)): qc.x(0) # Will be padded out to a duration of 1600 on the backend. with qc.if_test((1, 1)): qc.delay(1600, 1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_9\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_9_0.png) This behavior is also applied to the else condition of a fast-path eligible branch. ```python qc = QuantumCircuit(1, 1) qc.measure(0, 0) # Conditional blocks will be performed in parallel in the hardware with qc.if_test((0, 1)) as else_: qc.x(0) # Will be padded out to a duration of 1600 on the backend. with else_: qc.delay(1600, 0) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_10\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_10_0.png) If a single measurement result is used with several conditional blocks, if there is a fast-path eligible block it will be applied followed by the non-fast-path blocks which will execute with the standard higher latency conditional branch. ```python qc = QuantumCircuit(2, 2) qc.measure(0, 0) # Conditional blocks will be performed in parallel in the hardware with qc.if_test((0, 1)): # Uses fast-path qc.x(0) with qc.if_test((0, 1)): # Does not use fast-path qc.x(1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_11\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_11_0.png) If you wish to prevent the usage of the fast-path you may insert a barrier between the measurement and the conditional branch. ```python qc = QuantumCircuit(1, 2) qc.measure(0, 0) # Barrier prevents the fast-path. qc.barrier() with qc.if_test((0, 1)): qc.x(0) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_12\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_12_0.png) Conditional measurements are not eligible for the fast-path. ```python qc = QuantumCircuit(1, 2) qc.measure(0, 0) with qc.if_test((0, 1)): # Does not use the fast-path qc.measure(0, 1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_13\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_13_0.png) Similarly nested control-flow is not eligible. ```python qc = QuantumCircuit(1, 1) qc.measure(0, 0) with qc.if_test((0, 1)): # Does not use the fast-path qc.x(0) with qc.if_test((0, 1)): qc.x(0) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_14\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_14_0.png) The scheduler is aware of the fast-path behavior and will not insert delays on idle qubits in blocks that satisfy the fast-path conditions so as to avoid preventing the backend compiler from performing the necessary optimizations to utilize the fast-path. If there are fast-path blocks that will be performed in parallel they currently *will not* be padded out by the scheduler to ensure they are of the same duration in Qiskit ```python dd_sequence = [XGate(), XGate()] pm = PassManager( [ ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence), ] ) qc = QuantumCircuit(2, 2) qc.measure(0, 0) qc.measure(1, 1) with qc.if_test((0, 1)): qc.x(0) # Is currently not padded to ensure # a duration of 1000. If you desire # this you would need to manually add # qc.delay(840, 0) with qc.if_test((1, 1)): qc.delay(1000, 0) qc.draw(output=""mpl"", style=""iqp"") qc_dd = pm.run(qc) qc_dd.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_15\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_15_0.png) If there are qubits that are *not* involved in a fast-path decision it is not currently possible to use them in a fast-path branch in parallel with the fast-path qubits resulting from a measurement. This will be revised in the future as we further improve these capabilities. For example: ```python qc = QuantumCircuit(3, 2) qc.x(1) qc.measure(0, 0) with qc.if_test((0, 1)): qc.x(0) # Qubit 1 sits idle throughout the fast-path decision with qc.if_test((1, 0)): # Qubit 2 is idle but there is no measurement # to make it fast-path eligible. This will # however avoid a communication event in the hardware # since the condition is compile time evaluated. qc.x(2) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_provider.transpiler.passes.scheduling\_16\_0.png](/images/api/qiskit-ibm-provider/0.9/qiskit_ibm_provider.transpiler.passes.scheduling_16_0.png) #### Scheduling & Dynamical Decoupling | | | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [`BlockBasePadder`](qiskit_ibm_provider.transpiler.passes.scheduling.BlockBasePadder ""qiskit_ibm_provider.transpiler.passes.scheduling.BlockBasePadder"")(\[schedule\_idle\_qubits]) | The base class of padding pass. | | [`ALAPScheduleAnalysis`](qiskit_ibm_provider.transpiler.passes.scheduling.ALAPScheduleAnalysis ""qiskit_ibm_provider.transpiler.passes.scheduling.ALAPScheduleAnalysis"")(durations) | Dynamic circuits as-late-as-possible (ALAP) scheduling analysis pass. | | [`ASAPScheduleAnalysis`](qiskit_ibm_provider.transpiler.passes.scheduling.ASAPScheduleAnalysis ""qiskit_ibm_provider.transpiler.passes.scheduling.ASAPScheduleAnalysis"")(durations) | Dynamic circuits as-soon-as-possible (ASAP) scheduling analysis pass. | | [`DynamicCircuitInstructionDurations`](qiskit_ibm_provider.transpiler.passes.scheduling.DynamicCircuitInstructionDurations ""qiskit_ibm_provider.transpiler.passes.scheduling.DynamicCircuitInstructionDurations"")(\[...]) | For dynamic circuits the IBM Qiskit backend currently reports instruction durations that differ compared with those required for the legacy Qobj-based path. | | [`PadDelay`](qiskit_ibm_provider.transpiler.passes.scheduling.PadDelay ""qiskit_ibm_provider.transpiler.passes.scheduling.PadDelay"")(\[fill\_very\_end, schedule\_idle\_qubits]) | Padding idle time with Delay instructions. | | [`PadDynamicalDecoupling`](qiskit_ibm_provider.transpiler.passes.scheduling.PadDynamicalDecoupling ""qiskit_ibm_provider.transpiler.passes.scheduling.PadDynamicalDecoupling"")(durations, dd\_sequences) | Dynamical decoupling insertion pass for IBM dynamic circuit backends. | ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.transpiler.passes.scheduling.mdx "--- title: PadDelay description: API reference for qiskit_ibm_provider.transpiler.passes.scheduling.PadDelay in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.transpiler.passes.scheduling.PadDelay --- # PadDelay Padding idle time with Delay instructions. Consecutive delays will be merged in the output of this pass. The ASAP-scheduled circuit output may become ```python ┌────────────────┐ q_0: ┤ Delay(160[dt]) ├──■── └─────┬───┬──────┘┌─┴─┐ q_1: ──────┤ X ├───────┤ X ├ └───┘ └───┘ ``` Note that the additional idle time of 60dt on the `q_0` wire coming from the duration difference between `Delay` of 100dt (`q_0`) and `XGate` of 160 dt (`q_1`) is absorbed in the delay instruction on the `q_0` wire, i.e. in total 160 dt. See [`BlockBasePadder`](qiskit_ibm_provider.transpiler.passes.scheduling.BlockBasePadder ""qiskit_ibm_provider.transpiler.passes.scheduling.BlockBasePadder"") pass for details. Create new padding delay pass. **Parameters** * **fill\_very\_end** (`bool`) – Set `True` to fill the end of circuit with delay. * **schedule\_idle\_qubits** (`bool`) – Set to true if you’d like a delay inserted on idle qubits. This is useful for timeline visualizations, but may cause issues for execution on large backends. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### \_\_call\_\_ Runs the pass on circuit. **Parameters** * **circuit** (*QuantumCircuit*) – The dag on which the pass is run. * **property\_set** (*PropertySet | dict | None*) – Input/output property set. An analysis pass might change the property set in-place. **Return type** QuantumCircuit **Returns** If on transformation pass, the resulting QuantumCircuit. If analysis pass, the input circuit. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** (`Any`) – Qiskit IR to optimize. * **state** ([`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")) – State associated with workflow execution by the pass manager itself. * **callback** (`Optional`\[`Callable`]) – A callback function which is caller per execution of optimization task. **Return type** `tuple`\[`Any`, [`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")] **Returns** Optimized Qiskit IR and state of the workflow. ### name Name of the pass. **Return type** `str` ### run Run the padding pass on `dag`. **Parameters** **dag** ([`DAGCircuit`](/api/qiskit/qiskit.dagcircuit.DAGCircuit ""(in Qiskit v0.46)"")) – DAG to be checked. **Returns** DAG with idle time filled with instructions. **Return type** DAGCircuit **Raises** **TranspilerError** – When a particular node is not scheduled, likely some transform pass is inserted before this node is called. ### update\_status Update workflow status. **Parameters** * **state** ([`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")) – Pass manager state to update. * **run\_state** (`RunState`) – Completion status of current task. **Return type** [`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"") **Returns** Updated pass manager state. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.transpiler.passes.scheduling.PadDelay.mdx "--- title: PadDynamicalDecoupling description: API reference for qiskit_ibm_provider.transpiler.passes.scheduling.PadDynamicalDecoupling in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_provider.transpiler.passes.scheduling.PadDynamicalDecoupling --- # PadDynamicalDecoupling Dynamical decoupling insertion pass for IBM dynamic circuit backends. This pass works on a scheduled, physical circuit. It scans the circuit for idle periods of time (i.e. those containing delay instructions) and inserts a DD sequence of gates in those spots. These gates amount to the identity, so do not alter the logical action of the circuit, but have the effect of mitigating decoherence in those idle periods. As a special case, the pass allows a length-1 sequence (e.g. \[XGate()]). In this case the DD insertion happens only when the gate inverse can be absorbed into a neighboring gate in the circuit (so we would still be replacing Delay with something that is equivalent to the identity). This can be used, for instance, as a Hahn echo. This pass ensures that the inserted sequence preserves the circuit exactly (including global phase). ```python import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import XGate from qiskit.transpiler import PassManager, InstructionDurations from qiskit.visualization import timeline_drawer from qiskit_ibm_provider.transpiler.passes.scheduling import ALAPScheduleAnalysis from qiskit_ibm_provider.transpiler.passes.scheduling import PadDynamicalDecoupling circ = QuantumCircuit(4) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.cx(2, 3) circ.measure_all() durations = InstructionDurations( [(""h"", 0, 50), (""cx"", [0, 1], 700), (""reset"", None, 10), (""cx"", [1, 2], 200), (""cx"", [2, 3], 300), (""x"", None, 50), (""measure"", None, 1000)] ) ``` ```python # balanced X-X sequence on all qubits dd_sequence = [XGate(), XGate()] pm = PassManager([ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence)]) circ_dd = pm.run(circ) circ_dd.draw() ``` ```python ┌───┐ ┌───────────────┐ ┌───┐ » q_0: ──────┤ H ├─────────■──┤ Delay(96[dt]) ├──────┤ X ├──────» ┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴─────┐» q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(48[dt]) ├» ├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘» q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■────────» ├────────────────┤ └───┘ ┌─┴─┐ » q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├──────» └────────────────┘ └───┘ » meas: 4/═════════════════════════════════════════════════════════» » « ┌────────────────┐ ┌───┐ ┌───────────────┐ » « q_0: ┤ Delay(208[dt]) ├──────┤ X ├──────┤ Delay(96[dt]) ├─────────────────» « └─────┬───┬──────┘┌─────┴───┴─────┐└─────┬───┬─────┘┌───────────────┐» « q_1: ──────┤ X ├───────┤ Delay(96[dt]) ├──────┤ X ├──────┤ Delay(56[dt]) ├» « └───┘ └───────────────┘ └───┘ └───────────────┘» « q_2: ─────────────────────────────────────────────────────────────────────» « » « q_3: ─────────────────────────────────────────────────────────────────────» « » «meas: 4/═════════════════════════════════════════════════════════════════════» « » « ░ ┌─┐ « q_0: ─░─┤M├───────── « ░ └╥┘┌─┐ « q_1: ─░──╫─┤M├────── « ░ ║ └╥┘┌─┐ « q_2: ─░──╫──╫─┤M├─── « ░ ║ ║ └╥┘┌─┐ « q_3: ─░──╫──╫──╫─┤M├ « ░ ║ ║ ║ └╥┘ «meas: 4/════╩══╩══╩══╩═ « 0 1 2 3 ``` ```python # Uhrig sequence on qubit 0 n = 8 dd_sequence = [XGate()] * n def uhrig_pulse_location(k): return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2 spacings = [] for k in range(n): spacings.append(uhrig_pulse_location(k) - sum(spacings)) spacings.append(1 - sum(spacings)) pm = PassManager( [ ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence, qubits=[0], spacings=spacings), ] ) circ_dd = pm.run(circ) circ_dd.draw() ``` ```python ┌───┐ ┌────────────────┐ ░ ┌─┐ » q_0: ──────┤ H ├─────────■──┤ Delay(500[dt]) ├───────────────────░─┤M├──────» ┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌────────────────┐ ░ └╥┘┌─┐ » q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(300[dt]) ├─░──╫─┤M├───» ├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘ ░ ║ └╥┘┌─┐» q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■──────────░──╫──╫─┤M├» ├────────────────┤ └───┘ ┌─┴─┐ ░ ║ ║ └╥┘» q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├────────░──╫──╫──╫─» └────────────────┘ └───┘ ░ ║ ║ ║ » meas: 4/═══════════════════════════════════════════════════════════════╩══╩══╩═» 0 1 2 » « « q_0: ─── « « q_1: ─── « « q_2: ─── « ┌─┐ « q_3: ┤M├ « └╥┘ «meas: 4/═╩═ « 3 ``` You need to call [`ALAPScheduleAnalysis`](qiskit_ibm_provider.transpiler.passes.scheduling.ALAPScheduleAnalysis ""qiskit_ibm_provider.transpiler.passes.scheduling.ALAPScheduleAnalysis"") before running dynamical decoupling to guarantee your circuit satisfies acquisition alignment constraints for dynamic circuit backends. Dynamical decoupling initializer. **Parameters** * **durations** ([`InstructionDurations`](/api/qiskit/qiskit.transpiler.InstructionDurations ""(in Qiskit v0.46)"")) – Durations of instructions to be used in scheduling. * **dd\_sequences** (`Union`\[`List`\[[`Gate`](/api/qiskit/qiskit.circuit.Gate ""(in Qiskit v0.46)"")], `List`\[`List`\[[`Gate`](/api/qiskit/qiskit.circuit.Gate ""(in Qiskit v0.46)"")]]]) – Sequence of gates to apply in idle spots. Alternatively a list of gate sequences may be supplied that will preferentially be inserted if there is a delay of sufficient duration. This may be tuned by the optionally supplied `sequence_min_length_ratios`. * **qubits** (`Optional`\[`List`\[`int`]]) – Physical qubits on which to apply DD. If None, all qubits will undergo DD (when possible). * **spacings** (`Union`\[`List`\[`List`\[`float`]], `List`\[`float`], `None`]) – A list of lists of spacings between the DD gates. The available slack will be divided according to this. The list length must be one more than the length of dd\_sequence, and the elements must sum to 1. If None, a balanced spacing will be used \[d/2, d, d, …, d, d, d/2]. This spacing only applies to the first subcircuit, if a `coupling_map` is specified * **skip\_reset\_qubits** (`bool`) – If True, does not insert DD on idle periods that immediately follow initialized/reset qubits (as qubits in the ground state are less susceptible to decoherence). * **pulse\_alignment** (`int`) – The hardware constraints for gate timing allocation. This is usually provided from `backend.configuration().timing_constraints`. If provided, the delay length, i.e. `spacing`, is implicitly adjusted to satisfy this constraint. * **extra\_slack\_distribution** (`str`) – The option to control the behavior of DD sequence generation. The duration of the DD sequence should be identical to an idle time in the scheduled quantum circuit, however, the delay in between gates comprising the sequence should be integer number in units of dt, and it might be further truncated when `pulse_alignment` is specified. This sometimes results in the duration of the created sequence being shorter than the idle time that you want to fill with the sequence, i.e. extra slack. This option takes following values. > * ”middle”: Put the extra slack to the interval at the middle of the sequence. > * ”edges”: Divide the extra slack as evenly as possible into intervals at beginning and end of the sequence. * **sequence\_min\_length\_ratios** (`Union`\[`int`, `List`\[`int`], `None`]) – List of minimum delay length to DD sequence ratio to satisfy in order to insert the DD sequence. For example if the X-X dynamical decoupling sequence is 320dt samples long and the available delay is 384dt it has a ratio of 384dt/320dt=1.2. From the perspective of dynamical decoupling this is likely to add more control noise than decoupling error rate reductions. The defaults value is 2.0. * **insert\_multiple\_cycles** (`bool`) – If the available duration exceeds 2\*sequence\_min\_length\_ratio\*duration(dd\_sequence) enable the insertion of multiple rounds of the dynamical decoupling sequence in that delay. * **coupling\_map** (`Optional`\[[`CouplingMap`](/api/qiskit/qiskit.transpiler.CouplingMap ""(in Qiskit v0.46)"")]) – directed graph representing the coupling map for the device. Specifying a coupling map partitions the device into subcircuits, in order to apply DD sequences with different pulse spacings within each. Currently support 2 subcircuits. * **alt\_spacings** (`Union`\[`List`\[`List`\[`float`]], `List`\[`float`], `None`]) – A list of lists of spacings between the DD gates, for the second subcircuit, as determined by the coupling map. If None, a balanced spacing that is staggered with respect to the first subcircuit will be used \[d, d, d, …, d, d, 0]. * **schedule\_idle\_qubits** (`bool`) – Set to true if you’d like a delay inserted on idle qubits. This is useful for timeline visualizations, but may cause issues for execution on large backends. **Raises** * **TranspilerError** – When invalid DD sequence is specified. * **TranspilerError** – When pulse gate with the duration which is non-multiple of the alignment constraint value is found. * **TranspilerError** – When the coupling map is not supported (i.e., if degree > 3) ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### \_\_call\_\_ Runs the pass on circuit. **Parameters** * **circuit** (*QuantumCircuit*) – The dag on which the pass is run. * **property\_set** (*PropertySet | dict | None*) – Input/output property set. An analysis pass might change the property set in-place. **Return type** QuantumCircuit **Returns** If on transformation pass, the resulting QuantumCircuit. If analysis pass, the input circuit. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** (`Any`) – Qiskit IR to optimize. * **state** ([`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")) – State associated with workflow execution by the pass manager itself. * **callback** (`Optional`\[`Callable`]) – A callback function which is caller per execution of optimization task. **Return type** `tuple`\[`Any`, [`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")] **Returns** Optimized Qiskit IR and state of the workflow. ### name Name of the pass. **Return type** `str` ### run Run the padding pass on `dag`. **Parameters** **dag** ([`DAGCircuit`](/api/qiskit/qiskit.dagcircuit.DAGCircuit ""(in Qiskit v0.46)"")) – DAG to be checked. **Returns** DAG with idle time filled with instructions. **Return type** DAGCircuit **Raises** **TranspilerError** – When a particular node is not scheduled, likely some transform pass is inserted before this node is called. ### update\_status Update workflow status. **Parameters** * **state** ([`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"")) – Pass manager state to update. * **run\_state** (`RunState`) – Completion status of current task. **Return type** [`PassManagerState`](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v0.46)"") **Returns** Updated pass manager state. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.transpiler.passes.scheduling.PadDynamicalDecoupling.mdx "--- title: seconds_to_duration description: API reference for qiskit_ibm_provider.utils.seconds_to_duration in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit_ibm_provider.utils.seconds_to_duration --- # seconds\_to\_duration Converts seconds in a datetime delta to a duration. **Parameters** **seconds** (`float`) – Number of seconds in time delta. **Return type** `Tuple`\[`int`, `int`, `int`, `int`, `int`] **Returns** A tuple containing the duration in terms of days, hours, minutes, seconds, and milliseconds. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.utils.seconds_to_duration.mdx "--- title: to_python_identifier description: API reference for qiskit_ibm_provider.utils.to_python_identifier in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit_ibm_provider.utils.to_python_identifier --- # to\_python\_identifier Convert a name to a valid Python identifier. **Parameters** **name** (`str`) – Name to be converted. **Return type** `str` **Returns** Name that is a valid Python identifier. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.utils.to_python_identifier.mdx "--- title: utc_to_local description: API reference for qiskit_ibm_provider.utils.utc_to_local in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit_ibm_provider.utils.utc_to_local --- # utc\_to\_local Convert a UTC `datetime` object or string to a local timezone `datetime`. **Parameters** **utc\_dt** (`Union`\[`datetime`, `str`]) – Input UTC datetime or string. **Return type** `datetime` **Returns** A `datetime` with the local timezone. **Raises** **TypeError** – If the input parameter value is not valid. ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.utils.utc_to_local.mdx "--- title: validate_job_tags description: API reference for qiskit_ibm_provider.utils.validate_job_tags in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit_ibm_provider.utils.validate_job_tags --- # validate\_job\_tags Validates input job tags. **Parameters** * **job\_tags** (`Optional`\[`List`\[`str`]]) – Job tags to be validated. * **exception** (`Type`\[`Exception`]) – Exception to raise if the tags are invalid. **Raises** **Exception** – If the job tags are invalid. **Return type** `None` ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.utils.validate_job_tags.mdx "--- title: iplot_error_map description: API reference for qiskit_ibm_provider.visualization.iplot_error_map in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit_ibm_provider.visualization.iplot_error_map --- # iplot\_error\_map Plot the error map of a device. **Parameters** * **backend** ([`IBMBackend`](qiskit_ibm_provider.IBMBackend ""qiskit_ibm_provider.ibm_backend.IBMBackend"")) – Plot the error map for this backend. * **figsize** (`Tuple`\[`int`]) – Figure size in pixels. * **show\_title** (`bool`) – Whether to show figure title. * **remove\_badcal\_edges** (`bool`) – Whether to remove bad CX gate calibration data. * **background\_color** (`str`) – Background color, either ‘white’ or ‘black’. * **as\_widget** (`bool`) – `True` if the figure is to be returned as a `PlotlyWidget`. Otherwise the figure is to be returned as a `PlotlyFigure`. **Return type** `Union`\[`PlotlyFigure`, `PlotlyWidget`] **Returns** The error map figure. **Raises** * **VisualizationValueError** – If an invalid input is received. * **VisualizationTypeError** – If the specified backend is a simulator. **Example** ```python from qiskit_ibm_provider import IBMProvider from qiskit_ibm_provider.visualization import iplot_error_map provider = IBMProvider(group='open', project='main') # Note that this is a mock provider, replace ``FakeOpenPulse2Q`` # with any of the currently available IBM devices. backend = provider.get_backend('FakeOpenPulse2Q') iplot_error_map(backend, as_widget=True) ``` ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.visualization.iplot_error_map.mdx "--- title: iplot_gate_map description: API reference for qiskit_ibm_provider.visualization.iplot_gate_map in_page_toc_min_heading_level: 1 python_api_type: function python_api_name: qiskit_ibm_provider.visualization.iplot_gate_map --- # iplot\_gate\_map Plots an interactive gate map of a device. **Parameters** * **backend** ([`IBMBackend`](qiskit_ibm_provider.IBMBackend ""qiskit_ibm_provider.ibm_backend.IBMBackend"")) – Plot the gate map for this backend. * **figsize** (`Tuple`\[`Optional`\[`int`], `Optional`\[`int`]]) – Output figure size (wxh) in inches. * **label\_qubits** (`bool`) – Labels for the qubits. * **qubit\_size** (`Optional`\[`float`]) – Size of qubit marker. * **line\_width** (`Optional`\[`float`]) – Width of lines. * **font\_size** (`Optional`\[`int`]) – Font size of qubit labels. * **qubit\_color** (`Union`\[`List`\[`str`], `str`]) – A list of colors for the qubits. If a single color is given, it’s used for all qubits. * **qubit\_labels** (`Optional`\[`List`\[`str`]]) – A list of qubit labels * **line\_color** (`Union`\[`List`\[`str`], `str`]) – A list of colors for each line from the coupling map. If a single color is given, it’s used for all lines. * **font\_color** (`str`) – The font color for the qubit labels. * **background\_color** (`str`) – The background color, either ‘white’ or ‘black’. * **as\_widget** (`bool`) – `True` if the figure is to be returned as a `PlotlyWidget`. Otherwise the figure is to be returned as a `PlotlyFigure`. **Return type** `Union`\[`PlotlyFigure`, `PlotlyWidget`] **Returns** The gate map figure. **Example** ```python from qiskit_ibm_provider import IBMProvider from qiskit_ibm_provider.visualization import iplot_gate_map provider = IBMProvider(group='open', project='main') # Note that this is a mock provider, replace ``FakeOpenPulse2Q`` # with any of the currently available IBM devices. backend = provider.get_backend('FakeOpenPulse2Q') iplot_gate_map(backend, as_widget=True) ``` ",repo/docs/api/qiskit-ibm-provider/0.9\qiskit_ibm_provider.visualization.iplot_gate_map.mdx "--- title: fake_provider description: API reference for qiskit_ibm_runtime.fake_provider in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_runtime.fake_provider --- # Fake Provider `qiskit_ibm_runtime.fake_provider` ## Overview The fake provider module contains fake providers and fake backends classes. The fake backends are built to mimic the behaviors of IBM Quantum systems using system snapshots. The system snapshots contain important information about the quantum system such as coupling map, basis gates, qubit properties (T1, T2, error rate, etc.) which are useful for testing the transpiler and performing noisy simulations of the system. ## Example Usage Here is an example of using a fake backend for transpilation and simulation. ```python from qiskit import QuantumCircuit from qiskit import transpile from qiskit.visualization import plot_histogram from qiskit_ibm_runtime import SamplerV2 from qiskit_ibm_runtime.fake_provider import FakeManilaV2 # Get a fake backend from the fake provider backend = FakeManilaV2() # Create a simple circuit circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0,1) circuit.cx(0,2) circuit.measure_all() circuit.draw('mpl', style=""iqp"") # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(circuit, backend) transpiled_circuit.draw('mpl', style=""iqp"") # Run the transpiled circuit using the simulated fake backend sampler = SamplerV2(backend) job = sampler.run([transpiled_circuit]) pub_result = job.result()[0] counts = pub_result.data.meas.get_counts() plot_histogram(counts) ``` ![../\_images/fake\_provider-1\_00.png](/images/api/qiskit-ibm-runtime/0.25/fake_provider-1_00.png) ![../\_images/fake\_provider-1\_01.png](/images/api/qiskit-ibm-runtime/0.25/fake_provider-1_01.png) ![../\_images/fake\_provider-1\_02.png](/images/api/qiskit-ibm-runtime/0.25/fake_provider-1_02.png) Please note that the simulation is done using a noise model generated from system snapshots obtained in the past (sometimes a few years ago) and the results are not representative of the latest behaviours of the real quantum system which the fake backend is mimicking. If you want to run noisy simulations to compare with the real quantum system, you should use the `qiskit_aer` library. After installation, you can follow the steps below to generate a simulator that mimics a real quantum system with the latest calibration results. ```python from qiskit_ibm_runtime import QiskitRuntimeService from qiskit_aer import AerSimulator # get a real backend from the runtime service service = QiskitRuntimeService() backend = service.backend('ibmq_manila') # generate a simulator that mimics the real quantum system with the latest calibration results backend_sim = AerSimulator.from_backend(backend) ``` ## Fake Providers Fake providers provide access to a list of fake backends. | | | | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | | [`FakeProviderForBackendV2`](qiskit_ibm_runtime.fake_provider.FakeProviderForBackendV2 ""qiskit_ibm_runtime.fake_provider.FakeProviderForBackendV2"")() | Fake provider containing fake V2 backends. | | [`FakeProvider`](qiskit_ibm_runtime.fake_provider.FakeProvider ""qiskit_ibm_runtime.fake_provider.FakeProvider"")() | Fake provider containing fake V1 backends. | ## Fake Backends ### Fake V2 Backends Fake V2 backends are fake backends with IBM Quantum systems snapshots implemented with `BackendV2` interface. They are all subclasses of `FakeBackendV2`. | | | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | [`FakeAlgiers`](qiskit_ibm_runtime.fake_provider.FakeAlgiers ""qiskit_ibm_runtime.fake_provider.FakeAlgiers"")() | A fake 27 qubit backend. | | [`FakeAlmadenV2`](qiskit_ibm_runtime.fake_provider.FakeAlmadenV2 ""qiskit_ibm_runtime.fake_provider.FakeAlmadenV2"")() | A fake Almaden V2 backend. | | [`FakeArmonkV2`](qiskit_ibm_runtime.fake_provider.FakeArmonkV2 ""qiskit_ibm_runtime.fake_provider.FakeArmonkV2"")() | A fake 1 qubit backend. | | [`FakeAthensV2`](qiskit_ibm_runtime.fake_provider.FakeAthensV2 ""qiskit_ibm_runtime.fake_provider.FakeAthensV2"")() | A fake 5 qubit backend. | | [`FakeAuckland`](qiskit_ibm_runtime.fake_provider.FakeAuckland ""qiskit_ibm_runtime.fake_provider.FakeAuckland"")() | A fake 27 qubit backend. | | [`FakeBelemV2`](qiskit_ibm_runtime.fake_provider.FakeBelemV2 ""qiskit_ibm_runtime.fake_provider.FakeBelemV2"")() | A fake 5 qubit backend. | | [`FakeBoeblingenV2`](qiskit_ibm_runtime.fake_provider.FakeBoeblingenV2 ""qiskit_ibm_runtime.fake_provider.FakeBoeblingenV2"")() | A fake Boeblingen V2 backend. | | [`FakeBogotaV2`](qiskit_ibm_runtime.fake_provider.FakeBogotaV2 ""qiskit_ibm_runtime.fake_provider.FakeBogotaV2"")() | A fake 5 qubit backend. | | [`FakeBrisbane`](qiskit_ibm_runtime.fake_provider.FakeBrisbane ""qiskit_ibm_runtime.fake_provider.FakeBrisbane"")() | A fake 127 qubit backend. | | [`FakeBrooklynV2`](qiskit_ibm_runtime.fake_provider.FakeBrooklynV2 ""qiskit_ibm_runtime.fake_provider.FakeBrooklynV2"")() | A fake Brooklyn V2 backend. | | [`FakeBurlingtonV2`](qiskit_ibm_runtime.fake_provider.FakeBurlingtonV2 ""qiskit_ibm_runtime.fake_provider.FakeBurlingtonV2"")() | A fake 5 qubit backend. | | [`FakeCairoV2`](qiskit_ibm_runtime.fake_provider.FakeCairoV2 ""qiskit_ibm_runtime.fake_provider.FakeCairoV2"")() | A fake 27 qubit backend. | | [`FakeCambridgeV2`](qiskit_ibm_runtime.fake_provider.FakeCambridgeV2 ""qiskit_ibm_runtime.fake_provider.FakeCambridgeV2"")() | A fake Cambridge backend. | | [`FakeCasablancaV2`](qiskit_ibm_runtime.fake_provider.FakeCasablancaV2 ""qiskit_ibm_runtime.fake_provider.FakeCasablancaV2"")() | A fake 7 qubit backend. | | [`FakeCusco`](qiskit_ibm_runtime.fake_provider.FakeCusco ""qiskit_ibm_runtime.fake_provider.FakeCusco"")() | A fake 127 qubit backend. | | [`FakeEssexV2`](qiskit_ibm_runtime.fake_provider.FakeEssexV2 ""qiskit_ibm_runtime.fake_provider.FakeEssexV2"")() | A fake 5 qubit backend. | | [`FakeGeneva`](qiskit_ibm_runtime.fake_provider.FakeGeneva ""qiskit_ibm_runtime.fake_provider.FakeGeneva"")() | A fake 27 qubit backend. | | [`FakeGuadalupeV2`](qiskit_ibm_runtime.fake_provider.FakeGuadalupeV2 ""qiskit_ibm_runtime.fake_provider.FakeGuadalupeV2"")() | A fake 16 qubit backend. | | [`FakeHanoiV2`](qiskit_ibm_runtime.fake_provider.FakeHanoiV2 ""qiskit_ibm_runtime.fake_provider.FakeHanoiV2"")() | A fake 27 qubit backend. | | [`FakeJakartaV2`](qiskit_ibm_runtime.fake_provider.FakeJakartaV2 ""qiskit_ibm_runtime.fake_provider.FakeJakartaV2"")() | A fake 7 qubit V2 backend. | | [`FakeJohannesburgV2`](qiskit_ibm_runtime.fake_provider.FakeJohannesburgV2 ""qiskit_ibm_runtime.fake_provider.FakeJohannesburgV2"")() | A fake Johannesburg V2 backend. | | [`FakeKawasaki`](qiskit_ibm_runtime.fake_provider.FakeKawasaki ""qiskit_ibm_runtime.fake_provider.FakeKawasaki"")() | A fake 127 qubit backend. | | [`FakeKolkataV2`](qiskit_ibm_runtime.fake_provider.FakeKolkataV2 ""qiskit_ibm_runtime.fake_provider.FakeKolkataV2"")() | A fake 27 qubit backend. | | [`FakeKyiv`](qiskit_ibm_runtime.fake_provider.FakeKyiv ""qiskit_ibm_runtime.fake_provider.FakeKyiv"")() | A fake 127 qubit backend. | | [`FakeKyoto`](qiskit_ibm_runtime.fake_provider.FakeKyoto ""qiskit_ibm_runtime.fake_provider.FakeKyoto"")() | A fake 127 qubit backend. | | [`FakeLagosV2`](qiskit_ibm_runtime.fake_provider.FakeLagosV2 ""qiskit_ibm_runtime.fake_provider.FakeLagosV2"")() | A fake 7 qubit backend. | | [`FakeLimaV2`](qiskit_ibm_runtime.fake_provider.FakeLimaV2 ""qiskit_ibm_runtime.fake_provider.FakeLimaV2"")() | A fake 5 qubit backend. | | [`FakeFractionalBackend`](qiskit_ibm_runtime.fake_provider.FakeFractionalBackend ""qiskit_ibm_runtime.fake_provider.FakeFractionalBackend"")() | A fake 5 qubit backend with dynamic and fractional feature modeled based on FakeLima. | | [`FakeLondonV2`](qiskit_ibm_runtime.fake_provider.FakeLondonV2 ""qiskit_ibm_runtime.fake_provider.FakeLondonV2"")() | A fake 5 qubit backend. | | [`FakeManhattanV2`](qiskit_ibm_runtime.fake_provider.FakeManhattanV2 ""qiskit_ibm_runtime.fake_provider.FakeManhattanV2"")() | A fake Manhattan backend. | | [`FakeManilaV2`](qiskit_ibm_runtime.fake_provider.FakeManilaV2 ""qiskit_ibm_runtime.fake_provider.FakeManilaV2"")() | A fake 5 qubit backend. | | [`FakeMelbourneV2`](qiskit_ibm_runtime.fake_provider.FakeMelbourneV2 ""qiskit_ibm_runtime.fake_provider.FakeMelbourneV2"")() | A fake 14 qubit backend. | | [`FakeMontrealV2`](qiskit_ibm_runtime.fake_provider.FakeMontrealV2 ""qiskit_ibm_runtime.fake_provider.FakeMontrealV2"")() | A fake 27 qubit backend. | | [`FakeMumbaiV2`](qiskit_ibm_runtime.fake_provider.FakeMumbaiV2 ""qiskit_ibm_runtime.fake_provider.FakeMumbaiV2"")() | A fake 27 qubit backend. | | [`FakeNairobiV2`](qiskit_ibm_runtime.fake_provider.FakeNairobiV2 ""qiskit_ibm_runtime.fake_provider.FakeNairobiV2"")() | A fake 7 qubit backend. | | [`FakeOsaka`](qiskit_ibm_runtime.fake_provider.FakeOsaka ""qiskit_ibm_runtime.fake_provider.FakeOsaka"")() | A fake 127 qubit backend. | | [`FakeOslo`](qiskit_ibm_runtime.fake_provider.FakeOslo ""qiskit_ibm_runtime.fake_provider.FakeOslo"")() | A fake 7 qubit backend. | | [`FakeOurenseV2`](qiskit_ibm_runtime.fake_provider.FakeOurenseV2 ""qiskit_ibm_runtime.fake_provider.FakeOurenseV2"")() | A fake 5 qubit backend. | | [`FakeParisV2`](qiskit_ibm_runtime.fake_provider.FakeParisV2 ""qiskit_ibm_runtime.fake_provider.FakeParisV2"")() | A fake Paris backend. | | [`FakePeekskill`](qiskit_ibm_runtime.fake_provider.FakePeekskill ""qiskit_ibm_runtime.fake_provider.FakePeekskill"")() | A fake 27 qubit backend. | | [`FakePerth`](qiskit_ibm_runtime.fake_provider.FakePerth ""qiskit_ibm_runtime.fake_provider.FakePerth"")() | A fake 7 qubit backend. | | [`FakePrague`](qiskit_ibm_runtime.fake_provider.FakePrague ""qiskit_ibm_runtime.fake_provider.FakePrague"")() | A fake 33 qubit backend. | | [`FakePoughkeepsieV2`](qiskit_ibm_runtime.fake_provider.FakePoughkeepsieV2 ""qiskit_ibm_runtime.fake_provider.FakePoughkeepsieV2"")() | A fake Poughkeepsie backend. | | [`FakeQuebec`](qiskit_ibm_runtime.fake_provider.FakeQuebec ""qiskit_ibm_runtime.fake_provider.FakeQuebec"")() | A fake 127 qubit backend. | | [`FakeQuitoV2`](qiskit_ibm_runtime.fake_provider.FakeQuitoV2 ""qiskit_ibm_runtime.fake_provider.FakeQuitoV2"")() | A fake 5 qubit backend. | | [`FakeRochesterV2`](qiskit_ibm_runtime.fake_provider.FakeRochesterV2 ""qiskit_ibm_runtime.fake_provider.FakeRochesterV2"")() | A fake Rochester backend. | | [`FakeRomeV2`](qiskit_ibm_runtime.fake_provider.FakeRomeV2 ""qiskit_ibm_runtime.fake_provider.FakeRomeV2"")() | A fake 5 qubit backend. | | [`FakeSantiagoV2`](qiskit_ibm_runtime.fake_provider.FakeSantiagoV2 ""qiskit_ibm_runtime.fake_provider.FakeSantiagoV2"")() | A fake Santiago backend. | | [`FakeSherbrooke`](qiskit_ibm_runtime.fake_provider.FakeSherbrooke ""qiskit_ibm_runtime.fake_provider.FakeSherbrooke"")() | A fake 127 qubit backend. | | [`FakeSingaporeV2`](qiskit_ibm_runtime.fake_provider.FakeSingaporeV2 ""qiskit_ibm_runtime.fake_provider.FakeSingaporeV2"")() | A fake Singapore backend. | | [`FakeSydneyV2`](qiskit_ibm_runtime.fake_provider.FakeSydneyV2 ""qiskit_ibm_runtime.fake_provider.FakeSydneyV2"")() | A fake 27 qubit backend. | | [`FakeTorino`](qiskit_ibm_runtime.fake_provider.FakeTorino ""qiskit_ibm_runtime.fake_provider.FakeTorino"")() | A fake 133 qubit backend. | | [`FakeTorontoV2`](qiskit_ibm_runtime.fake_provider.FakeTorontoV2 ""qiskit_ibm_runtime.fake_provider.FakeTorontoV2"")() | A fake 27 qubit backend. | | [`FakeValenciaV2`](qiskit_ibm_runtime.fake_provider.FakeValenciaV2 ""qiskit_ibm_runtime.fake_provider.FakeValenciaV2"")() | A fake 5 qubit backend. | | [`FakeVigoV2`](qiskit_ibm_runtime.fake_provider.FakeVigoV2 ""qiskit_ibm_runtime.fake_provider.FakeVigoV2"")() | A fake 5 qubit backend. | | [`FakeWashingtonV2`](qiskit_ibm_runtime.fake_provider.FakeWashingtonV2 ""qiskit_ibm_runtime.fake_provider.FakeWashingtonV2"")() | A fake 127 qubit backend. | | [`FakeYorktownV2`](qiskit_ibm_runtime.fake_provider.FakeYorktownV2 ""qiskit_ibm_runtime.fake_provider.FakeYorktownV2"")() | A fake 5 qubit backend. | ### Fake V1 Backends Fake V1 backends are fake backends with IBM Quantum systems snapshots implemented with `BackendV1` interface. | | | | ----------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | | [`FakeAlmaden`](qiskit_ibm_runtime.fake_provider.FakeAlmaden ""qiskit_ibm_runtime.fake_provider.FakeAlmaden"")() | A fake Almaden backend. | | [`FakeArmonk`](qiskit_ibm_runtime.fake_provider.FakeArmonk ""qiskit_ibm_runtime.fake_provider.FakeArmonk"")() | A fake 1 qubit backend. | | [`FakeAthens`](qiskit_ibm_runtime.fake_provider.FakeAthens ""qiskit_ibm_runtime.fake_provider.FakeAthens"")() | A fake 5 qubit backend. | | [`FakeBelem`](qiskit_ibm_runtime.fake_provider.FakeBelem ""qiskit_ibm_runtime.fake_provider.FakeBelem"")() | A fake 5 qubit backend. | | [`FakeBoeblingen`](qiskit_ibm_runtime.fake_provider.FakeBoeblingen ""qiskit_ibm_runtime.fake_provider.FakeBoeblingen"")() | A fake Boeblingen backend. | | [`FakeBogota`](qiskit_ibm_runtime.fake_provider.FakeBogota ""qiskit_ibm_runtime.fake_provider.FakeBogota"")() | A fake 5 qubit backend. | | [`FakeBrooklyn`](qiskit_ibm_runtime.fake_provider.FakeBrooklyn ""qiskit_ibm_runtime.fake_provider.FakeBrooklyn"")() | A fake Brooklyn backend. | | [`FakeBurlington`](qiskit_ibm_runtime.fake_provider.FakeBurlington ""qiskit_ibm_runtime.fake_provider.FakeBurlington"")() | A fake 5 qubit backend. | | [`FakeCairo`](qiskit_ibm_runtime.fake_provider.FakeCairo ""qiskit_ibm_runtime.fake_provider.FakeCairo"")() | A fake 27 qubit backend. | | [`FakeCambridge`](qiskit_ibm_runtime.fake_provider.FakeCambridge ""qiskit_ibm_runtime.fake_provider.FakeCambridge"")() | A fake Cambridge backend. | | [`FakeCasablanca`](qiskit_ibm_runtime.fake_provider.FakeCasablanca ""qiskit_ibm_runtime.fake_provider.FakeCasablanca"")() | A fake 7 qubit backend. | | [`FakeEssex`](qiskit_ibm_runtime.fake_provider.FakeEssex ""qiskit_ibm_runtime.fake_provider.FakeEssex"")() | A fake 5 qubit backend. | | [`FakeGuadalupe`](qiskit_ibm_runtime.fake_provider.FakeGuadalupe ""qiskit_ibm_runtime.fake_provider.FakeGuadalupe"")() | A fake 16 qubit backend. | | [`FakeHanoi`](qiskit_ibm_runtime.fake_provider.FakeHanoi ""qiskit_ibm_runtime.fake_provider.FakeHanoi"")() | A fake 27 qubit backend. | | [`FakeJakarta`](qiskit_ibm_runtime.fake_provider.FakeJakarta ""qiskit_ibm_runtime.fake_provider.FakeJakarta"")() | A fake 7 qubit backend. | | [`FakeJohannesburg`](qiskit_ibm_runtime.fake_provider.FakeJohannesburg ""qiskit_ibm_runtime.fake_provider.FakeJohannesburg"")() | A fake Johannesburg backend. | | [`FakeKolkata`](qiskit_ibm_runtime.fake_provider.FakeKolkata ""qiskit_ibm_runtime.fake_provider.FakeKolkata"")() | A fake 27 qubit backend. | | [`FakeLagos`](qiskit_ibm_runtime.fake_provider.FakeLagos ""qiskit_ibm_runtime.fake_provider.FakeLagos"")() | A fake 7 qubit backend. | | [`FakeLima`](qiskit_ibm_runtime.fake_provider.FakeLima ""qiskit_ibm_runtime.fake_provider.FakeLima"")() | A fake 5 qubit backend. | | [`FakeLondon`](qiskit_ibm_runtime.fake_provider.FakeLondon ""qiskit_ibm_runtime.fake_provider.FakeLondon"")() | A fake 5 qubit backend. | | [`FakeManhattan`](qiskit_ibm_runtime.fake_provider.FakeManhattan ""qiskit_ibm_runtime.fake_provider.FakeManhattan"")() | A fake Manhattan backend. | | [`FakeManila`](qiskit_ibm_runtime.fake_provider.FakeManila ""qiskit_ibm_runtime.fake_provider.FakeManila"")() | A fake 5 qubit backend. | | [`FakeMelbourne`](qiskit_ibm_runtime.fake_provider.FakeMelbourne ""qiskit_ibm_runtime.fake_provider.FakeMelbourne"")() | A fake 14 qubit backend. | | [`FakeMontreal`](qiskit_ibm_runtime.fake_provider.FakeMontreal ""qiskit_ibm_runtime.fake_provider.FakeMontreal"")() | A fake 27 qubit backend. | | [`FakeMumbai`](qiskit_ibm_runtime.fake_provider.FakeMumbai ""qiskit_ibm_runtime.fake_provider.FakeMumbai"")() | A fake 27 qubit backend. | | [`FakeNairobi`](qiskit_ibm_runtime.fake_provider.FakeNairobi ""qiskit_ibm_runtime.fake_provider.FakeNairobi"")() | A fake 7 qubit backend. | | [`FakeOurense`](qiskit_ibm_runtime.fake_provider.FakeOurense ""qiskit_ibm_runtime.fake_provider.FakeOurense"")() | A fake 5 qubit backend. | | [`FakeParis`](qiskit_ibm_runtime.fake_provider.FakeParis ""qiskit_ibm_runtime.fake_provider.FakeParis"")() | A fake Paris backend. | | [`FakePoughkeepsie`](qiskit_ibm_runtime.fake_provider.FakePoughkeepsie ""qiskit_ibm_runtime.fake_provider.FakePoughkeepsie"")() | A fake Poughkeepsie backend. | | [`FakeQuito`](qiskit_ibm_runtime.fake_provider.FakeQuito ""qiskit_ibm_runtime.fake_provider.FakeQuito"")() | A fake 5 qubit backend. | | [`FakeRochester`](qiskit_ibm_runtime.fake_provider.FakeRochester ""qiskit_ibm_runtime.fake_provider.FakeRochester"")() | A fake Rochester backend. | | [`FakeRome`](qiskit_ibm_runtime.fake_provider.FakeRome ""qiskit_ibm_runtime.fake_provider.FakeRome"")() | A fake 5 qubit backend. | | [`FakeRueschlikon`](qiskit_ibm_runtime.fake_provider.FakeRueschlikon ""qiskit_ibm_runtime.fake_provider.FakeRueschlikon"")() | A fake 16 qubit backend. | | [`FakeSantiago`](qiskit_ibm_runtime.fake_provider.FakeSantiago ""qiskit_ibm_runtime.fake_provider.FakeSantiago"")() | A fake Santiago backend. | | [`FakeSingapore`](qiskit_ibm_runtime.fake_provider.FakeSingapore ""qiskit_ibm_runtime.fake_provider.FakeSingapore"")() | A fake Singapore backend. | | [`FakeSydney`](qiskit_ibm_runtime.fake_provider.FakeSydney ""qiskit_ibm_runtime.fake_provider.FakeSydney"")() | A fake 27 qubit backend. | | [`FakeTenerife`](qiskit_ibm_runtime.fake_provider.FakeTenerife ""qiskit_ibm_runtime.fake_provider.FakeTenerife"")() | A fake 5 qubit backend. | | [`FakeTokyo`](qiskit_ibm_runtime.fake_provider.FakeTokyo ""qiskit_ibm_runtime.fake_provider.FakeTokyo"")() | A fake 20 qubit backend. | | [`FakeToronto`](qiskit_ibm_runtime.fake_provider.FakeToronto ""qiskit_ibm_runtime.fake_provider.FakeToronto"")() | A fake 27 qubit backend. | | [`FakeValencia`](qiskit_ibm_runtime.fake_provider.FakeValencia ""qiskit_ibm_runtime.fake_provider.FakeValencia"")() | A fake 5 qubit backend. | | [`FakeVigo`](qiskit_ibm_runtime.fake_provider.FakeVigo ""qiskit_ibm_runtime.fake_provider.FakeVigo"")() | A fake 5 qubit backend. | | [`FakeWashington`](qiskit_ibm_runtime.fake_provider.FakeWashington ""qiskit_ibm_runtime.fake_provider.FakeWashington"")() | A fake 127 qubit backend. | | [`FakeYorktown`](qiskit_ibm_runtime.fake_provider.FakeYorktown ""qiskit_ibm_runtime.fake_provider.FakeYorktown"")() | A fake 5 qubit backend. | ",repo/docs/api/qiskit-ibm-runtime/0.25\fake_provider.mdx "--- title: Qiskit Runtime IBM Client API Docs description: API documentation for the qiskit-ibm-runtime client --- # qiskit-ibm-runtime API reference * [Qiskit Runtime (`qiskit_ibm_runtime`)](runtime_service) * [Primitive options (`qiskit_ibm_runtime.options`)](options) * [Transpiler passes (`qiskit_ibm_runtime.transpiler.passes`)](transpiler) * [Transpiler scheduling passes (`qiskit_ibm_runtime.transpiler.passes.scheduling`)](qiskit_ibm_runtime.transpiler.passes.scheduling) * [Fake Provider (`qiskit_ibm_runtime.fake_provider`)](fake_provider) ",repo/docs/api/qiskit-ibm-runtime/0.25\index.mdx "--- title: options description: API reference for qiskit_ibm_runtime.options in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_runtime.options --- # Primitive options `qiskit_ibm_runtime.options` Options that can be passed to the primitives. ## V2 Primitives `SamplerV2` and `EstimatorV2` each have their own options. You can use the `options` attribute to set the options. For example: ```python from qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2 service = QiskitRuntimeService() backend = service.least_busy(operational=True, simulator=False) estimator = EstimatorV2(backend=backend) estimator.options.resilience_level = 1 ``` You can also use the `update()` method to do bulk update. For example: ```python from qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2 service = QiskitRuntimeService() backend = service.least_busy(operational=True, simulator=False) estimator = EstimatorV2(backend=backend) estimator.options.update(resilience_level=1) ``` Refer to [`SamplerOptions`](qiskit_ibm_runtime.options.SamplerOptions ""qiskit_ibm_runtime.options.SamplerOptions"") and [`EstimatorOptions`](qiskit_ibm_runtime.options.EstimatorOptions ""qiskit_ibm_runtime.options.EstimatorOptions"") for V2 Sampler and V2 Estimator options, respectively. If an option is not specified, the server default value is used. The default values are subject to change. Refer to this current module’s documentation for the latest defaults. ## V1 Primitives The [`Options`](qiskit_ibm_runtime.options.Options ""qiskit_ibm_runtime.options.Options"") class encapsulates all the options you can specify when invoking a V1 primitive. It includes frequently used options, such as `optimization_level` and `resilience_level` as well as sub-categories, such as `transpilation` and `execution`. You can use auto-complete to easily find the options inside each sub-category, for example: ```python from qiskit_ibm_runtime.options import Options options = Options() options.transpilation.initial_layout = [0, 1, 2, 3] # This an be done using auto-complete ``` You can also pass dictionaries to each sub-category, for example: ```python from qiskit_ibm_runtime.options import Options options = Options(transpilation={""initial_layout"": [0, 1, 2, 3]}) ``` ## Classes | | | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`EstimatorOptions`](qiskit_ibm_runtime.options.EstimatorOptions ""qiskit_ibm_runtime.options.EstimatorOptions"")(\*args, \*\*kwargs) | Options for V2 Estimator. | | [`SamplerOptions`](qiskit_ibm_runtime.options.SamplerOptions ""qiskit_ibm_runtime.options.SamplerOptions"")(\*args, \*\*kwargs) | Options for V2 Sampler. | | [`DynamicalDecouplingOptions`](qiskit_ibm_runtime.options.DynamicalDecouplingOptions ""qiskit_ibm_runtime.options.DynamicalDecouplingOptions"")(\*args, \*\*kwargs) | Options for dynamical decoupling (DD). | | [`ResilienceOptionsV2`](qiskit_ibm_runtime.options.ResilienceOptionsV2 ""qiskit_ibm_runtime.options.ResilienceOptionsV2"")(\*args, \*\*kwargs) | Resilience options for V2 Estimator. | | [`LayerNoiseLearningOptions`](qiskit_ibm_runtime.options.LayerNoiseLearningOptions ""qiskit_ibm_runtime.options.LayerNoiseLearningOptions"")(\*args, \*\*kwargs) | Options for learning layer noise. | | [`MeasureNoiseLearningOptions`](qiskit_ibm_runtime.options.MeasureNoiseLearningOptions ""qiskit_ibm_runtime.options.MeasureNoiseLearningOptions"")(\*args, \*\*kwargs) | Options for measurement noise learning. | | [`PecOptions`](qiskit_ibm_runtime.options.PecOptions ""qiskit_ibm_runtime.options.PecOptions"")(\*args, \*\*kwargs) | Probabalistic error cancellation mitigation options. | | [`ZneOptions`](qiskit_ibm_runtime.options.ZneOptions ""qiskit_ibm_runtime.options.ZneOptions"")(\*args, \*\*kwargs) | Zero noise extrapolation mitigation options. | | [`TwirlingOptions`](qiskit_ibm_runtime.options.TwirlingOptions ""qiskit_ibm_runtime.options.TwirlingOptions"")(\*args, \*\*kwargs) | Twirling options. | | [`ExecutionOptionsV2`](qiskit_ibm_runtime.options.ExecutionOptionsV2 ""qiskit_ibm_runtime.options.ExecutionOptionsV2"")(\*args, \*\*kwargs) | Execution options for V2 primitives. | | [`Options`](qiskit_ibm_runtime.options.Options ""qiskit_ibm_runtime.options.Options"")(\[optimization\_level, ...]) | Options for the primitives, used by V1 primitives. | | [`TranspilationOptions`](qiskit_ibm_runtime.options.TranspilationOptions ""qiskit_ibm_runtime.options.TranspilationOptions"")(\*args, \*\*kwargs) | Transpilation options. | | [`ResilienceOptions`](qiskit_ibm_runtime.options.ResilienceOptions ""qiskit_ibm_runtime.options.ResilienceOptions"")(\*args, \*\*kwargs) | Resilience options for V1 primitives. | | [`ExecutionOptions`](qiskit_ibm_runtime.options.ExecutionOptions ""qiskit_ibm_runtime.options.ExecutionOptions"")(\*args, \*\*kwargs) | Execution options for V1 primitives. | | [`EnvironmentOptions`](qiskit_ibm_runtime.options.EnvironmentOptions ""qiskit_ibm_runtime.options.EnvironmentOptions"")(\*args, \*\*kwargs) | Options related to the execution environment. | | [`SimulatorOptions`](qiskit_ibm_runtime.options.SimulatorOptions ""qiskit_ibm_runtime.options.SimulatorOptions"")(\*args, \*\*kwargs) | Simulator options. | | [`SamplerExecutionOptionsV2`](qiskit_ibm_runtime.options.SamplerExecutionOptionsV2 ""qiskit_ibm_runtime.options.SamplerExecutionOptionsV2"")(\*args, \*\*kwargs) | Extension of [`ExecutionOptionsV2`](qiskit_ibm_runtime.options.ExecutionOptionsV2 ""qiskit_ibm_runtime.options.ExecutionOptionsV2"") for the sampler primitive. | ",repo/docs/api/qiskit-ibm-runtime/0.25\options.mdx "--- title: Batch description: API reference for qiskit_ibm_runtime.Batch in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.Batch --- # Batch Class for running jobs in batch execution mode. The `batch` mode is designed to efficiently perform experiments that comprise multiple independent jobs. **Using the `batch` mode provides the following benefits:** * The jobs’ classical computation, such as compilation, is run in parallel. Thus, running multiple jobs in a batch is significantly faster than running them serially. * There is usually minimal delay between job, which can help avoid drift. * If you partition your workload into multiple jobs and run them in `batch` mode, you can get results from individual jobs, which makes them more flexible to work with. For example, if a job’s results do not meet your expectations, you can cancel the remaining jobs, or simply re-submit that individual job and avoid re-running the entire workload. All jobs need to be provided at the outset. To submit iterative jobs, use the `session` mode instead. You can open a Qiskit Runtime batch by using this `Batch` class, then submit jobs to one or more primitives. For example: ```python from qiskit.circuit.random import random_circuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import Batch, SamplerV2 as Sampler, QiskitRuntimeService service = QiskitRuntimeService() backend = service.least_busy(operational=True, simulator=False) pm = generate_preset_pass_manager(backend=backend, optimization_level=1) # generate fifty unique three-qubit random circuits circuits = [pm.run(random_circuit(3, 2, measure=True)) for _ in range(50)] # split up the list of circuits into partitions max_circuits = 10 partitions = [circuits[i : i + max_circuits] for i in range(0, len(circuits), max_circuits)] # run the circuits in batched mode with Batch(backend=backend): sampler = Sampler() for partition in partitions: job = sampler.run(partition) pub_result = job.result()[0] print(f""Sampler job ID: {job.job_id()}"") print(f""Counts for the first PUB: {pub_result.data.cr.get_counts()}"") ``` For more details, check the “[Run jobs in a batch](/run/run-jobs-batch)” tutorial. Batch constructor. **Parameters** * **service** (`Optional`\[[`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")]) – Optional instance of the `QiskitRuntimeService` class. If `None`, the service associated with the backend, if known, is used. Otherwise `QiskitRuntimeService()` is used to initialize your default saved account. * **backend** (`Union`\[`str`, `BackendV1`, `BackendV2`, `None`]) – Optional instance of `Backend` class or backend string name. * **max\_time** (`Union`\[`int`, `str`, `None`]) – Maximum amount of time a runtime session can be open before being forcibly closed. Can be specified as seconds (int) or a string like “2h 30m 40s”. This value must be less than the [system imposed maximum](/run/max-execution-time). **Raises** **ValueError** – If an input value is invalid. ## Attributes ### service Return service associated with this session. **Return type** [`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"") **Returns** [`qiskit_ibm_runtime.QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.QiskitRuntimeService"") associated with this session. ### session\_id Return the session ID. **Return type** `Optional`\[`str`] **Returns** Session ID. None if the backend is a simulator. ## Methods ### backend Return backend for this session. **Return type** `Optional`\[`str`] **Returns** Backend for this session. None if unknown. ### cancel Cancel all pending jobs in a session. **Return type** `None` ### close Close the session so new jobs will no longer be accepted, but existing queued or running jobs will run to completion. The session will be terminated once there are no more pending jobs. **Return type** `None` ### details Return session details. **Return type** `Optional`\[`Dict`\[`str`, `Any`]] **Returns** A dictionary with the sessions details. * `id`: id of the session. * `backend_name`: backend used for the session. * `interactive_timeout`: The maximum idle time (in seconds) between jobs that is allowed to occur before the session is deactivated. * `max_time`: Maximum allowed time (in seconds) for the session, subject to plan limits. * `active_timeout`: The maximum time (in seconds) a session can stay active. * `state`: State of the session - open, active, inactive, or closed. * `accepting_jobs`: Whether or not the session is accepting jobs. * `last_job_started`: Timestamp of when the last job in the session started. * `last_job_completed`: Timestamp of when the last job in the session completed. * `started_at`: Timestamp of when the session was started. * `closed_at`: Timestamp of when the session was closed. * `activated_at`: Timestamp of when the session state was changed to active. * `mode`: Execution mode of the session. * `usage_time`: The usage time, in seconds, of this Session or Batch. Usage is defined as the time a quantum system is committed to complete a job. ### from\_id Construct a Session object with a given session\_id **Parameters** * **session\_id** (`str`) – the id of the session to be created. This must be an already existing session id. * **service** (`Optional`\[[`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")]) – **instance of the `QiskitRuntimeService` class.** If `None`, `QiskitRuntimeService()` is used to initialize your default saved account. **Raises:** IBMInputValueError: If given session\_id does not exist. **Return type** [`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session"") **Returns** A new Session with the given `session_id` ### run Run a program in the session. **Parameters** * **program\_id** (`str`) – Program ID. * **inputs** (`Dict`) – Program input parameters. These input values are passed to the runtime program. * **options** (`Optional`\[`Dict`]) – Runtime options that control the execution environment. See [`qiskit_ibm_runtime.RuntimeOptions`](qiskit_ibm_runtime.RuntimeOptions ""qiskit_ibm_runtime.RuntimeOptions"") for all available options. * **callback** (`Optional`\[`Callable`]) – Callback function to be invoked for any interim results and final result. **Return type** `Union`\[[`RuntimeJob`](qiskit_ibm_runtime.RuntimeJob ""qiskit_ibm_runtime.runtime_job.RuntimeJob""), [`RuntimeJobV2`](qiskit_ibm_runtime.RuntimeJobV2 ""qiskit_ibm_runtime.runtime_job_v2.RuntimeJobV2"")] **Returns** Submitted job. ### status Return current session status. **Return type** `Optional`\[`str`] **Returns** Session status as a string. * `Pending`: Session is created but not active. It will become active when the next job of this session is dequeued. * `In progress, accepting new jobs`: session is active and accepting new jobs. * `In progress, not accepting new jobs`: session is active and not accepting new jobs. * `Closed`: max\_time expired or session was explicitly closed. * `None`: status details are not available. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.Batch.mdx "--- title: Estimator description: API reference for qiskit_ibm_runtime.Estimator in_page_toc_min_heading_level: 1 python_api_type: attribute python_api_name: qiskit_ibm_runtime.Estimator --- # Estimator alias of [`EstimatorV1`](qiskit_ibm_runtime.EstimatorV1 ""qiskit_ibm_runtime.estimator.EstimatorV1"") ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.Estimator.mdx "--- title: EstimatorV1 description: API reference for qiskit_ibm_runtime.EstimatorV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.EstimatorV1 --- # EstimatorV1 Class for interacting with Qiskit Runtime Estimator primitive service. Qiskit Runtime Estimator primitive service estimates expectation values of quantum circuits and observables. The [`run()`](#qiskit_ibm_runtime.EstimatorV1.run ""qiskit_ibm_runtime.EstimatorV1.run"") can be used to submit circuits, observables, and parameters to the Estimator primitive. You are encouraged to use [`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.Session"") to open a session, during which you can invoke one or more primitives. Jobs submitted within a session are prioritized by the scheduler. Example: ```python from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import SparsePauliOp from qiskit_ibm_runtime import QiskitRuntimeService, Estimator service = QiskitRuntimeService(channel=""ibm_cloud"") psi1 = RealAmplitudes(num_qubits=2, reps=2) H1 = SparsePauliOp.from_list([(""II"", 1), (""IZ"", 2), (""XI"", 3)]) H2 = SparsePauliOp.from_list([(""IZ"", 1)]) H3 = SparsePauliOp.from_list([(""ZI"", 1), (""ZZ"", 1)]) with Session(service=service, backend=""ibmq_qasm_simulator"") as session: estimator = Estimator(session=session) theta1 = [0, 1, 1, 2, 3, 5] # calculate [ ] psi1_H1 = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta1]) print(psi1_H1.result()) # calculate [ , ] psi1_H23 = estimator.run( circuits=[psi1, psi1], observables=[H2, H3], parameter_values=[theta1]*2 ) print(psi1_H23.result()) ``` Initializes the Estimator primitive. **Parameters** * **backend** (`Union`\[`str`, [`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.ibm_backend.IBMBackend""), `None`]) – Backend to run the primitive. This can be a backend name or an [`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.IBMBackend"") instance. If a name is specified, the default account (e.g. `QiskitRuntimeService()`) is used. * **session** (`Optional`\[[`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session"")]) – Session in which to call the primitive. If both `session` and `backend` are specified, `session` takes precedence. If neither is specified, and the primitive is created inside a [`qiskit_ibm_runtime.Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.Session"") context manager, then the session is used. Otherwise if IBM Cloud channel is used, a default backend is selected. * **options** (`Union`\[`Dict`, [`Options`](qiskit_ibm_runtime.options.Options ""qiskit_ibm_runtime.options.options.Options""), `None`]) – Primitive options, see `Options` for detailed description. The `backend` keyword is still supported but is deprecated. ## Attributes ### options Return options values for the sampler. :rtype: `Options` :returns: options ### session Return session used by this primitive. **Return type** `Optional`\[[`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session"")] **Returns** Session used by this primitive, or `None` if session is not used. ### version ## Methods ### run Submit a request to the estimator primitive. **Parameters** * **circuits** (*QuantumCircuit | Sequence\[QuantumCircuit]*) – a (parameterized) `QuantumCircuit` or a list of (parameterized) `QuantumCircuit`. * **observables** (*Sequence\[BaseOperator | str] | BaseOperator | str*) – Observable objects. * **parameter\_values** (*Sequence\[float] | Sequence\[Sequence\[float]] | None*) – Concrete parameters to be bound. * **\*\*kwargs** – Individual options to overwrite the default primitive options. These include the runtime options in [`qiskit_ibm_runtime.RuntimeOptions`](qiskit_ibm_runtime.RuntimeOptions ""qiskit_ibm_runtime.RuntimeOptions""). **Return type** [RuntimeJob](qiskit_ibm_runtime.RuntimeJob ""qiskit_ibm_runtime.RuntimeJob"") **Returns** Submitted job. The result of the job is an instance of `qiskit.primitives.EstimatorResult`. **Raises** **ValueError** – Invalid arguments are given. ### set\_options Set options values for the sampler. **Parameters** **\*\*fields** – The fields to update the options **Return type** `None` ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.EstimatorV1.mdx "--- title: EstimatorV2 description: API reference for qiskit_ibm_runtime.EstimatorV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.EstimatorV2 --- # EstimatorV2 Class for interacting with Qiskit Runtime Estimator primitive service. Qiskit Runtime Estimator primitive service estimates expectation values of quantum circuits and observables. The [`run()`](#qiskit_ibm_runtime.EstimatorV2.run ""qiskit_ibm_runtime.EstimatorV2.run"") can be used to submit circuits, observables, and parameters to the Estimator primitive. Following construction, an estimator is used by calling its [`run()`](#qiskit_ibm_runtime.EstimatorV2.run ""qiskit_ibm_runtime.EstimatorV2.run"") method with a list of PUBs (Primitive Unified Blocs). Each PUB contains four values that, together, define a computation unit of work for the estimator to complete: * a single `QuantumCircuit`, possibly parametrized, whose final state we define as $\psi(\theta)$, * one or more observables (specified as any `ObservablesArrayLike`, including `Pauli`, `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$. * an optional target precision for expectation value estimates. Here is an example of how the estimator is used. ```python from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import SparsePauliOp from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2 as Estimator service = QiskitRuntimeService() backend = service.least_busy(operational=True, simulator=False) psi = RealAmplitudes(num_qubits=2, reps=2) hamiltonian = SparsePauliOp.from_list([(""II"", 1), (""IZ"", 2), (""XI"", 3)]) theta = [0, 1, 1, 2, 3, 5] pm = generate_preset_pass_manager(backend=backend, optimization_level=1) isa_psi = pm.run(psi) isa_observables = hamiltonian.apply_layout(isa_psi.layout) estimator = Estimator(backend=backend) # calculate [ ] job = estimator.run([(isa_psi, isa_observables, [theta])]) pub_result = job.result()[0] print(f""Expectation values: {pub_result.data.evs}"") ``` Initializes the Estimator primitive. **Parameters** * **mode** (`Union`\[`BackendV1`, `BackendV2`, [`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session""), [`Batch`](qiskit_ibm_runtime.Batch ""qiskit_ibm_runtime.batch.Batch""), `str`, `None`]) – The execution mode used to make the primitive query. It can be: * A `Backend` if you are using job mode. * A [`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.Session"") if you are using session execution mode. * A [`Batch`](qiskit_ibm_runtime.Batch ""qiskit_ibm_runtime.Batch"") if you are using batch execution mode. Refer to the [Qiskit Runtime documentation](/run). for more information about the `Execution modes`. * **backend** (`Union`\[`str`, `BackendV1`, `BackendV2`, `None`]) – Backend to run the primitive. This can be a backend name or an [`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.IBMBackend"") instance. If a name is specified, the default account (e.g. `QiskitRuntimeService()`) is used. * **session** (`Optional`\[[`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session"")]) – Session in which to call the primitive. If both `session` and `backend` are specified, `session` takes precedence. If neither is specified, and the primitive is created inside a [`qiskit_ibm_runtime.Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.Session"") context manager, then the session is used. Otherwise if IBM Cloud channel is used, a default backend is selected. * **options** (`Union`\[`Dict`, [`EstimatorOptions`](qiskit_ibm_runtime.options.EstimatorOptions ""qiskit_ibm_runtime.options.estimator_options.EstimatorOptions""), `None`]) – Estimator options, see `EstimatorOptions` for detailed description. **Raises** **NotImplementedError** – If “q-ctrl” channel strategy is used. ## Attributes ### mode Return the execution mode used by this primitive. **Return type** Optional\[[Session](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.Session"") | [Batch](qiskit_ibm_runtime.Batch ""qiskit_ibm_runtime.Batch"")] **Returns** Mode used by this primitive, or `None` if an execution mode is not used. ### options Return options **Return type** `TypeVar`(`OptionsT`, bound= `BaseOptions`) ### session Return session used by this primitive. **Return type** `Optional`\[[`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session"")] **Returns** Session used by this primitive, or `None` if session is not used. ### version ## Methods ### run Submit a request to the estimator primitive. **Parameters** * **pubs** (*Iterable\[EstimatorPubLike]*) – An iterable of pub-like (primitive unified bloc) objects, such as tuples `(circuit, observables)` or `(circuit, observables, parameter_values)`. * **precision** (*float | None*) – The target precision for expectation value estimates of each run Estimator Pub that does not specify its own precision. If None the estimator’s default precision value will be used. **Return type** [RuntimeJobV2](qiskit_ibm_runtime.RuntimeJobV2 ""qiskit_ibm_runtime.RuntimeJobV2"") **Returns** Submitted job. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.EstimatorV2.mdx "--- title: FakeAlgiers description: API reference for qiskit_ibm_runtime.fake_provider.FakeAlgiers in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeAlgiers --- # FakeAlgiers A fake 27 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeAlgiers.run ""qiskit_ibm_runtime.fake_provider.FakeAlgiers.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeAlgiers.mdx "--- title: FakeAlmaden description: API reference for qiskit_ibm_runtime.fake_provider.FakeAlmaden in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeAlmaden --- # FakeAlmaden A fake Almaden backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ 05 ↔ 06 ↔ 07 ↔ 08 ↔ 09 ↕ ↕ ↕ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↕ ↕ 15 ↔ 16 ↔ 17 ↔ 18 ↔ 19 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeAlmaden.run ""qiskit_ibm_runtime.fake_provider.FakeAlmaden.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeAlmaden.mdx "--- title: FakeAlmadenV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeAlmadenV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeAlmadenV2 --- # FakeAlmadenV2 A fake Almaden V2 backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ 05 ↔ 06 ↔ 07 ↔ 08 ↔ 09 ↕ ↕ ↕ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↕ ↕ 15 ↔ 16 ↔ 17 ↔ 18 ↔ 19 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeAlmadenV2.run ""qiskit_ibm_runtime.fake_provider.FakeAlmadenV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeAlmadenV2.mdx "--- title: FakeArmonk description: API reference for qiskit_ibm_runtime.fake_provider.FakeArmonk in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeArmonk --- # FakeArmonk A fake 1 qubit backend. ```python 0 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeArmonk.run ""qiskit_ibm_runtime.fake_provider.FakeArmonk.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeArmonk.mdx "--- title: FakeArmonkV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeArmonkV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeArmonkV2 --- # FakeArmonkV2 A fake 1 qubit backend. ```python 0 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeArmonkV2.run ""qiskit_ibm_runtime.fake_provider.FakeArmonkV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeArmonkV2.mdx "--- title: FakeAthens description: API reference for qiskit_ibm_runtime.fake_provider.FakeAthens in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeAthens --- # FakeAthens A fake 5 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeAthens.run ""qiskit_ibm_runtime.fake_provider.FakeAthens.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeAthens.mdx "--- title: FakeAthensV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeAthensV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeAthensV2 --- # FakeAthensV2 A fake 5 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeAthensV2.run ""qiskit_ibm_runtime.fake_provider.FakeAthensV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeAthensV2.mdx "--- title: FakeAuckland description: API reference for qiskit_ibm_runtime.fake_provider.FakeAuckland in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeAuckland --- # FakeAuckland A fake 27 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeAuckland.run ""qiskit_ibm_runtime.fake_provider.FakeAuckland.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeAuckland.mdx "--- title: FakeBelem description: API reference for qiskit_ibm_runtime.fake_provider.FakeBelem in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeBelem --- # FakeBelem A fake 5 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeBelem.run ""qiskit_ibm_runtime.fake_provider.FakeBelem.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeBelem.mdx "--- title: FakeBelemV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeBelemV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeBelemV2 --- # FakeBelemV2 A fake 5 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeBelemV2.run ""qiskit_ibm_runtime.fake_provider.FakeBelemV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeBelemV2.mdx "--- title: FakeBoeblingen description: API reference for qiskit_ibm_runtime.fake_provider.FakeBoeblingen in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeBoeblingen --- # FakeBoeblingen A fake Boeblingen backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ 05 ↔ 06 ↔ 07 ↔ 08 ↔ 09 ↕ ↕ ↕ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↕ ↕ 15 ↔ 16 ↔ 17 ↔ 18 ↔ 19 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeBoeblingen.run ""qiskit_ibm_runtime.fake_provider.FakeBoeblingen.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeBoeblingen.mdx "--- title: FakeBoeblingenV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeBoeblingenV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeBoeblingenV2 --- # FakeBoeblingenV2 A fake Boeblingen V2 backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ 05 ↔ 06 ↔ 07 ↔ 08 ↔ 09 ↕ ↕ ↕ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↕ ↕ 15 ↔ 16 ↔ 17 ↔ 18 ↔ 19 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeBoeblingenV2.run ""qiskit_ibm_runtime.fake_provider.FakeBoeblingenV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeBoeblingenV2.mdx "--- title: FakeBogota description: API reference for qiskit_ibm_runtime.fake_provider.FakeBogota in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeBogota --- # FakeBogota A fake 5 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeBogota.run ""qiskit_ibm_runtime.fake_provider.FakeBogota.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeBogota.mdx "--- title: FakeBogotaV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeBogotaV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeBogotaV2 --- # FakeBogotaV2 A fake 5 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeBogotaV2.run ""qiskit_ibm_runtime.fake_provider.FakeBogotaV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeBogotaV2.mdx "--- title: FakeBrisbane description: API reference for qiskit_ibm_runtime.fake_provider.FakeBrisbane in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeBrisbane --- # FakeBrisbane A fake 127 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeBrisbane.run ""qiskit_ibm_runtime.fake_provider.FakeBrisbane.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeBrisbane.mdx "--- title: FakeBrooklyn description: API reference for qiskit_ibm_runtime.fake_provider.FakeBrooklyn in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeBrooklyn --- # FakeBrooklyn A fake Brooklyn backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeBrooklyn.run ""qiskit_ibm_runtime.fake_provider.FakeBrooklyn.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeBrooklyn.mdx "--- title: FakeBrooklynV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeBrooklynV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeBrooklynV2 --- # FakeBrooklynV2 A fake Brooklyn V2 backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeBrooklynV2.run ""qiskit_ibm_runtime.fake_provider.FakeBrooklynV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeBrooklynV2.mdx "--- title: FakeBurlington description: API reference for qiskit_ibm_runtime.fake_provider.FakeBurlington in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeBurlington --- # FakeBurlington A fake 5 qubit backend. ```python 0 ↔ 1 ↔ 3 ↔ 4 ↕ 2 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeBurlington.run ""qiskit_ibm_runtime.fake_provider.FakeBurlington.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeBurlington.mdx "--- title: FakeBurlingtonV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeBurlingtonV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeBurlingtonV2 --- # FakeBurlingtonV2 A fake 5 qubit backend. ```python 0 ↔ 1 ↔ 3 ↔ 4 ↕ 2 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeBurlingtonV2.run ""qiskit_ibm_runtime.fake_provider.FakeBurlingtonV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeBurlingtonV2.mdx "--- title: FakeCairo description: API reference for qiskit_ibm_runtime.fake_provider.FakeCairo in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeCairo --- # FakeCairo A fake 27 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeCairo.run ""qiskit_ibm_runtime.fake_provider.FakeCairo.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeCairo.mdx "--- title: FakeCairoV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeCairoV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeCairoV2 --- # FakeCairoV2 A fake 27 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeCairoV2.run ""qiskit_ibm_runtime.fake_provider.FakeCairoV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeCairoV2.mdx "--- title: FakeCambridge description: API reference for qiskit_ibm_runtime.fake_provider.FakeCambridge in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeCambridge --- # FakeCambridge A fake Cambridge backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ 05 06 ↕ ↕ 07 ↔ 08 ↔ 09 ↔ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↔ 15 ↕ ↕ ↕ 16 17 18 ↕ ↕ ↕ 19 ↔ 20 ↔ 21 ↔ 22 ↔ 23 ↔ 24 ↔ 25 ↔ 26 ↔ 27 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeCambridge.run ""qiskit_ibm_runtime.fake_provider.FakeCambridge.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeCambridge.mdx "--- title: FakeCambridgeV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeCambridgeV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeCambridgeV2 --- # FakeCambridgeV2 A fake Cambridge backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ 05 06 ↕ ↕ 07 ↔ 08 ↔ 09 ↔ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↔ 15 ↕ ↕ ↕ 16 17 18 ↕ ↕ ↕ 19 ↔ 20 ↔ 21 ↔ 22 ↔ 23 ↔ 24 ↔ 25 ↔ 26 ↔ 27 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeCambridgeV2.run ""qiskit_ibm_runtime.fake_provider.FakeCambridgeV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeCambridgeV2.mdx "--- title: FakeCasablanca description: API reference for qiskit_ibm_runtime.fake_provider.FakeCasablanca in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeCasablanca --- # FakeCasablanca A fake 7 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeCasablanca.run ""qiskit_ibm_runtime.fake_provider.FakeCasablanca.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeCasablanca.mdx "--- title: FakeCasablancaV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeCasablancaV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeCasablancaV2 --- # FakeCasablancaV2 A fake 7 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeCasablancaV2.run ""qiskit_ibm_runtime.fake_provider.FakeCasablancaV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeCasablancaV2.mdx "--- title: FakeCusco description: API reference for qiskit_ibm_runtime.fake_provider.FakeCusco in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeCusco --- # FakeCusco A fake 127 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeCusco.run ""qiskit_ibm_runtime.fake_provider.FakeCusco.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeCusco.mdx "--- title: FakeEssex description: API reference for qiskit_ibm_runtime.fake_provider.FakeEssex in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeEssex --- # FakeEssex A fake 5 qubit backend. ```python 0 ↔ 1 ↔ 2 ↕ 3 ↕ 4 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeEssex.run ""qiskit_ibm_runtime.fake_provider.FakeEssex.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeEssex.mdx "--- title: FakeEssexV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeEssexV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeEssexV2 --- # FakeEssexV2 A fake 5 qubit backend. ```python 0 ↔ 1 ↔ 2 ↕ 3 ↕ 4 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeEssexV2.run ""qiskit_ibm_runtime.fake_provider.FakeEssexV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeEssexV2.mdx "--- title: FakeFractionalBackend description: API reference for qiskit_ibm_runtime.fake_provider.FakeFractionalBackend in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeFractionalBackend --- # FakeFractionalBackend A fake 5 qubit backend with dynamic and fractional feature modeled based on FakeLima. This backend include following features. * Fractional gates (rx, rzx) in addition to the standard basis gates. * Control flow operations (if\_else, while\_loop). * Pulse calibrations (fractional gates don’t support calibration). * Gate properties of all instructions. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeFractionalBackend.run ""qiskit_ibm_runtime.fake_provider.FakeFractionalBackend.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeFractionalBackend.mdx "--- title: FakeGeneva description: API reference for qiskit_ibm_runtime.fake_provider.FakeGeneva in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeGeneva --- # FakeGeneva A fake 27 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeGeneva.run ""qiskit_ibm_runtime.fake_provider.FakeGeneva.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeGeneva.mdx "--- title: FakeGuadalupe description: API reference for qiskit_ibm_runtime.fake_provider.FakeGuadalupe in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeGuadalupe --- # FakeGuadalupe A fake 16 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeGuadalupe.run ""qiskit_ibm_runtime.fake_provider.FakeGuadalupe.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeGuadalupe.mdx "--- title: FakeGuadalupeV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeGuadalupeV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeGuadalupeV2 --- # FakeGuadalupeV2 A fake 16 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeGuadalupeV2.run ""qiskit_ibm_runtime.fake_provider.FakeGuadalupeV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeGuadalupeV2.mdx "--- title: FakeHanoi description: API reference for qiskit_ibm_runtime.fake_provider.FakeHanoi in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeHanoi --- # FakeHanoi A fake 27 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeHanoi.run ""qiskit_ibm_runtime.fake_provider.FakeHanoi.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeHanoi.mdx "--- title: FakeHanoiV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeHanoiV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeHanoiV2 --- # FakeHanoiV2 A fake 27 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeHanoiV2.run ""qiskit_ibm_runtime.fake_provider.FakeHanoiV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeHanoiV2.mdx "--- title: FakeJakarta description: API reference for qiskit_ibm_runtime.fake_provider.FakeJakarta in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeJakarta --- # FakeJakarta A fake 7 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeJakarta.run ""qiskit_ibm_runtime.fake_provider.FakeJakarta.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeJakarta.mdx "--- title: FakeJakartaV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeJakartaV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeJakartaV2 --- # FakeJakartaV2 A fake 7 qubit V2 backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeJakartaV2.run ""qiskit_ibm_runtime.fake_provider.FakeJakartaV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeJakartaV2.mdx "--- title: FakeJohannesburg description: API reference for qiskit_ibm_runtime.fake_provider.FakeJohannesburg in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeJohannesburg --- # FakeJohannesburg A fake Johannesburg backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ 05 ↔ 06 ↔ 07 ↔ 08 ↔ 09 ↕ ↕ ↕ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↕ ↕ 15 ↔ 16 ↔ 17 ↔ 18 ↔ 19 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeJohannesburg.run ""qiskit_ibm_runtime.fake_provider.FakeJohannesburg.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeJohannesburg.mdx "--- title: FakeJohannesburgV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeJohannesburgV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeJohannesburgV2 --- # FakeJohannesburgV2 A fake Johannesburg V2 backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ 05 ↔ 06 ↔ 07 ↔ 08 ↔ 09 ↕ ↕ ↕ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↕ ↕ 15 ↔ 16 ↔ 17 ↔ 18 ↔ 19 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeJohannesburgV2.run ""qiskit_ibm_runtime.fake_provider.FakeJohannesburgV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeJohannesburgV2.mdx "--- title: FakeKawasaki description: API reference for qiskit_ibm_runtime.fake_provider.FakeKawasaki in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeKawasaki --- # FakeKawasaki A fake 127 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeKawasaki.run ""qiskit_ibm_runtime.fake_provider.FakeKawasaki.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeKawasaki.mdx "--- title: FakeKolkata description: API reference for qiskit_ibm_runtime.fake_provider.FakeKolkata in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeKolkata --- # FakeKolkata A fake 27 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeKolkata.run ""qiskit_ibm_runtime.fake_provider.FakeKolkata.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeKolkata.mdx "--- title: FakeKolkataV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeKolkataV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeKolkataV2 --- # FakeKolkataV2 A fake 27 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeKolkataV2.run ""qiskit_ibm_runtime.fake_provider.FakeKolkataV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeKolkataV2.mdx "--- title: FakeKyiv description: API reference for qiskit_ibm_runtime.fake_provider.FakeKyiv in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeKyiv --- # FakeKyiv A fake 127 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeKyiv.run ""qiskit_ibm_runtime.fake_provider.FakeKyiv.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeKyiv.mdx "--- title: FakeKyoto description: API reference for qiskit_ibm_runtime.fake_provider.FakeKyoto in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeKyoto --- # FakeKyoto A fake 127 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeKyoto.run ""qiskit_ibm_runtime.fake_provider.FakeKyoto.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeKyoto.mdx "--- title: FakeLagos description: API reference for qiskit_ibm_runtime.fake_provider.FakeLagos in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeLagos --- # FakeLagos A fake 7 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeLagos.run ""qiskit_ibm_runtime.fake_provider.FakeLagos.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeLagos.mdx "--- title: FakeLagosV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeLagosV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeLagosV2 --- # FakeLagosV2 A fake 7 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeLagosV2.run ""qiskit_ibm_runtime.fake_provider.FakeLagosV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeLagosV2.mdx "--- title: FakeLima description: API reference for qiskit_ibm_runtime.fake_provider.FakeLima in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeLima --- # FakeLima A fake 5 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeLima.run ""qiskit_ibm_runtime.fake_provider.FakeLima.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeLima.mdx "--- title: FakeLimaV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeLimaV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeLimaV2 --- # FakeLimaV2 A fake 5 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeLimaV2.run ""qiskit_ibm_runtime.fake_provider.FakeLimaV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeLimaV2.mdx "--- title: FakeLondon description: API reference for qiskit_ibm_runtime.fake_provider.FakeLondon in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeLondon --- # FakeLondon A fake 5 qubit backend. ```python 0 ↔ 1 ↔ 2 ↕ 3 ↕ 4 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeLondon.run ""qiskit_ibm_runtime.fake_provider.FakeLondon.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeLondon.mdx "--- title: FakeLondonV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeLondonV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeLondonV2 --- # FakeLondonV2 A fake 5 qubit backend. ```python 0 ↔ 1 ↔ 2 ↕ 3 ↕ 4 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeLondonV2.run ""qiskit_ibm_runtime.fake_provider.FakeLondonV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeLondonV2.mdx "--- title: FakeManhattan description: API reference for qiskit_ibm_runtime.fake_provider.FakeManhattan in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeManhattan --- # FakeManhattan A fake Manhattan backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeManhattan.run ""qiskit_ibm_runtime.fake_provider.FakeManhattan.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeManhattan.mdx "--- title: FakeManhattanV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeManhattanV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeManhattanV2 --- # FakeManhattanV2 A fake Manhattan backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeManhattanV2.run ""qiskit_ibm_runtime.fake_provider.FakeManhattanV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeManhattanV2.mdx "--- title: FakeManila description: API reference for qiskit_ibm_runtime.fake_provider.FakeManila in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeManila --- # FakeManila A fake 5 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeManila.run ""qiskit_ibm_runtime.fake_provider.FakeManila.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeManila.mdx "--- title: FakeManilaV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeManilaV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeManilaV2 --- # FakeManilaV2 A fake 5 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeManilaV2.run ""qiskit_ibm_runtime.fake_provider.FakeManilaV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeManilaV2.mdx "--- title: FakeMelbourne description: API reference for qiskit_ibm_runtime.fake_provider.FakeMelbourne in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeMelbourne --- # FakeMelbourne A fake 14 qubit backend. ```python 0 ← 1 → 2 → 3 ← 4 ← 5 → 6 ↑ ↑ ↑ ↓ ↓ ↓ 13 → 12 ← 11 → 10 ← 9 → 8 ← 7 ``` ## Attributes ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeMelbourne.run ""qiskit_ibm_runtime.fake_provider.FakeMelbourne.run"") method. ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeMelbourne.mdx "--- title: FakeMelbourneV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeMelbourneV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeMelbourneV2 --- # FakeMelbourneV2 A fake 14 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeMelbourneV2.run ""qiskit_ibm_runtime.fake_provider.FakeMelbourneV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeMelbourneV2.mdx "--- title: FakeMontreal description: API reference for qiskit_ibm_runtime.fake_provider.FakeMontreal in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeMontreal --- # FakeMontreal A fake 27 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeMontreal.run ""qiskit_ibm_runtime.fake_provider.FakeMontreal.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeMontreal.mdx "--- title: FakeMontrealV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeMontrealV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeMontrealV2 --- # FakeMontrealV2 A fake 27 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeMontrealV2.run ""qiskit_ibm_runtime.fake_provider.FakeMontrealV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeMontrealV2.mdx "--- title: FakeMumbai description: API reference for qiskit_ibm_runtime.fake_provider.FakeMumbai in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeMumbai --- # FakeMumbai A fake 27 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeMumbai.run ""qiskit_ibm_runtime.fake_provider.FakeMumbai.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeMumbai.mdx "--- title: FakeMumbaiV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeMumbaiV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeMumbaiV2 --- # FakeMumbaiV2 A fake 27 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeMumbaiV2.run ""qiskit_ibm_runtime.fake_provider.FakeMumbaiV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeMumbaiV2.mdx "--- title: FakeNairobi description: API reference for qiskit_ibm_runtime.fake_provider.FakeNairobi in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeNairobi --- # FakeNairobi A fake 7 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeNairobi.run ""qiskit_ibm_runtime.fake_provider.FakeNairobi.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeNairobi.mdx "--- title: FakeNairobiV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeNairobiV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeNairobiV2 --- # FakeNairobiV2 A fake 7 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeNairobiV2.run ""qiskit_ibm_runtime.fake_provider.FakeNairobiV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeNairobiV2.mdx "--- title: FakeOsaka description: API reference for qiskit_ibm_runtime.fake_provider.FakeOsaka in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeOsaka --- # FakeOsaka A fake 127 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeOsaka.run ""qiskit_ibm_runtime.fake_provider.FakeOsaka.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeOsaka.mdx "--- title: FakeOslo description: API reference for qiskit_ibm_runtime.fake_provider.FakeOslo in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeOslo --- # FakeOslo A fake 7 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeOslo.run ""qiskit_ibm_runtime.fake_provider.FakeOslo.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeOslo.mdx "--- title: FakeOurense description: API reference for qiskit_ibm_runtime.fake_provider.FakeOurense in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeOurense --- # FakeOurense A fake 5 qubit backend. ```python 0 ↔ 1 ↔ 3 ↔ 4 ↕ 2 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeOurense.run ""qiskit_ibm_runtime.fake_provider.FakeOurense.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeOurense.mdx "--- title: FakeOurenseV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeOurenseV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeOurenseV2 --- # FakeOurenseV2 A fake 5 qubit backend. ```python 0 ↔ 1 ↔ 3 ↔ 4 ↕ 2 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeOurenseV2.run ""qiskit_ibm_runtime.fake_provider.FakeOurenseV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeOurenseV2.mdx "--- title: FakeParis description: API reference for qiskit_ibm_runtime.fake_provider.FakeParis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeParis --- # FakeParis A fake Paris backend. ```python 06 17 ↕ ↕ 00 ↔ 01 ↔ 04 ↔ 07 ↔ 10 ↔ 12 ↔ 15 ↔ 18 ↔ 20 ↔ 23 ↕ ↕ ↕ 02 13 24 ↕ ↕ ↕ 03 ↔ 05 ↔ 08 ↔ 11 ↔ 14 ↔ 16 ↔ 19 ↔ 22 ↔ 25 ↔ 26 ↕ ↕ 09 20 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeParis.run ""qiskit_ibm_runtime.fake_provider.FakeParis.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeParis.mdx "--- title: FakeParisV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeParisV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeParisV2 --- # FakeParisV2 A fake Paris backend. ```python 06 17 ↕ ↕ 00 ↔ 01 ↔ 04 ↔ 07 ↔ 10 ↔ 12 ↔ 15 ↔ 18 ↔ 20 ↔ 23 ↕ ↕ ↕ 02 13 24 ↕ ↕ ↕ 03 ↔ 05 ↔ 08 ↔ 11 ↔ 14 ↔ 16 ↔ 19 ↔ 22 ↔ 25 ↔ 26 ↕ ↕ 09 20 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeParisV2.run ""qiskit_ibm_runtime.fake_provider.FakeParisV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeParisV2.mdx "--- title: FakePeekskill description: API reference for qiskit_ibm_runtime.fake_provider.FakePeekskill in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakePeekskill --- # FakePeekskill A fake 27 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakePeekskill.run ""qiskit_ibm_runtime.fake_provider.FakePeekskill.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakePeekskill.mdx "--- title: FakePerth description: API reference for qiskit_ibm_runtime.fake_provider.FakePerth in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakePerth --- # FakePerth A fake 7 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakePerth.run ""qiskit_ibm_runtime.fake_provider.FakePerth.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakePerth.mdx "--- title: FakePoughkeepsie description: API reference for qiskit_ibm_runtime.fake_provider.FakePoughkeepsie in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakePoughkeepsie --- # FakePoughkeepsie A fake Poughkeepsie backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ 05 ↔ 06 ↔ 07 ↔ 08 ↔ 09 ↕ ↕ ↕ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↕ ↕ 15 ↔ 16 ↔ 17 ↔ 18 ↔ 19 ``` ## Attributes ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakePoughkeepsie.run ""qiskit_ibm_runtime.fake_provider.FakePoughkeepsie.run"") method. ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakePoughkeepsie.mdx "--- title: FakePoughkeepsieV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakePoughkeepsieV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakePoughkeepsieV2 --- # FakePoughkeepsieV2 A fake Poughkeepsie backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakePoughkeepsieV2.run ""qiskit_ibm_runtime.fake_provider.FakePoughkeepsieV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakePoughkeepsieV2.mdx "--- title: FakePrague description: API reference for qiskit_ibm_runtime.fake_provider.FakePrague in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakePrague --- # FakePrague A fake 33 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakePrague.run ""qiskit_ibm_runtime.fake_provider.FakePrague.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakePrague.mdx "--- title: FakeProvider description: API reference for qiskit_ibm_runtime.fake_provider.FakeProvider in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeProvider --- # FakeProvider Fake provider containing fake V1 backends. Only filtering backends by name is implemented. This class contains all fake V1 backends available in the [`qiskit_ibm_runtime.fake_provider`](fake_provider#module-qiskit_ibm_runtime.fake_provider ""qiskit_ibm_runtime.fake_provider""). The class `qiskit.providers.provider.Provider` is deprecated as of qiskit 1.1. It will be removed no earlier than 3 months after the release date. The abstract Provider and ProviderV1 classes are deprecated and will be removed in 2.0. You can just remove it as the parent class and a get\_backend method that returns the backends from self.backend. ## Attributes ### version ## Methods ### backends Return a list of backends matching the specified filtering. **Parameters** * **name** (*str*) – name of the backend. * **\*\*kwargs** – dict used for filtering. **Returns** **a list of Backends that match the filtering** criteria. **Return type** list\[Backend] ### get\_backend Return a single backend matching the specified filtering. The method `qiskit.providers.provider.ProviderV1.get_backend()` is deprecated as of qiskit 1.1. It will be removed no earlier than 3 months after the release date. The abstract Provider and ProviderV1 classes are deprecated and will be removed in 2.0. You can just remove it as the parent class and a get\_backend method that returns the backends from self.backend. **Parameters** * **name** (*str*) – name of the backend. * **\*\*kwargs** – dict used for filtering. **Returns** a backend matching the filtering. **Return type** Backend **Raises** **QiskitBackendNotFoundError** – if no backend could be found or more than one backend matches the filtering criteria. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeProvider.mdx "--- title: FakeProviderForBackendV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeProviderForBackendV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeProviderForBackendV2 --- # FakeProviderForBackendV2 Fake provider containing fake V2 backends. Only filtering backends by name is implemented. This class contains all fake V2 backends available in the [`qiskit_ibm_runtime.fake_provider`](fake_provider#module-qiskit_ibm_runtime.fake_provider ""qiskit_ibm_runtime.fake_provider""). ## Methods ### backend Filter backends in provider by name. **Return type** `FakeBackendV2` ### backends Return all backends accessible via this account. **Return type** `List`\[`FakeBackendV2`] ### get\_backend Return a single backend matching the specified filtering. **Return type** `FakeBackendV2` ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeProviderForBackendV2.mdx "--- title: FakeQuebec description: API reference for qiskit_ibm_runtime.fake_provider.FakeQuebec in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeQuebec --- # FakeQuebec A fake 127 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeQuebec.run ""qiskit_ibm_runtime.fake_provider.FakeQuebec.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeQuebec.mdx "--- title: FakeQuito description: API reference for qiskit_ibm_runtime.fake_provider.FakeQuito in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeQuito --- # FakeQuito A fake 5 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeQuito.run ""qiskit_ibm_runtime.fake_provider.FakeQuito.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeQuito.mdx "--- title: FakeQuitoV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeQuitoV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeQuitoV2 --- # FakeQuitoV2 A fake 5 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeQuitoV2.run ""qiskit_ibm_runtime.fake_provider.FakeQuitoV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeQuitoV2.mdx "--- title: FakeRochester description: API reference for qiskit_ibm_runtime.fake_provider.FakeRochester in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeRochester --- # FakeRochester A fake Rochester backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeRochester.run ""qiskit_ibm_runtime.fake_provider.FakeRochester.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeRochester.mdx "--- title: FakeRochesterV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeRochesterV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeRochesterV2 --- # FakeRochesterV2 A fake Rochester backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeRochesterV2.run ""qiskit_ibm_runtime.fake_provider.FakeRochesterV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeRochesterV2.mdx "--- title: FakeRome description: API reference for qiskit_ibm_runtime.fake_provider.FakeRome in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeRome --- # FakeRome A fake 5 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeRome.run ""qiskit_ibm_runtime.fake_provider.FakeRome.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeRome.mdx "--- title: FakeRomeV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeRomeV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeRomeV2 --- # FakeRomeV2 A fake 5 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeRomeV2.run ""qiskit_ibm_runtime.fake_provider.FakeRomeV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeRomeV2.mdx "--- title: FakeRueschlikon description: API reference for qiskit_ibm_runtime.fake_provider.FakeRueschlikon in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeRueschlikon --- # FakeRueschlikon A fake 16 qubit backend. ```python 1 → 2 → 3 → 4 ← 5 ← 6 → 7 ← 8 ↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑ 0 ← 15 → 14 ← 13 ← 12 → 11 → 10 ← 9 ``` ## Attributes ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeRueschlikon.run ""qiskit_ibm_runtime.fake_provider.FakeRueschlikon.run"") method. ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Return backend properties ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeRueschlikon.mdx "--- title: FakeSantiago description: API reference for qiskit_ibm_runtime.fake_provider.FakeSantiago in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeSantiago --- # FakeSantiago A fake Santiago backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeSantiago.run ""qiskit_ibm_runtime.fake_provider.FakeSantiago.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeSantiago.mdx "--- title: FakeSantiagoV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeSantiagoV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeSantiagoV2 --- # FakeSantiagoV2 A fake Santiago backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeSantiagoV2.run ""qiskit_ibm_runtime.fake_provider.FakeSantiagoV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeSantiagoV2.mdx "--- title: FakeSherbrooke description: API reference for qiskit_ibm_runtime.fake_provider.FakeSherbrooke in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeSherbrooke --- # FakeSherbrooke A fake 127 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeSherbrooke.run ""qiskit_ibm_runtime.fake_provider.FakeSherbrooke.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeSherbrooke.mdx "--- title: FakeSingapore description: API reference for qiskit_ibm_runtime.fake_provider.FakeSingapore in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeSingapore --- # FakeSingapore A fake Singapore backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ 05 ↔ 06 ↔ 07 ↔ 08 ↔ 09 ↕ ↕ ↕ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↕ ↕ 15 ↔ 16 ↔ 17 ↔ 18 ↔ 19 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeSingapore.run ""qiskit_ibm_runtime.fake_provider.FakeSingapore.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeSingapore.mdx "--- title: FakeSingaporeV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeSingaporeV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeSingaporeV2 --- # FakeSingaporeV2 A fake Singapore backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ 05 ↔ 06 ↔ 07 ↔ 08 ↔ 09 ↕ ↕ ↕ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↕ ↕ 15 ↔ 16 ↔ 17 ↔ 18 ↔ 19 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeSingaporeV2.run ""qiskit_ibm_runtime.fake_provider.FakeSingaporeV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeSingaporeV2.mdx "--- title: FakeSydney description: API reference for qiskit_ibm_runtime.fake_provider.FakeSydney in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeSydney --- # FakeSydney A fake 27 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeSydney.run ""qiskit_ibm_runtime.fake_provider.FakeSydney.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeSydney.mdx "--- title: FakeSydneyV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeSydneyV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeSydneyV2 --- # FakeSydneyV2 A fake 27 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeSydneyV2.run ""qiskit_ibm_runtime.fake_provider.FakeSydneyV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeSydneyV2.mdx "--- title: FakeTenerife description: API reference for qiskit_ibm_runtime.fake_provider.FakeTenerife in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeTenerife --- # FakeTenerife A fake 5 qubit backend. ```python 1 ↙ ↑ 0 ← 2 ← 3 ↑ ↙ 4 ``` ## Attributes ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeTenerife.run ""qiskit_ibm_runtime.fake_provider.FakeTenerife.run"") method. ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties as recorded on 8/30/19. **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeTenerife.mdx "--- title: FakeTokyo description: API reference for qiskit_ibm_runtime.fake_provider.FakeTokyo in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeTokyo --- # FakeTokyo A fake 20 qubit backend. ```python 00 ↔ 01 ↔ 02 ↔ 03 ↔ 04 ↕ ↕ ↕ ↕ ⤫ ↕ 05 ↔ 06 ↔ 07 ↔ 08 ↔ 09 ↕ ⤫ ↕ ↕ ⤫ ↕ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↕ ↕ ⤫ ↕ ⤫ ↕ 15 ↔ 16 ↔ 17 18 19 ``` ## Attributes ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeTokyo.run ""qiskit_ibm_runtime.fake_provider.FakeTokyo.run"") method. ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties as recorded on 8/30/19. **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeTokyo.mdx "--- title: FakeTorino description: API reference for qiskit_ibm_runtime.fake_provider.FakeTorino in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeTorino --- # FakeTorino A fake 133 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeTorino.run ""qiskit_ibm_runtime.fake_provider.FakeTorino.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeTorino.mdx "--- title: FakeToronto description: API reference for qiskit_ibm_runtime.fake_provider.FakeToronto in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeToronto --- # FakeToronto A fake 27 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeToronto.run ""qiskit_ibm_runtime.fake_provider.FakeToronto.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeToronto.mdx "--- title: FakeTorontoV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeTorontoV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeTorontoV2 --- # FakeTorontoV2 A fake 27 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeTorontoV2.run ""qiskit_ibm_runtime.fake_provider.FakeTorontoV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeTorontoV2.mdx "--- title: FakeValencia description: API reference for qiskit_ibm_runtime.fake_provider.FakeValencia in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeValencia --- # FakeValencia A fake 5 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeValencia.run ""qiskit_ibm_runtime.fake_provider.FakeValencia.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeValencia.mdx "--- title: FakeValenciaV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeValenciaV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeValenciaV2 --- # FakeValenciaV2 A fake 5 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeValenciaV2.run ""qiskit_ibm_runtime.fake_provider.FakeValenciaV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeValenciaV2.mdx "--- title: FakeVigo description: API reference for qiskit_ibm_runtime.fake_provider.FakeVigo in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeVigo --- # FakeVigo A fake 5 qubit backend. ```python 0 ↔ 1 ↔ 3 ↔ 4 ↕ 2 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeVigo.run ""qiskit_ibm_runtime.fake_provider.FakeVigo.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeVigo.mdx "--- title: FakeVigoV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeVigoV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeVigoV2 --- # FakeVigoV2 A fake 5 qubit backend. ```python 0 ↔ 1 ↔ 3 ↔ 4 ↕ 2 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeVigoV2.run ""qiskit_ibm_runtime.fake_provider.FakeVigoV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeVigoV2.mdx "--- title: FakeWashington description: API reference for qiskit_ibm_runtime.fake_provider.FakeWashington in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeWashington --- # FakeWashington A fake 127 qubit backend. FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### defs\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeWashington.run ""qiskit_ibm_runtime.fake_provider.FakeWashington.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### defaults Returns a snapshot of device defaults **Return type** `PulseDefaults` ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeWashington.mdx "--- title: FakeWashingtonV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeWashingtonV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeWashingtonV2 --- # FakeWashingtonV2 A fake 127 qubit backend. FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeWashingtonV2.run ""qiskit_ibm_runtime.fake_provider.FakeWashingtonV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeWashingtonV2.mdx "--- title: FakeYorktown description: API reference for qiskit_ibm_runtime.fake_provider.FakeYorktown in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeYorktown --- # FakeYorktown A fake 5 qubit backend. ```python 1 / | 0 - 2 - 3 | / 4 ``` FakeBackend initializer. **Parameters** * **configuration** (*BackendConfiguration*) – backend configuration * **time\_alive** (*int*) – time to wait before returning result ## Attributes ### backend\_name ### conf\_filename ### dirname ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeYorktown.run ""qiskit_ibm_runtime.fake_provider.FakeYorktown.run"") method. ### props\_filename ### version ## Methods ### configuration Return the backend configuration. **Returns** the configuration for the backend. **Return type** BackendConfiguration ### name Return the backend name. **Returns** the name of the backend. **Return type** str ### properties Returns a snapshot of device properties **Return type** `BackendProperties` ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### run Main job in simulator ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. **Returns** the status of the backend. **Return type** BackendStatus ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeYorktown.mdx "--- title: FakeYorktownV2 description: API reference for qiskit_ibm_runtime.fake_provider.FakeYorktownV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.fake_provider.FakeYorktownV2 --- # FakeYorktownV2 A fake 5 qubit backend. ```python 1 / | 0 - 2 - 3 | / 4 ``` FakeBackendV2 initializer. ## Attributes ### backend\_name ### conf\_filename ### coupling\_map Return the `CouplingMap` object ### defs\_filename ### dirname ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Return type** `float` **Returns** The output signal timestep in seconds. ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits **Return type** `None` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Return type** `List`\[`List`\[`int`]] **Returns** The grouping of measurements which are multiplexed ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.fake_provider.FakeYorktownV2.run ""qiskit_ibm_runtime.fake_provider.FakeYorktownV2.run"") method. ### props\_filename ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### target A `qiskit.transpiler.Target` object for the backend. **Return type** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### acquire\_channel Return the acquisition channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. This is required to be implemented if the backend supports Pulse scheduling. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The multi qubit control line. **Return type** List\[ControlChannel] ### drive\_channel Return the drive channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit drive channel **Return type** DriveChannel ### measure\_channel Return the measure stimulus channel for the given qubit. This is required to be implemented if the backend supports Pulse scheduling. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### refresh Update the data files from its real counterpart This method pulls the latest backend data files from their real counterpart and overwrites the corresponding files in the local installation: \* ../fake\_provider/backends/\{backend\_name}/conf\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/defs\_\{backend\_name}.json \* ../fake\_provider/backends/\{backend\_name}/props\_\{backend\_name}.json **The new data files will persist through sessions so the files will stay updated unless they** are manually reverted locally or when qiskit-ibm-runtime is upgraded/reinstalled. **Parameters** **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – A `QiskitRuntimeService` instance **Raises** **Exception** – If the real target doesn’t exist or can’t be accessed **Return type** `None` ### run Run on the fake backend using a simulator. This method runs circuit jobs (an individual or a list of QuantumCircuit ) and pulse jobs (an individual or a list of Schedule or ScheduleBlock) using BasicSimulator or Aer simulator and returns a `Job` object. If qiskit-aer is installed, jobs will be run using AerSimulator with noise model of the fake backend. Otherwise, jobs will be run using BasicSimulator without noise. Currently noisy simulation of a pulse job is not supported yet in FakeBackendV2. **Parameters** * **run\_input** (*QuantumCircuit or Schedule or ScheduleBlock or list*) – An individual or a list of `QuantumCircuit`, `ScheduleBlock`, or `Schedule` objects to run on the backend. * **options** – Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object then the expectation is that the value specified will be used instead of what’s set in the options object. **Returns** The job object for the run **Return type** Job **Raises** **QiskitError** – If a pulse job is supplied and qiskit-aer is not installed. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.fake_provider.FakeYorktownV2.mdx "--- title: IBMBackend description: API reference for qiskit_ibm_runtime.IBMBackend in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.IBMBackend --- # IBMBackend Backend class interfacing with an IBM Quantum backend. * You should not instantiate the `IBMBackend` class directly. Instead, use the methods provided by an [`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.QiskitRuntimeService"") instance to retrieve and handle backends. This class represents an IBM Quantum backend. Its attributes and methods provide information about the backend. For example, the [`status()`](#qiskit_ibm_runtime.IBMBackend.status ""qiskit_ibm_runtime.IBMBackend.status"") method returns a `BackendStatus` instance. The instance contains the `operational` and `pending_jobs` attributes, which state whether the backend is operational and also the number of jobs in the server queue for the backend, respectively: ```python status = backend.status() is_operational = status.operational jobs_in_queue = status.pending_jobs ``` Here is list of attributes available on the `IBMBackend` class: > * name: backend name. > > * backend\_version: backend version in the form X.Y.Z. > > * num\_qubits: number of qubits. > > * target: A `qiskit.transpiler.Target` object for the backend. > > * basis\_gates: list of basis gates names on the backend. > > * gates: list of basis gates on the backend. > > * local: backend is local or remote. > > * simulator: backend is a simulator. > > * conditional: backend supports conditional operations. > > * open\_pulse: backend supports open pulse. > > * memory: backend supports memory. > > * max\_shots: maximum number of shots supported. > > * coupling\_map (list): The coupling map for the device > > * supported\_instructions (List\[str]): Instructions supported by the backend. > > * dynamic\_reprate\_enabled (bool): whether delay between primitives can be set dynamically (ie via `rep_delay`). Defaults to False. > > * rep\_delay\_range (List\[float]): 2d list defining supported range of repetition delays for backend in μs. First entry is lower end of the range, second entry is higher end of the range. Optional, but will be specified when `dynamic_reprate_enabled=True`. > > * default\_rep\_delay (float): Value of `rep_delay` if not specified by user and `dynamic_reprate_enabled=True`. > > * n\_uchannels: Number of u-channels. > > * u\_channel\_lo: U-channel relationship on device los. > > * meas\_levels: Supported measurement levels. > > * qubit\_lo\_range: Qubit lo ranges for each qubit with form (min, max) in GHz. > > * meas\_lo\_range: Measurement lo ranges for each qubit with form (min, max) in GHz. > > * dt: Qubit drive channel timestep in nanoseconds. > > * dtm: Measurement drive channel timestep in nanoseconds. > > * rep\_times: Supported repetition times (program execution time) for backend in μs. > > * meas\_kernels: Supported measurement kernels. > > * discriminators: Supported discriminators. > > * hamiltonian: An optional dictionary with fields characterizing the system hamiltonian. > > * channel\_bandwidth (list): Bandwidth of all channels (qubit, measurement, and U) > > * acquisition\_latency (list): Array of dimension n\_qubits x n\_registers. Latency (in units of dt) to write a measurement result from qubit n into register slot m. > > * conditional\_latency (list): Array of dimension n\_channels \[d->u->m] x n\_registers. Latency (in units of dt) to do a conditional operation on channel n from register slot m > > * meas\_map (list): Grouping of measurement which are multiplexed > > * max\_circuits (int): The maximum number of experiments per job > > * sample\_name (str): Sample name for the backend > > * n\_registers (int): Number of register slots available for feedback (if conditional is True) > > * register\_map (list): An array of dimension n\_qubits X n\_registers that specifies whether a qubit can store a measurement in a certain register slot. > > * configurable (bool): True if the backend is configurable, if the backend is a simulator > > * credits\_required (bool): True if backend requires credits to run a job. > > * online\_date (datetime): The date that the device went online > > * display\_name (str): Alternate name field for the backend > > * description (str): A description for the backend > > * tags (list): A list of string tags to describe the backend > > * version: version of `Backend` class (Ex: 1, 2) > > * channels: An optional dictionary containing information of each channel – their purpose, type, and qubits operated on. > > * parametric\_pulses (list): A list of pulse shapes which are supported on the backend. For example: `['gaussian', 'constant']` > > * processor\_type (dict): Processor type for this backend. A dictionary of the form `{""family"": , ""revision"": , segment: }` such as `{""family"": ""Canary"", ""revision"": ""1.0"", segment: ""A""}`. > > > * family: Processor family of this backend. > > * revision: Revision version of this processor. > > * segment: Segment this processor belongs to within a larger chip. IBMBackend constructor. **Parameters** * **configuration** (`Union`\[`QasmBackendConfiguration`, `PulseBackendConfiguration`]) – Backend configuration. * **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – Instance of QiskitRuntimeService. * **api\_client** (`RuntimeClient`) – IBM client used to communicate with the server. ## Attributes ### coupling\_map Return the `CouplingMap` object ### dt Return the system time resolution of input signals This is required to be implemented if the backend supports Pulse scheduling. **Return type** `Optional`\[`float`] **Returns** The input signal timestep in seconds. If the backend doesn’t define `dt`, `None` will be returned. ### dtm Return the system time resolution of output signals **Returns** The output signal timestep in seconds. **Return type** dtm ### id\_warning\_issued ### instruction\_durations Return the `InstructionDurations` object. ### instruction\_schedule\_map Return the `InstructionScheduleMap` for the instructions defined in this backend’s target. ### instructions A list of Instruction tuples on the backend of the form `(instruction, (qubits)` **Return type** `List`\[`Tuple`\[`Instruction`, `Tuple`\[`int`]]] ### max\_circuits The maximum number of circuits The maximum number of circuits (or Pulse schedules) that can be run in a single job. If there is no limit this will return None. **Return type** `int` ### meas\_map Return the grouping of measurements which are multiplexed This is required to be implemented if the backend supports Pulse scheduling. **Returns** The grouping of measurements which are multiplexed **Return type** meas\_map ### num\_qubits Return the number of qubits the backend has. **Return type** `int` ### operation\_names A list of instruction names that the backend supports. **Return type** `List`\[`str`] ### operations A list of `Instruction` instances that the backend supports. **Return type** `List`\[`Instruction`] ### options Return the options for the backend The options of a backend are the dynamic parameters defining how the backend is used. These are used to control the [`run()`](#qiskit_ibm_runtime.IBMBackend.run ""qiskit_ibm_runtime.IBMBackend.run"") method. ### provider Return the backend Provider. **Returns** the Provider responsible for the backend. **Return type** Provider ### service Return the `service` object **Returns** instance of QiskitRuntimeService **Return type** service ### session Return session **Return type** `Session` ### target A `qiskit.transpiler.Target` object for the backend. **Return type** `Target` **Returns** Target ### version ### name Name of the backend. ### description Optional human-readable description. ### online\_date Date that the backend came online. ### backend\_version Version of the backend being provided. This is not the same as `BackendV2.version`, which is the version of the `Backend` abstract interface. ## Methods ### \_\_call\_\_ Call self as a function. **Return type** [`IBMBackend`](#qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.ibm_backend.IBMBackend"") ### acquire\_channel Return the acquisition channel for the given qubit. **Returns** The Qubit measurement acquisition line. **Return type** AcquireChannel ### cancel\_session Cancel session. All pending jobs will be cancelled. **Return type** `None` ### check\_faulty Check if the input circuit uses faulty qubits or edges. **Parameters** **circuit** (`QuantumCircuit`) – Circuit to check. **Raises** **ValueError** – If an instruction operating on a faulty qubit or edge is found. **Return type** `None` ### close\_session Close the session so new jobs will no longer be accepted, but existing queued or running jobs will run to completion. The session will be terminated once there are no more pending jobs. **Return type** `None` ### configuration Return the backend configuration. Backend configuration contains fixed information about the backend, such as its name, number of qubits, basis gates, coupling map, quantum volume, etc. The schema for backend configuration can be found in [Qiskit/ibm-quantum-schemas/backend\_configuration](https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/backend_configuration_schema.json). **Return type** `Union`\[`QasmBackendConfiguration`, `PulseBackendConfiguration`] **Returns** The configuration for the backend. ### control\_channel Return the secondary drive channel for the given qubit This is typically utilized for controlling multiqubit interactions. This channel is derived from other channels. **Parameters** **qubits** (`Iterable`\[`int`]) – Tuple or list of qubits of the form `(control_qubit, target_qubit)`. **Returns** The Qubit measurement acquisition line. **Return type** List\[ControlChannel] ### defaults Return the pulse defaults for the backend. The schema for default pulse configuration can be found in [Qiskit/ibm-quantum-schemas/default\_pulse\_configuration](https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/default_pulse_configuration_schema.json). **Parameters** **refresh** (`bool`) – If `True`, re-query the server for the backend pulse defaults. Otherwise, return a cached version. **Return type** `Optional`\[`PulseDefaults`] **Returns** The backend pulse defaults or `None` if the backend does not support pulse. ### drive\_channel Return the drive channel for the given qubit. **Returns** The Qubit drive channel **Return type** DriveChannel ### get\_translation\_stage\_plugin Return the default translation stage plugin name for IBM backends. **Return type** `str` ### measure\_channel Return the measure stimulus channel for the given qubit. **Returns** The Qubit measurement stimulus line **Return type** MeasureChannel ### open\_session Open session **Return type** `Session` ### properties Return the backend properties, subject to optional filtering. This data describes qubits properties (such as T1 and T2), gates properties (such as gate length and error), and other general properties of the backend. The schema for backend properties can be found in [Qiskit/ibm-quantum-schemas/backend\_properties](https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/backend_properties_schema.json). **Parameters** * **refresh** (`bool`) – If `True`, re-query the server for the backend properties. Otherwise, return a cached version. * **datetime** (`Optional`\[`datetime`]) – By specifying datetime, this function returns an instance of the `BackendProperties` whose timestamp is closest to, but older than, the specified datetime. Note that this is only supported using `ibm_quantum` runtime. **Return type** `Optional`\[`BackendProperties`] **Returns** The backend properties or `None` if the backend properties are not currently available. **Raises** * **TypeError** – If an input argument is not of the correct type. * **NotImplementedError** – If datetime is specified when cloud runtime is used. ### qubit\_properties Return QubitProperties for a given qubit. If there are no defined or the backend doesn’t support querying these details this method does not need to be implemented. **Parameters** **qubit** (`Union`\[`int`, `List`\[`int`]]) – The qubit to get the `QubitProperties` object for. This can be a single integer for 1 qubit or a list of qubits and a list of `QubitProperties` objects will be returned in the same order **Return type** `Union`\[`QubitProperties`, `List`\[`QubitProperties`]] **Returns** The `QubitProperties` object for the specified qubit. If a list of qubits is provided a list will be returned. If properties are missing for a qubit this can be `None`. **Raises** **NotImplementedError** – if the backend doesn’t support querying the qubit properties ### run Run on the backend. If a keyword specified here is also present in the `options` attribute/object, the value specified here will be used for this run. **Parameters** * **circuits** (`Union`\[`QuantumCircuit`, `str`, `List`\[`Union`\[`QuantumCircuit`, `str`]]]) – An individual or a list of `QuantumCircuit`. * **dynamic** (`Optional`\[`bool`]) – Whether the circuit is dynamic (uses in-circuit conditionals) * **job\_tags** (`Optional`\[`List`\[`str`]]) – Tags to be assigned to the job. The tags can subsequently be used as a filter in the `jobs()` function call. * **init\_circuit** (`Optional`\[`QuantumCircuit`]) – A quantum circuit to execute for initializing qubits before each circuit. If specified, `init_num_resets` is ignored. Applicable only if `dynamic=True` is specified. * **init\_num\_resets** (`Optional`\[`int`]) – The number of qubit resets to insert before each circuit execution. * **header** (`Optional`\[`Dict`]) – User input that will be attached to the job and will be copied to the corresponding result header. Headers do not affect the run. This replaces the old `Qobj` header. This parameter is applicable only if `dynamic=False` is specified or defaulted to. * **shots** (`Union`\[`int`, `float`, `None`]) – Number of repetitions of each circuit, for sampling. Default: 4000 or `max_shots` from the backend configuration, whichever is smaller. This parameter is applicable only if `dynamic=False` is specified or defaulted to. * **memory** (`Optional`\[`bool`]) – 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. This parameter is applicable only if `dynamic=False` is specified or defaulted to. * **meas\_level** (`Union`\[`int`, `MeasLevel`, `None`]) – Level of the measurement output for pulse experiments. See [OpenPulse specification](https://arxiv.org/pdf/1809.03452.pdf) for details: * `0`, measurements of the raw signal (the measurement output pulse envelope) * `1`, measurement kernel is selected (a complex number obtained after applying the measurement kernel to the measurement output signal) * `2` (default), a discriminator is selected and the qubit state is stored (0 or 1) This parameter is applicable only if `dynamic=False` is specified or defaulted to. * **meas\_return** (`Union`\[`str`, `MeasReturnType`, `None`]) – 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). This parameter is applicable only if `dynamic=False` is specified or defaulted to. * **rep\_delay** (`Optional`\[`float`]) – Delay between primitives in seconds. Only supported on certain backends (if `backend.configuration().dynamic_reprate_enabled=True`). If supported, `rep_delay` must be from the range supplied by the backend (`backend.configuration().rep_delay_range`). Default is given by `backend.configuration().default_rep_delay`. This parameter is applicable only if `dynamic=False` is specified or defaulted to. * **init\_qubits** (`Optional`\[`bool`]) – Whether to reset the qubits to the ground state for each shot. Default: `True`. This parameter is applicable only if `dynamic=False` is specified or defaulted to. * **use\_measure\_esp** (`Optional`\[`bool`]) – Whether to use excited state promoted (ESP) readout for measurements which are the terminal instruction to a qubit. ESP readout can offer higher fidelity than standard measurement sequences. See [here](https://arxiv.org/pdf/2008.08571.pdf). Default: `True` if backend supports ESP readout, else `False`. Backend support for ESP readout is determined by the flag `measure_esp_enabled` in `backend.configuration()`. This parameter is applicable only if `dynamic=False` is specified or defaulted to. * **noise\_model** (`Optional`\[`Any`]) – Noise model (Simulators only). This parameter is applicable only if `dynamic=False` is specified or defaulted to. * **seed\_simulator** (`Optional`\[`int`]) – Random seed to control sampling (Simulators only). This parameter is applicable only if `dynamic=False` is specified or defaulted to. * **\*\*run\_config** – Extra arguments used to configure the run. This parameter is applicable only if `dynamic=False` is specified or defaulted to. **Return type** [`RuntimeJob`](qiskit_ibm_runtime.RuntimeJob ""qiskit_ibm_runtime.runtime_job.RuntimeJob"") **Returns** The job to be executed. **Raises** * **IBMBackendApiError** – If an unexpected error occurred while submitting the job. * **IBMBackendApiProtocolError** – If an unexpected value received from the server. * **IBMBackendValueError** – * If an input parameter value is not valid. - If ESP readout is used and the backend does not support this. ### set\_options Set the options fields for the backend This method is used to update the options of a backend. If you need to change any of the options prior to running just pass in the kwarg with the new value for the options. **Parameters** **fields** – The fields to update the options **Raises** **AttributeError** – If the field passed in is not part of the options ### status Return the backend status. If the returned `BackendStatus` instance has `operational=True` but `status_msg=""internal""`, then the backend is accepting jobs but not processing them. **Return type** `BackendStatus` **Returns** The status of the backend. **Raises** **IBMBackendApiProtocolError** – If the status for the backend cannot be formatted properly. ### target\_history A `qiskit.transpiler.Target` object for the backend. **Return type** `Target` **Returns** Target with properties found on datetime ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.IBMBackend.mdx "--- title: DynamicalDecouplingOptions description: API reference for qiskit_ibm_runtime.options.DynamicalDecouplingOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.DynamicalDecouplingOptions --- # DynamicalDecouplingOptions Options for dynamical decoupling (DD). **Parameters** * **enable** – Whether to enable DD as specified by the other options in this class. Default: False. * **sequence\_type** – Which dynamical decoupling sequence to use. Default: “XX”. * `""XX""`: use the sequence `tau/2 - (+X) - tau - (+X) - tau/2` * `""XpXm""`: use the sequence `tau/2 - (+X) - tau - (-X) - tau/2` * `""XY4""`: : use the sequence `tau/2 - (+X) - tau - (+Y) - tau (-X) - tau - (-Y) - tau/2` * **extra\_slack\_distribution** – Where to put extra timing delays due to rounding issues. Rounding issues arise because the discrete time step `dt` of the system cannot be divided. This option takes following values. Default: “middle”. * `""middle""`: Put the extra slack to the interval at the middle of the sequence. * `""edges""`: Divide the extra slack as evenly as possible into intervals at beginning and end of the sequence. * **scheduling\_method** – Whether to schedule gates as soon as (“asap”) or as late as (“alap”) possible. Default: “alap”. ## Attributes ### enable ### extra\_slack\_distribution ### scheduling\_method ### sequence\_type ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.DynamicalDecouplingOptions.mdx "--- title: EnvironmentOptions description: API reference for qiskit_ibm_runtime.options.EnvironmentOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.EnvironmentOptions --- # EnvironmentOptions Options related to the execution environment. This applies to both V1 and V2 primitives. **Parameters** * **log\_level** – logging level to set in the execution environment. The valid log levels are: `DEBUG`, `INFO`, `WARNING`, `ERROR`, and `CRITICAL`. Default: `WARNING`. * **callback** – Callback function to be invoked for any interim results and final result. The callback function will receive 2 positional parameters: > 1. Job ID > 2. Job result. Default: `None`. * **job\_tags** – Tags to be assigned to the job. The tags can subsequently be used as a filter in the `qiskit_ibm_runtime.qiskit_runtime_service.jobs()` function call. Default: `None`. ## Attributes ### callback ### job\_tags ### log\_level ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.EnvironmentOptions.mdx "--- title: EstimatorOptions description: API reference for qiskit_ibm_runtime.options.EstimatorOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.EstimatorOptions --- # EstimatorOptions Options for V2 Estimator. **Parameters** * **default\_precision** – The default precision to use for any PUB or `run()` call that does not specify one. Each estimator pub can specify its own precision. If the `run()` method is given a precision, then that value is used for all PUBs in the `run()` call that do not specify their own. Default: 0.015625 (1 / sqrt(4096)). * **default\_shots** – The total number of shots to use per circuit per configuration. If set, this value overrides [`default_precision`](#qiskit_ibm_runtime.options.EstimatorOptions.default_precision ""qiskit_ibm_runtime.options.EstimatorOptions.default_precision""). A configuration is a combination of a specific parameter value binding set and a physical measurement basis. A physical measurement basis groups together some collection of qubit-wise commuting observables for some specific circuit/parameter value set to create a single measurement with basis rotations that is inserted into hardware executions. If twirling is enabled, the value of this option will be divided over circuit, randomizations, with a smaller number of shots per randomization. See the [`twirling`](#qiskit_ibm_runtime.options.EstimatorOptions.twirling ""qiskit_ibm_runtime.options.EstimatorOptions.twirling"") options. Default: `None`. * **optimization\_level** – (DEPRECATED) How much optimization to perform on the circuits. Higher levels generate more optimized circuits, at the expense of longer processing times. * 0: no optimization * 1: light optimization Default: 0. * **resilience\_level** – How much resilience to build against errors. Higher levels generate more accurate results, at the expense of longer processing times. * 0: No mitigation. * 1: Minimal mitigation costs. Mitigate error associated with readout errors. * 2: Medium mitigation costs. Typically reduces bias in estimators but is not guaranteed to be zero bias. Refer to the [Configure error mitigation for Qiskit Runtime](/run/configure-error-mitigation). for more information about the error mitigation methods used at each level. Default: 1. * **seed\_estimator** – Seed used to control sampling. Default: `None`. * **dynamical\_decoupling** – Suboptions for dynamical decoupling. See [`DynamicalDecouplingOptions`](qiskit_ibm_runtime.options.DynamicalDecouplingOptions ""qiskit_ibm_runtime.options.DynamicalDecouplingOptions"") for all available options. * **resilience** – Advanced resilience options to fine tune the resilience strategy. See [`ResilienceOptionsV2`](qiskit_ibm_runtime.options.ResilienceOptionsV2 ""qiskit_ibm_runtime.options.ResilienceOptionsV2"") for all available options. * **execution** – Execution time options. See [`ExecutionOptionsV2`](qiskit_ibm_runtime.options.ExecutionOptionsV2 ""qiskit_ibm_runtime.options.ExecutionOptionsV2"") for all available options. * **twirling** – Pauli twirling options. See [`TwirlingOptions`](qiskit_ibm_runtime.options.TwirlingOptions ""qiskit_ibm_runtime.options.TwirlingOptions"") for all available options. * **experimental** – Experimental options. These options are subject to change without notification, and stability is not guaranteed. Currently, the available options are: * Probabilistic Error Amplification (PEA). To enable PEA, set: ```python estimator_options.experimental = {""resilience"": {""zne"": {""amplifier"": ""pea""}}} ``` Since PEA is an amplification technique of ZNE, you will also need to enable ZNE by setting `resilience.zne_mitigation = True`. Other documented `resilience.zne` options can be used in conjunction to set extrapolators, amplification levels, etc. Experiments to learn a sparse Pauli noise model will be performed for every uniquely identified entangling layer (up to a specified cutoff) in the union of circuits across PUBs; see :class:\~.LayerNoiseLearningOptions\` for options. Add full-width barriers to specify layers unambiguously. ## Attributes ### default\_precision ### default\_shots ### dynamical\_decoupling ### environment ### execution ### experimental ### max\_execution\_time ### optimization\_level ### resilience ### resilience\_level ### seed\_estimator ### simulator ### twirling ## Methods ### update Update the options. **Return type** `None` ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.EstimatorOptions.mdx "--- title: ExecutionOptions description: API reference for qiskit_ibm_runtime.options.ExecutionOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.ExecutionOptions --- # ExecutionOptions Execution options for V1 primitives. **Parameters** * **shots** – Number of repetitions of each circuit, for sampling. Default: 4000. * **init\_qubits** – Whether to reset the qubits to the ground state for each shot. Default: `True`. ## Attributes ### init\_qubits ### shots ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.ExecutionOptions.mdx "--- title: ExecutionOptionsV2 description: API reference for qiskit_ibm_runtime.options.ExecutionOptionsV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.ExecutionOptionsV2 --- # ExecutionOptionsV2 Execution options for V2 primitives. ## Attributes ### init\_qubits Whether to reset the qubits to the ground state for each shot. Default is `True`. ### rep\_delay The repetition delay. This is the delay between a measurement and the subsequent quantum circuit. This is only supported on backends that have `backend.dynamic_reprate_enabled=True`. It must be from the range supplied by `backend.rep_delay_range`. Default is given by `backend.default_rep_delay`. ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.ExecutionOptionsV2.mdx "--- title: LayerNoiseLearningOptions description: API reference for qiskit_ibm_runtime.options.LayerNoiseLearningOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.LayerNoiseLearningOptions --- # LayerNoiseLearningOptions Options for learning layer noise. This is only used by V2 Estimator. These options are only used when the resilience level or options specify a technique that requires layer noise learning. **Parameters** * **max\_layers\_to\_learn** – The max number of unique layers to learn. A `None` value indicates that there is no limit. If there are more unique layers present, then some layers will not be learned or mitigated. The learned layers are prioritized based on the number of times they occur in a set of run estimator PUBs, and for equally occurring layers are further sorted by the number of two-qubit gates in the layer. Default: 4. * **shots\_per\_randomization** – The total number of shots to use per random learning circuit. A learning circuit is a random circuit at a specific learning depth with a specific measurement basis that is executed on hardware. Default: 128. * **num\_randomizations** – The number of random circuits to use per learning circuit configuration. A configuration is a measurement basis and depth setting. For example, if your experiment has six depths, and nine required measurement bases, then setting this value to 32 will result in a total of `32 * 9 * 6` circuits that need to be executed (at [`shots_per_randomization`](#qiskit_ibm_runtime.options.LayerNoiseLearningOptions.shots_per_randomization ""qiskit_ibm_runtime.options.LayerNoiseLearningOptions.shots_per_randomization"") each). Default: 32. * **layer\_pair\_depths** – The circuit depths (measured in number of pairs) to use in learning experiments. Pairs are used as the unit because we exploit the order-2 nature of our entangling gates in the noise learning implementation. A value of `3` would correspond to 6 layers of the layer of interest, for example. Default: (0, 1, 2, 4, 16, 32). ## Attributes ### layer\_pair\_depths ### max\_layers\_to\_learn ### num\_randomizations ### shots\_per\_randomization ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.LayerNoiseLearningOptions.mdx "--- title: MeasureNoiseLearningOptions description: API reference for qiskit_ibm_runtime.options.MeasureNoiseLearningOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.MeasureNoiseLearningOptions --- # MeasureNoiseLearningOptions Options for measurement noise learning. This is only used by V2 Estimator. These options are only used when the resilience level or options specify a technique that requires measurement noise learning. **Parameters** * **num\_randomizations** – The number of random circuits to draw for the measurement learning experiment. Default: 32. * **shots\_per\_randomization** – The number of shots to use for the learning experiment per random circuit. If “auto”, the value will be chosen automatically based on the input PUBs. Default: “auto”. ## Attributes ### num\_randomizations ### shots\_per\_randomization ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.MeasureNoiseLearningOptions.mdx "--- title: Options description: API reference for qiskit_ibm_runtime.options.Options in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.Options --- # Options , resilience=, execution=, environment=, simulator=)"" modifiers=""class""> Options for the primitives, used by V1 primitives. **Parameters** * **optimization\_level** (`Optional`\[`int`]) – How much optimization to perform on the circuits. Higher levels generate more optimized circuits, at the expense of longer transpilation times. This is based on the `optimization_level` parameter in qiskit-terra but may include backend-specific optimization. Default: 3. * 0: no optimization * 1: light optimization * 2: heavy optimization * 3: even heavier optimization * **resilience\_level** (`Optional`\[`int`]) – How much resilience to build against errors. Higher levels generate more accurate results, at the expense of longer processing times. Default: 1. * 0: No mitigation. * 1: Minimal mitigation costs. Mitigate error associated with readout errors. * 2: Medium mitigation costs. Typically reduces bias in estimators but is not guaranteed to be zero bias. Only applies to estimator. * 3: Heavy mitigation with layer sampling. Theoretically expected to deliver zero bias estimators. Only applies to estimator. Refer to the [Qiskit Runtime documentation](/run/configure-error-mitigation). for more information about the error mitigation methods used at each level. * **max\_execution\_time** (`Optional`\[`int`]) – Maximum execution time in seconds, which is based on system execution time (not wall clock time). System execution time is the amount of time that the system is dedicated to processing your job. If a job exceeds this time limit, it is forcibly cancelled. Simulator jobs continue to use wall clock time. Refer to the [Max execution time documentation](/run/max-execution-time). for more information. * **transpilation** (`Union`\[[`TranspilationOptions`](qiskit_ibm_runtime.options.TranspilationOptions ""qiskit_ibm_runtime.options.transpilation_options.TranspilationOptions""), `Dict`]) – Transpilation options. See [`TranspilationOptions`](qiskit_ibm_runtime.options.TranspilationOptions ""qiskit_ibm_runtime.options.TranspilationOptions"") for all available options. * **resilience** (`Union`\[[`ResilienceOptions`](qiskit_ibm_runtime.options.ResilienceOptions ""qiskit_ibm_runtime.options.resilience_options.ResilienceOptions""), `Dict`]) – Advanced resilience options to fine tune the resilience strategy. See [`ResilienceOptions`](qiskit_ibm_runtime.options.ResilienceOptions ""qiskit_ibm_runtime.options.ResilienceOptions"") for all available options. * **execution** (`Union`\[[`ExecutionOptions`](qiskit_ibm_runtime.options.ExecutionOptions ""qiskit_ibm_runtime.options.execution_options.ExecutionOptions""), `Dict`]) – Execution time options. See [`ExecutionOptions`](qiskit_ibm_runtime.options.ExecutionOptions ""qiskit_ibm_runtime.options.ExecutionOptions"") for all available options. * **environment** (`Union`\[[`EnvironmentOptions`](qiskit_ibm_runtime.options.EnvironmentOptions ""qiskit_ibm_runtime.options.environment_options.EnvironmentOptions""), `Dict`]) – Options related to the execution environment. See [`EnvironmentOptions`](qiskit_ibm_runtime.options.EnvironmentOptions ""qiskit_ibm_runtime.options.EnvironmentOptions"") for all available options. * **simulator** (`Union`\[[`SimulatorOptions`](qiskit_ibm_runtime.options.SimulatorOptions ""qiskit_ibm_runtime.options.simulator_options.SimulatorOptions""), `Dict`]) – Simulator options. See [`SimulatorOptions`](qiskit_ibm_runtime.options.SimulatorOptions ""qiskit_ibm_runtime.options.SimulatorOptions"") for all available options. ## Attributes ### max\_execution\_time ### optimization\_level ### resilience\_level ### transpilation ### resilience ### execution ### environment ### simulator ## Methods ### validate\_options Validate that program inputs (options) are valid :raises ValueError: if optimization\_level is outside the allowed range. :raises ValueError: if max\_execution\_time is outside the allowed range. **Return type** `None` ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.Options.mdx "--- title: PecOptions description: API reference for qiskit_ibm_runtime.options.PecOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.PecOptions --- # PecOptions Probabalistic error cancellation mitigation options. This is only used by V2 Estimator. **Parameters** * **max\_overhead** – The maximum circuit sampling overhead allowed, or `None` for no maximum. Default: 100. * **noise\_gain** – The amount by which to scale the noise, where: * A value of 0 corresponds to removing the full learned noise. * A value of 1 corresponds to no removal of the learned noise. * A value between 0 and 1 corresponds to partially removing the learned noise. * A value greater than one corresponds to amplifying the learned noise. If “auto”, the value in the range `[0, 1]` will be chosen automatically for each input PUB based on the learned noise strength, `max_overhead`, and the depth of the PUB. Default: “auto”. ## Attributes ### max\_overhead ### noise\_gain ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.PecOptions.mdx "--- title: ResilienceOptions description: API reference for qiskit_ibm_runtime.options.ResilienceOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.ResilienceOptions --- # ResilienceOptions Resilience options for V1 primitives. **Parameters** * **noise\_factors** – An list of real valued noise factors that determine by what amount the circuits’ noise is amplified. Only applicable for `resilience_level=2`. Default: `None`, and (1, 3, 5) if resilience level is 2. * **noise\_amplifier** – A noise amplification strategy. Currently only * **resilience\_level=2.** (*""LocalFoldingAmplifier"" is supported Only applicable for*) – Default: “LocalFoldingAmplifier”. * **extrapolator** – An extrapolation strategy. One of `""LinearExtrapolator""`, `""QuadraticExtrapolator""`, `""CubicExtrapolator""`, `""QuarticExtrapolator""`. Note that `""CubicExtrapolator""` and `""QuarticExtrapolator""` require more noise factors than the default. Only applicable for `resilience_level=2`. Default: `None`, and `LinearExtrapolator` if resilience level is 2. ## Attributes ### extrapolator ### noise\_amplifier ### noise\_factors ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.ResilienceOptions.mdx "--- title: ResilienceOptionsV2 description: API reference for qiskit_ibm_runtime.options.ResilienceOptionsV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.ResilienceOptionsV2 --- # ResilienceOptionsV2 Resilience options for V2 Estimator. **Parameters** * **measure\_mitigation** – Whether to enable measurement error mitigation method. Further suboptions are available in [`measure_noise_learning`](#qiskit_ibm_runtime.options.ResilienceOptionsV2.measure_noise_learning ""qiskit_ibm_runtime.options.ResilienceOptionsV2.measure_noise_learning""). Default: True. * **measure\_noise\_learning** – Additional measurement noise learning options. See [`MeasureNoiseLearningOptions`](qiskit_ibm_runtime.options.MeasureNoiseLearningOptions ""qiskit_ibm_runtime.options.MeasureNoiseLearningOptions"") for all options. * **zne\_mitigation** – Whether to turn on Zero Noise Extrapolation error mitigation method. Further suboptions are available in [`zne`](#qiskit_ibm_runtime.options.ResilienceOptionsV2.zne ""qiskit_ibm_runtime.options.ResilienceOptionsV2.zne""). Default: False. * **zne** – Additional zero noise extrapolation mitigation options. See [`ZneOptions`](qiskit_ibm_runtime.options.ZneOptions ""qiskit_ibm_runtime.options.ZneOptions"") for all options. * **pec\_mitigation** – Whether to turn on Probabilistic Error Cancellation error mitigation method. Further suboptions are available in [`pec`](#qiskit_ibm_runtime.options.ResilienceOptionsV2.pec ""qiskit_ibm_runtime.options.ResilienceOptionsV2.pec""). Default: False. * **pec** – Additional probabalistic error cancellation mitigation options. See [`PecOptions`](qiskit_ibm_runtime.options.PecOptions ""qiskit_ibm_runtime.options.PecOptions"") for all options. * **layer\_noise\_learning** – Layer noise learning options. See [`LayerNoiseLearningOptions`](qiskit_ibm_runtime.options.LayerNoiseLearningOptions ""qiskit_ibm_runtime.options.LayerNoiseLearningOptions"") for all options. ## Attributes ### layer\_noise\_learning ### measure\_mitigation ### measure\_noise\_learning ### pec ### pec\_mitigation ### zne ### zne\_mitigation ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.ResilienceOptionsV2.mdx "--- title: SamplerExecutionOptionsV2 description: API reference for qiskit_ibm_runtime.options.SamplerExecutionOptionsV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.SamplerExecutionOptionsV2 --- # SamplerExecutionOptionsV2 Extension of [`ExecutionOptionsV2`](qiskit_ibm_runtime.options.ExecutionOptionsV2 ""qiskit_ibm_runtime.options.ExecutionOptionsV2"") for the sampler primitive. ## Attributes ### init\_qubits Whether to reset the qubits to the ground state for each shot. Default is `True`. ### meas\_type How to process and return measurement results. This option sets the return type of all classical registers in all `SamplerPubResult`s. If a sampler pub with shape `pub_shape` has a circuit that contains a classical register with size `creg_size`, then the returned data associated with this register will have one of the following formats depending on the value of this option. * `""classified""`: A `BitArray` of shape `pub_shape` over `num_shots` with a number of bits equal to `creg_size`. * `""kerneled""`: A complex NumPy array of shape `(*pub_shape, num_shots, creg_size)`, where each entry represents an IQ data point (resulting from kerneling the measurement trace) in arbitrary units. * `""avg_kerneled""`: A complex NumPy array of shape `(*pub_shape, creg_size)`, where each entry represents an IQ data point (resulting from kerneling the measurement trace and averaging over shots) in arbitrary units. This option is equivalent to selecting `""kerneled""` and then averaging over the shots axis, but requires less data bandwidth. Default: “classified”. See [here](https://pubs.aip.org/aip/rsi/article/88/10/104703/836456) for a description of kerneling. ### rep\_delay The repetition delay. This is the delay between a measurement and the subsequent quantum circuit. This is only supported on backends that have `backend.dynamic_reprate_enabled=True`. It must be from the range supplied by `backend.rep_delay_range`. Default is given by `backend.default_rep_delay`. ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.SamplerExecutionOptionsV2.mdx "--- title: SamplerOptions description: API reference for qiskit_ibm_runtime.options.SamplerOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.SamplerOptions --- # SamplerOptions Options for V2 Sampler. **Parameters** * **default\_shots** – The default number of shots to use if none are specified in the PUBs or in the run method. Default: 4096. * **dynamical\_decoupling** – Suboptions for dynamical decoupling. See [`DynamicalDecouplingOptions`](qiskit_ibm_runtime.options.DynamicalDecouplingOptions ""qiskit_ibm_runtime.options.DynamicalDecouplingOptions"") for all available options. * **execution** – Execution time options. See [`SamplerExecutionOptionsV2`](qiskit_ibm_runtime.options.SamplerExecutionOptionsV2 ""qiskit_ibm_runtime.options.SamplerExecutionOptionsV2"") for all available options. * **twirling** – Pauli twirling options. See [`TwirlingOptions`](qiskit_ibm_runtime.options.TwirlingOptions ""qiskit_ibm_runtime.options.TwirlingOptions"") for all available options. * **experimental** – Experimental options. ## Attributes ### default\_shots ### dynamical\_decoupling ### environment ### execution ### experimental ### max\_execution\_time ### simulator ### twirling ## Methods ### update Update the options. **Return type** `None` ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.SamplerOptions.mdx "--- title: SimulatorOptions description: API reference for qiskit_ibm_runtime.options.SimulatorOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.SimulatorOptions --- # SimulatorOptions Simulator options. For best practice in simulating a backend make sure to pass the basis gates and coupling map of that backend. **Parameters** * **noise\_model** – Noise model for the simulator. Default: `None`. * **seed\_simulator** – Random seed to control sampling. Default: `None`. * **coupling\_map** – Directed coupling map to target in mapping. If the coupling map is symmetric, both directions need to be specified. Each entry in the list specifies a directed two-qubit interactions, e.g: `[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]`. Default: `None`, which implies no connectivity constraints. * **basis\_gates** – List of basis gate names to unroll to. For example, `['u1', 'u2', 'u3', 'cx']`. Unrolling is not done if not set. Default: all basis gates supported by the simulator. ## Attributes ### basis\_gates ### coupling\_map ### noise\_model ### seed\_simulator ## Methods ### set\_backend Set backend for simulation. This method changes noise\_model, coupling\_map, basis\_gates according to given backend. **Parameters** **backend** (`Union`\[`BackendV1`, `BackendV2`]) – backend to be set. **Raises** **MissingOptionalLibraryError** – if qiskit-aer is not found. **Return type** `None` ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.SimulatorOptions.mdx "--- title: TranspilationOptions description: API reference for qiskit_ibm_runtime.options.TranspilationOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.TranspilationOptions --- # TranspilationOptions Transpilation options. This is only used by V1 primitives. **Parameters** * **skip\_transpilation** – Whether to skip transpilation. Default is False. * **initial\_layout** – Initial position of virtual qubits on physical qubits. See `qiskit.compiler.transpile` for more information. * **layout\_method** – Name of layout selection pass. One of ‘trivial’, ‘dense’, ‘noise\_adaptive’, ‘sabre’. * **routing\_method** – Name of routing pass. One of ‘basic’, ‘lookahead’, ‘stochastic’, ‘sabre’, ‘none’. * **approximation\_degree** – heuristic dial used for circuit approximation (1.0=no approximation, 0.0=maximal approximation) ## Attributes ### approximation\_degree ### initial\_layout ### layout\_method ### routing\_method ### skip\_transpilation ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.TranspilationOptions.mdx "--- title: TwirlingOptions description: API reference for qiskit_ibm_runtime.options.TwirlingOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.TwirlingOptions --- # TwirlingOptions Twirling options. This is only used by V2 primitives. **Parameters** * **enable\_gates** – Whether to apply 2-qubit gate twirling. Default: False. * **enable\_measure** – Whether to enable twirling of measurements. Twirling will only be applied to those measurement registers not involved within a conditional logic. Default: True for Estimator, false for Sampler. * **num\_randomizations** – The number of random samples to use when twirling or peforming sampled mitigation. If `num_randomizations` is “auto”, for every pub executed `shots` times: * If `shots_per_randomization` is also “auto”, `shots_per_randomization` is set first as described below, then `num_randomizations` is set as `ceil(shots/shots_per_randomization)`, where `ceil` is the ceiling function. * Otherwise, the value is set to `ceil(shots/shots_per_randomization)`. Default: “auto”. * **shots\_per\_randomization** – The number of shots to run for each random sample. If “auto”, for every pub executed `shots` times: * If `num_randomizations` is also “auto”, the value is set to `64` for PEC mitigation or to `max(64, ceil(shots / 32))` in all other cases, where `ceil` is the ceiling function. * Otherwise, the value is set to `ceil(shots/num_randomizations)`. Default: “auto”. * **strategy** – Specify the strategy of twirling qubits in identified layers of 2-qubit twirled gates. Allowed values are * If `""active""` only the instruction qubits in each individual twirled layer will be twirled. * If `""active-circuit""` the union of all instruction qubits in the circuit will be twirled in each twirled layer. * If `""active-accum""` the union of instructions qubits in the circuit up to the current twirled layer will be twirled in each individual twirled layer. * If `""all""` all qubits in the input circuit will be twirled in each twirled layer. Default: “active-accum”. ## Attributes ### enable\_gates ### enable\_measure ### num\_randomizations ### shots\_per\_randomization ### strategy ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.TwirlingOptions.mdx "--- title: ZneOptions description: API reference for qiskit_ibm_runtime.options.ZneOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.options.ZneOptions --- # ZneOptions Zero noise extrapolation mitigation options. This is only used by V2 Estimator. **Parameters** * **amplifier** – Which technique to use for amplifying noise. One of: * ”gate\_folding” (default) uses 2-qubit gate folding to amplify noise. If the noise factor requires amplifying only a subset of the gates, then these gates are chosen randomly. * ”gate\_folding\_front” uses 2-qubit gate folding to amplify noise. If the noise factor requires amplifying only a subset of the gates, then these gates are selected from the front of the topologically ordered DAG circuit. * ”gate\_folding\_back” uses 2-qubit gate folding to amplify noise. If the noise factor requires amplifying only a subset of the gates, then these gates are selected from the back of the topologically ordered DAG circuit. * **noise\_factors** – Noise factors to use for noise amplification. Default: (1, 3, 5). * **extrapolator** – Extrapolator(s) to try (in order) for extrapolating to zero noise. One or more of: * ”linear” * ”exponential” * ”double\_exponential” * ”polynomial\_degree\_(1 \<= k \<= 7)” Default: (“exponential”, “linear”). ## Attributes ### amplifier ### extrapolator ### noise\_factors ## Methods ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.options.ZneOptions.mdx "--- title: QiskitRuntimeService description: API reference for qiskit_ibm_runtime.QiskitRuntimeService in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.QiskitRuntimeService --- # QiskitRuntimeService Class for interacting with the Qiskit Runtime service. QiskitRuntimeService constructor An account is selected in the following order: > * Account with the input name, if specified. > * Default account for the channel type, if channel is specified but token is not. > * Account defined by the input channel and token, if specified. > * Account defined by the default\_channel if defined in filename > * Account defined by the environment variables, if defined. > * Default account for the `ibm_cloud` account, if one is available. > * Default account for the `ibm_quantum` account, if one is available. instance, proxies, and verify can be used to overwrite corresponding values in the loaded account. **Parameters** * **channel** (`Optional`\[`Literal`\[‘ibm\_cloud’, ‘ibm\_quantum’]]) – Channel type. `ibm_cloud` or `ibm_quantum`. * **token** (`Optional`\[`str`]) – IBM Cloud API key or IBM Quantum API token. * **url** (`Optional`\[`str`]) – The API URL. Defaults to [https://cloud.ibm.com](https://cloud.ibm.com) (ibm\_cloud) or [https://auth.quantum-computing.ibm.com/api](https://auth.quantum-computing.ibm.com/api) (ibm\_quantum). * **filename** (`Optional`\[`str`]) – Full path of the file where the account is created. Default: \_DEFAULT\_ACCOUNT\_CONFIG\_JSON\_FILE * **name** (`Optional`\[`str`]) – Name of the account to load. * **instance** (`Optional`\[`str`]) – The service instance to use. For `ibm_cloud` runtime, this is the Cloud Resource Name (CRN) or the service name. For `ibm_quantum` runtime, this is the hub/group/project in that format. * **proxies** (`Optional`\[`dict`]) – Proxy configuration. Supported optional keys are `urls` (a dictionary mapping protocol or protocol and host to the URL of the proxy, documented at [https://docs.python-requests.org/en/latest/api/#requests.Session.proxies](https://docs.python-requests.org/en/latest/api/#requests.Session.proxies)), `username_ntlm`, `password_ntlm` (username and password to enable NTLM user authentication) * **verify** (`Optional`\[`bool`]) – Whether to verify the server’s TLS certificate. * **channel\_strategy** (`Optional`\[`str`]) – Error mitigation strategy. * **private\_endpoint** (`Optional`\[`bool`]) – Connect to private API URL. **Returns** An instance of QiskitRuntimeService. **Raises** **IBMInputValueError** – If an input is invalid. ## Attributes ### channel Return the channel type used. **Return type** `str` **Returns** The channel type used. ### global\_service ## Methods ### active\_account Return the IBM Quantum account currently in use for the session. **Return type** `Optional`\[`Dict`\[`str`, `str`]] **Returns** A dictionary with information about the account currently in the session. ### backend Return a single backend matching the specified filtering. **Parameters** * **name** (`Optional`\[`str`]) – Name of the backend. * **instance** (`Optional`\[`str`]) – This is only supported for `ibm_quantum` runtime and is in the hub/group/project format. If an instance is not given, among the providers with access to the backend, a premium provider will be prioritized. For users without access to a premium provider, the default open provider will be used. * **use\_fractional\_gates** (`bool`) – Set True to allow for the backends to include fractional gates in target. Currently this feature cannot be used simulataneously with the dynamic circuits, PEC, or PEA. When this flag is set, control flow instructions are automatically removed from the backend target. When you use the dynamic circuits feature (e.g. if\_else) in your algorithm, you must disable this flag to create executable ISA circuits. This flag might be modified or removed when our backend supports dynamic circuits and fractional gates simultaneously. **Returns** A backend matching the filtering. **Return type** Backend **Raises** **QiskitBackendNotFoundError** – if no backend could be found. ### backends Return all backends accessible via this account, subject to optional filtering. **Parameters** * **name** (`Optional`\[`str`]) – Backend name to filter by. * **min\_num\_qubits** (`Optional`\[`int`]) – Minimum number of qubits the backend has to have. * **instance** (`Optional`\[`str`]) – This is only supported for `ibm_quantum` runtime and is in the hub/group/project format. * **dynamic\_circuits** (`Optional`\[`bool`]) – Filter by whether the backend supports dynamic circuits. * **filters** (`Optional`\[`Callable`\[\[[`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.ibm_backend.IBMBackend"")], `bool`]]) – More complex filters, such as lambda functions. For example: ```python QiskitRuntimeService.backends( filters=lambda b: b.max_shots > 50000 ) QiskitRuntimeService.backends( filters=lambda x: (""rz"" in x.basis_gates ) ) ``` * **use\_fractional\_gates** (`bool`) – Set True to allow for the backends to include fractional gates in target. Currently this feature cannot be used simulataneously with the dynamic circuits, PEC, or PEA. When this flag is set, control flow instructions are automatically removed from the backend target. When you use the dynamic circuits feature (e.g. if\_else) in your algorithm, you must disable this flag to create executable ISA circuits. This flag might be modified or removed when our backend supports dynamic circuits and fractional gates simultaneously. * **\*\*kwargs** – Simple filters that require a specific value for an attribute in backend configuration or status. Examples: ```python # Get the operational real backends QiskitRuntimeService.backends(simulator=False, operational=True) # Get the backends with at least 127 qubits QiskitRuntimeService.backends(min_num_qubits=127) # Get the backends that support OpenPulse QiskitRuntimeService.backends(open_pulse=True) ``` For the full list of backend attributes, see the IBMBackend class documentation \<[api/qiskit/providers\_models](/api/qiskit/providers_models)> **Return type** `List`\[[`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.ibm_backend.IBMBackend"")] **Returns** The list of available backends that match the filter. **Raises** * **IBMInputValueError** – If an input is invalid. * **QiskitBackendNotFoundError** – If the backend is not in any instance. ### delete\_account Delete a saved account from disk. **Parameters** * **filename** (`Optional`\[`str`]) – Name of file from which to delete the account. * **name** (`Optional`\[`str`]) – Name of the saved account to delete. * **channel** (`Optional`\[`Literal`\[‘ibm\_cloud’, ‘ibm\_quantum’]]) – Channel type of the default account to delete. Ignored if account name is provided. **Return type** `bool` **Returns** True if the account was deleted. False if no account was found. ### delete\_job Delete a runtime job. Note that this operation cannot be reversed. **Parameters** **job\_id** (`str`) – ID of the job to delete. **Raises** * **RuntimeJobNotFound** – If the job doesn’t exist. * **IBMRuntimeError** – If the request failed. **Return type** `None` ### get\_backend Return a single backend matching the specified filtering. **Return type** `BackendV2` ### instances Return the IBM Quantum instances list currently in use for the session. **Return type** `List`\[`str`] **Returns** A list with instances currently in the session. ### job Retrieve a runtime job. **Parameters** **job\_id** (`str`) – Job ID. **Return type** `Union`\[[`RuntimeJob`](qiskit_ibm_runtime.RuntimeJob ""qiskit_ibm_runtime.runtime_job.RuntimeJob""), [`RuntimeJobV2`](qiskit_ibm_runtime.RuntimeJobV2 ""qiskit_ibm_runtime.runtime_job_v2.RuntimeJobV2"")] **Returns** Runtime job retrieved. **Raises** * **RuntimeJobNotFound** – If the job doesn’t exist. * **IBMRuntimeError** – If the request failed. ### jobs Retrieve all runtime jobs, subject to optional filtering. **Parameters** * **limit** (`Optional`\[`int`]) – Number of jobs to retrieve. `None` means no limit. * **skip** (`int`) – Starting index for the job retrieval. * **backend\_name** (`Optional`\[`str`]) – Name of the backend to retrieve jobs from. * **pending** (`Optional`\[`bool`]) – Filter by job pending state. If `True`, ‘QUEUED’ and ‘RUNNING’ jobs are included. If `False`, ‘DONE’, ‘CANCELLED’ and ‘ERROR’ jobs are included. * **program\_id** (`Optional`\[`str`]) – Filter by Program ID. * **instance** (`Optional`\[`str`]) – This is only supported for `ibm_quantum` runtime and is in the hub/group/project format. * **job\_tags** (`Optional`\[`List`\[`str`]]) – Filter by tags assigned to jobs. Matched jobs are associated with all tags. * **session\_id** (`Optional`\[`str`]) – Job ID of the first job in a runtime session. * **created\_after** (`Optional`\[`datetime`]) – Filter by the given start date, in local time. This is used to find jobs whose creation dates are after (greater than or equal to) this local date/time. * **created\_before** (`Optional`\[`datetime`]) – Filter by the given end date, in local time. This is used to find jobs whose creation dates are before (less than or equal to) this local date/time. * **descending** (`bool`) – If `True`, return the jobs in descending order of the job creation date (i.e. newest first) until the limit is reached. **Return type** `List`\[`Union`\[[`RuntimeJob`](qiskit_ibm_runtime.RuntimeJob ""qiskit_ibm_runtime.runtime_job.RuntimeJob""), [`RuntimeJobV2`](qiskit_ibm_runtime.RuntimeJobV2 ""qiskit_ibm_runtime.runtime_job_v2.RuntimeJobV2"")]] **Returns** A list of runtime jobs. **Raises** **IBMInputValueError** – If an input value is invalid. ### least\_busy Return the least busy available backend. **Parameters** * **min\_num\_qubits** (`Optional`\[`int`]) – Minimum number of qubits the backend has to have. * **instance** (`Optional`\[`str`]) – This is only supported for `ibm_quantum` runtime and is in the hub/group/project format. * **filters** (`Optional`\[`Callable`\[\[[`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.ibm_backend.IBMBackend"")], `bool`]]) – Filters can be defined as for the [`backends()`](#qiskit_ibm_runtime.QiskitRuntimeService.backends ""qiskit_ibm_runtime.QiskitRuntimeService.backends"") method. An example to get the operational backends with 5 qubits: ```python QiskitRuntimeService.least_busy(n_qubits=5, operational=True) ``` **Return type** [`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.ibm_backend.IBMBackend"") **Returns** The backend with the fewest number of pending jobs. **Raises** **QiskitBackendNotFoundError** – If no backend matches the criteria. ### run Execute the runtime program. **Parameters** * **program\_id** (`str`) – Program ID. * **inputs** (`Dict`) – Program input parameters. These input values are passed to the runtime program. * **options** (`Union`\[[`RuntimeOptions`](qiskit_ibm_runtime.RuntimeOptions ""qiskit_ibm_runtime.runtime_options.RuntimeOptions""), `Dict`, `None`]) – Runtime options that control the execution environment. See [`RuntimeOptions`](qiskit_ibm_runtime.RuntimeOptions ""qiskit_ibm_runtime.RuntimeOptions"") for all available options. * **callback** (`Optional`\[`Callable`]) – Callback function to be invoked for any interim results and final result. The callback function will receive 2 positional parameters: > 1. Job ID > 2. Job result. * **result\_decoder** (`Union`\[`Type`\[`ResultDecoder`], `Sequence`\[`Type`\[`ResultDecoder`]], `None`]) – A `ResultDecoder` subclass used to decode job results. If more than one decoder is specified, the first is used for interim results and the second final results. If not specified, a program-specific decoder or the default `ResultDecoder` is used. * **session\_id** (`Optional`\[`str`]) – Job ID of the first job in a runtime session. * **start\_session** (`Optional`\[`bool`]) – Set to True to explicitly start a runtime session. Defaults to False. **Return type** `Union`\[[`RuntimeJob`](qiskit_ibm_runtime.RuntimeJob ""qiskit_ibm_runtime.runtime_job.RuntimeJob""), [`RuntimeJobV2`](qiskit_ibm_runtime.RuntimeJobV2 ""qiskit_ibm_runtime.runtime_job_v2.RuntimeJobV2"")] **Returns** A `RuntimeJob` instance representing the execution. **Raises** * **IBMInputValueError** – If input is invalid. * **RuntimeProgramNotFound** – If the program cannot be found. * **IBMRuntimeError** – An error occurred running the program. ### save\_account Save the account to disk for future use. **Parameters** * **token** (`Optional`\[`str`]) – IBM Cloud API key or IBM Quantum API token. * **url** (`Optional`\[`str`]) – The API URL. Defaults to [https://cloud.ibm.com](https://cloud.ibm.com) (ibm\_cloud) or [https://auth.quantum-computing.ibm.com/api](https://auth.quantum-computing.ibm.com/api) (ibm\_quantum). * **instance** (`Optional`\[`str`]) – The CRN (ibm\_cloud) or hub/group/project (ibm\_quantum). * **channel** (`Optional`\[`Literal`\[‘ibm\_cloud’, ‘ibm\_quantum’]]) – Channel type. ibm\_cloud or ibm\_quantum. * **filename** (`Optional`\[`str`]) – Full path of the file where the account is saved. * **name** (`Optional`\[`str`]) – Name of the account to save. * **proxies** (`Optional`\[`dict`]) – Proxy configuration. Supported optional keys are `urls` (a dictionary mapping protocol or protocol and host to the URL of the proxy, documented at [https://docs.python-requests.org/en/latest/api/#requests.Session.proxies](https://docs.python-requests.org/en/latest/api/#requests.Session.proxies)), `username_ntlm`, `password_ntlm` (username and password to enable NTLM user authentication) * **verify** (`Optional`\[`bool`]) – Verify the server’s TLS certificate. * **overwrite** (`Optional`\[`bool`]) – `True` if the existing account is to be overwritten. * **channel\_strategy** (`Optional`\[`str`]) – Error mitigation strategy. * **set\_as\_default** (`Optional`\[`bool`]) – If `True`, the account is saved in filename, as the default account. * **private\_endpoint** (`Optional`\[`bool`]) – Connect to private API URL. **Return type** `None` ### saved\_accounts List the accounts saved on disk. **Parameters** * **default** (`Optional`\[`bool`]) – If set to True, only default accounts are returned. * **channel** (`Optional`\[`Literal`\[‘ibm\_cloud’, ‘ibm\_quantum’]]) – Channel type. ibm\_cloud or ibm\_quantum. * **filename** (`Optional`\[`str`]) – Name of file whose accounts are returned. * **name** (`Optional`\[`str`]) – If set, only accounts with the given name are returned. **Return type** `dict` **Returns** A dictionary with information about the accounts saved on disk. **Raises** **ValueError** – If an invalid account is found on disk. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.QiskitRuntimeService.mdx "--- title: RuntimeDecoder description: API reference for qiskit_ibm_runtime.RuntimeDecoder in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.RuntimeDecoder --- # RuntimeDecoder JSON Decoder used by runtime service. `object_hook`, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given `dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). `object_pairs_hook`, if specified will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of `object_pairs_hook` will be used instead of the `dict`. This feature can be used to implement custom decoders. If `object_hook` is also defined, the `object_pairs_hook` takes priority. `parse_float`, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num\_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). `parse_int`, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num\_str). This can be used to use another datatype or parser for JSON integers (e.g. float). `parse_constant`, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. If `strict` is false (true is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0-31 range, including `'\t'` (tab), `'\n'`, `'\r'` and `'\0'`. ## Methods ### decode )""> Return the Python representation of `s` (a `str` instance containing a JSON document). ### object\_hook Called to decode object. **Return type** `Any` ### raw\_decode Decode a JSON document from `s` (a `str` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in `s` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.RuntimeDecoder.mdx "--- title: RuntimeEncoder description: API reference for qiskit_ibm_runtime.RuntimeEncoder in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.RuntimeEncoder --- # RuntimeEncoder JSON Encoder used by runtime service. Constructor for JSONEncoder, with sensible defaults. If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped. If ensure\_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure\_ascii is false, the output can contain non-ASCII characters. If check\_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an RecursionError). Otherwise, no such check takes place. If allow\_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort\_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation. If specified, separators should be an (item\_separator, key\_separator) tuple. The default is (’, ‘, ‘: ‘) if *indent* is `None` and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace. If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a `TypeError`. ## Attributes ### item\_separator ### key\_separator ## Methods ### default Implement this method in a subclass such that it returns a serializable object for `o`, or calls the base implementation (to raise a `TypeError`). For example, to support arbitrary iterators, you could implement default like this: ```python def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o) ``` **Return type** `Any` ### encode Return a JSON string representation of a Python data structure. ```python >>> from json.encoder import JSONEncoder >>> JSONEncoder().encode({""foo"": [""bar"", ""baz""]}) '{""foo"": [""bar"", ""baz""]}' ``` ### iterencode Encode the given object and yield each string representation as available. For example: ```python for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) ``` ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.RuntimeEncoder.mdx "--- title: RuntimeJob description: API reference for qiskit_ibm_runtime.RuntimeJob in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.RuntimeJob --- # RuntimeJob Representation of a runtime primitive execution. A new `RuntimeJob` instance is returned when you call [`QiskitRuntimeService.run`](qiskit_ibm_runtime.QiskitRuntimeService#run ""qiskit_ibm_runtime.QiskitRuntimeService.run"") to execute a runtime primitive, or [`QiskitRuntimeService.job`](qiskit_ibm_runtime.QiskitRuntimeService#job ""qiskit_ibm_runtime.QiskitRuntimeService.job"") to retrieve a previously executed job. If the primitive execution is successful, you can inspect the job’s status by calling [`status()`](#qiskit_ibm_runtime.RuntimeJob.status ""qiskit_ibm_runtime.RuntimeJob.status""). Job status can be one of the `JobStatus` members. Some of the methods in this class are blocking, which means control may not be returned immediately. [`result()`](#qiskit_ibm_runtime.RuntimeJob.result ""qiskit_ibm_runtime.RuntimeJob.result"") is an example of a blocking method: ```python job = service.run(...) try: job_result = job.result() # It will block until the job finishes. print(""The job finished with result {}"".format(job_result)) except RuntimeJobFailureError as ex: print(""Job failed!: {}"".format(ex)) ``` If the primitive has any interim results, you can use the `callback` parameter of the [`run()`](qiskit_ibm_runtime.QiskitRuntimeService#run ""qiskit_ibm_runtime.QiskitRuntimeService.run"") method to stream the interim results along with the final result. Alternatively, you can use the [`stream_results()`](#qiskit_ibm_runtime.RuntimeJob.stream_results ""qiskit_ibm_runtime.RuntimeJob.stream_results"") method to stream the results at a later time, but before the job finishes. RuntimeJob constructor. **Parameters** * **backend** (`Backend`) – The backend instance used to run this job. * **api\_client** (`RuntimeClient`) – Object for connecting to the server. * **client\_params** (`ClientParameters`) – Parameters used for server connection. * **job\_id** (`str`) – Job ID. * **program\_id** (`str`) – ID of the program this job is for. * **params** (`Optional`\[`Dict`]) – Job parameters. * **creation\_date** (`Optional`\[`str`]) – Job creation date, in UTC. * **user\_callback** (`Optional`\[`Callable`]) – User callback function. * **result\_decoder** (`Union`\[`Type`\[`ResultDecoder`], `Sequence`\[`Type`\[`ResultDecoder`]], `None`]) – A `ResultDecoder` subclass used to decode job results. * **image** (`Optional`\[`str`]) – Runtime image used for this job: image\_name:tag. * **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – Runtime service. * **session\_id** (`Optional`\[`str`]) – Job ID of the first job in a runtime session. * **tags** (`Optional`\[`List`]) – Tags assigned to the job. * **version** (`Optional`\[`int`]) – Primitive version. ## Attributes ### ERROR ### JOB\_FINAL\_STATES ### creation\_date Job creation date in local time. **Return type** `Optional`\[`datetime`] **Returns** The job creation date as a datetime object, in local time, or `None` if creation date is not available. ### image Return the runtime image used for the job. **Returns** image\_name:tag or “” if the default image is used. **Return type** Runtime image ### inputs Job input parameters. **Return type** `Dict` **Returns** Input parameters used in this job. ### instance For ibm\_quantum channel jobs, return the instance where the job was run. For ibm\_cloud, None is returned. **Return type** `Optional`\[`str`] ### primitive\_id Primitive name. :rtype: `str` :returns: Primitive this job is for. ### program\_id Program ID. **Return type** `str` **Returns** ID of the program this job is for. ### session\_id Session ID. **Return type** `str` **Returns** Session ID. None if the backend is a simulator. ### tags Job tags. **Return type** `List` **Returns** Tags assigned to the job that can be used for filtering. ### usage\_estimation Return the usage estimation infromation for this job. **Return type** `Dict`\[`str`, `Any`] **Returns** `quantum_seconds` which is the estimated system execution time of the job in seconds. Quantum time represents the time that the system is dedicated to processing your job. ### version ## Methods ### backend Return the backend where this job was executed. Retrieve data again if backend is None. **Raises** **IBMRuntimeError** – If a network error occurred. **Return type** `Optional`\[`Backend`] ### cancel Cancel the job. **Raises** * **RuntimeInvalidStateError** – If the job is in a state that cannot be cancelled. * **IBMRuntimeError** – If unable to cancel job. **Return type** `None` ### cancel\_result\_streaming Cancel result streaming. **Return type** `None` ### cancelled Return whether the job has been cancelled. **Return type** `bool` ### done Return whether the job has successfully run. **Return type** `bool` ### error\_message Returns the reason if the job failed. **Return type** `Optional`\[`str`] **Returns** Error message string or `None`. ### errored Return whether the job has failed. **Return type** `bool` ### in\_final\_state Return whether the job is in a final job state such as `DONE` or `ERROR`. **Return type** `bool` ### interim\_results Return the interim results of the job. **Parameters** **decoder** (`Optional`\[`Type`\[`ResultDecoder`]]) – A `ResultDecoder` subclass used to decode interim results. **Return type** `Any` **Returns** Runtime job interim results. **Raises** **RuntimeJobFailureError** – If the job failed. ### job\_id Return a unique id identifying the job. **Return type** `str` ### logs Return job logs. Job logs are only available after the job finishes. **Return type** `str` **Returns** Job logs, including standard output and error. **Raises** **IBMRuntimeError** – If a network error occurred. ### metrics Return job metrics. **Return type** `Dict`\[`str`, `Any`] **Returns** Job metrics, which includes timestamp information. **Raises** **IBMRuntimeError** – If a network error occurred. ### properties Return the backend properties for this job. **Parameters** **refresh** (`bool`) – If `True`, re-query the server for the backend properties. Otherwise, return a cached version. **Return type** `Optional`\[`BackendProperties`] **Returns** The backend properties used for this job, at the time the job was run, or `None` if properties are not available. ### queue\_info Return queue information for this job. The queue information may include queue position, estimated start and end time, and dynamic priorities for the hub, group, and project. See `QueueInfo` for more information. The queue information is calculated after the job enters the queue. Therefore, some or all of the information may not be immediately available, and this method may return `None`. **Return type** `Optional`\[`QueueInfo`] **Returns** A `QueueInfo` instance that contains queue information for this job, or `None` if queue information is unknown or not applicable. ### queue\_position Return the position of the job in the server queue. The position returned is within the scope of the provider and may differ from the global queue position. **Parameters** **refresh** (`bool`) – If `True`, re-query the server to get the latest value. Otherwise return the cached value. **Return type** `Optional`\[`int`] **Returns** Position in the queue or `None` if position is unknown or not applicable. ### result Return the results of the job. **Parameters** * **timeout** (`Optional`\[`float`]) – Number of seconds to wait for job. * **decoder** (`Optional`\[`Type`\[`ResultDecoder`]]) – A `ResultDecoder` subclass used to decode job results. **Return type** `Any` **Returns** Runtime job result. **Raises** * **RuntimeJobFailureError** – If the job failed. * **RuntimeJobMaxTimeoutError** – If the job does not complete within given timeout. * **RuntimeInvalidStateError** – If the job was cancelled, and attempting to retrieve result. ### running Return whether the job is actively running. **Return type** `bool` ### status Return the status of the job. **Return type** `JobStatus` **Returns** Status of this job. ### stream\_results Start streaming job results. **Parameters** * **callback** (`Callable`) – Callback function to be invoked for any interim results and final result. The callback function will receive 2 positional parameters: > 1. Job ID > 2. Job result. * **decoder** (`Optional`\[`Type`\[`ResultDecoder`]]) – A `ResultDecoder` subclass used to decode job results. **Raises** **RuntimeInvalidStateError** – If a callback function is already streaming results or if the job already finished. **Return type** `None` ### submit Unsupported method. .. note: ```python This method is not supported, please use :meth:`~qiskit_ibm_runtime.QiskitRuntimeService.run` to submit a job. ``` **Raises** **NotImplementedError** – Upon invocation. **Return type** `None` ### update\_tags Update the tags associated with this job. **Parameters** **new\_tags** (`List`\[`str`]) – New tags to assign to the job. **Return type** `List`\[`str`] **Returns** The new tags associated with this job. **Raises** **IBMApiError** – If an unexpected error occurred when communicating with the server or updating the job tags. ### wait\_for\_final\_state Poll for the job status from the API until the status is in a final state. **Parameters** **timeout** (`Optional`\[`float`]) – Seconds to wait for the job. If `None`, wait indefinitely. **Raises** **RuntimeJobTimeoutError** – If the job does not complete within given timeout. **Return type** `None` ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.RuntimeJob.mdx "--- title: RuntimeJobV2 description: API reference for qiskit_ibm_runtime.RuntimeJobV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.RuntimeJobV2 --- # RuntimeJobV2 Representation of a runtime V2 primitive exeuction. RuntimeJob constructor. **Parameters** * **backend** (`Backend`) – The backend instance used to run this job. * **api\_client** (`RuntimeClient`) – Object for connecting to the server. * **client\_params** (`ClientParameters`) – Parameters used for server connection. * **job\_id** (`str`) – Job ID. * **program\_id** (`str`) – ID of the program this job is for. * **params** (`Optional`\[`Dict`]) – Job parameters. * **creation\_date** (`Optional`\[`str`]) – Job creation date, in UTC. * **user\_callback** (`Optional`\[`Callable`]) – User callback function. * **result\_decoder** (`Union`\[`Type`\[`ResultDecoder`], `Sequence`\[`Type`\[`ResultDecoder`]], `None`]) – A `ResultDecoder` subclass used to decode job results. * **image** (`Optional`\[`str`]) – Runtime image used for this job: image\_name:tag. * **service** ([`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")) – Runtime service. * **session\_id** (`Optional`\[`str`]) – Job ID of the first job in a runtime session. * **tags** (`Optional`\[`List`]) – Tags assigned to the job. * **version** (`Optional`\[`int`]) – Primitive version. ## Attributes ### ERROR ### JOB\_FINAL\_STATES ### creation\_date Job creation date in local time. **Return type** `Optional`\[`datetime`] **Returns** The job creation date as a datetime object, in local time, or `None` if creation date is not available. ### image Return the runtime image used for the job. **Returns** image\_name:tag or “” if the default image is used. **Return type** Runtime image ### inputs Job input parameters. **Return type** `Dict` **Returns** Input parameters used in this job. ### instance For ibm\_quantum channel jobs, return the instance where the job was run. For ibm\_cloud, None is returned. **Return type** `Optional`\[`str`] ### primitive\_id Primitive name. :rtype: `str` :returns: Primitive this job is for. ### program\_id Program ID. **Return type** `str` **Returns** ID of the program this job is for. ### session\_id Session ID. **Return type** `str` **Returns** Session ID. None if the backend is a simulator. ### tags Job tags. **Return type** `List` **Returns** Tags assigned to the job that can be used for filtering. ### usage\_estimation Return the usage estimation infromation for this job. **Return type** `Dict`\[`str`, `Any`] **Returns** `quantum_seconds` which is the estimated system execution time of the job in seconds. Quantum time represents the time that the system is dedicated to processing your job. ## Methods ### backend Return the backend where this job was executed. Retrieve data again if backend is None. **Raises** **IBMRuntimeError** – If a network error occurred. **Return type** `Optional`\[`Backend`] ### cancel Cancel the job. **Raises** * **RuntimeInvalidStateError** – If the job is in a state that cannot be cancelled. * **IBMRuntimeError** – If unable to cancel job. **Return type** `None` ### cancel\_result\_streaming Cancel result streaming. **Return type** `None` ### cancelled Return whether the job has been cancelled. **Return type** `bool` ### done Return whether the job has successfully run. **Return type** `bool` ### error\_message Returns the reason if the job failed. **Return type** `Optional`\[`str`] **Returns** Error message string or `None`. ### errored Return whether the job has failed. **Return type** `bool` ### in\_final\_state Return whether the job is in a final job state such as `DONE` or `ERROR`. **Return type** `bool` ### interim\_results Return the interim results of the job. **Parameters** **decoder** (`Optional`\[`Type`\[`ResultDecoder`]]) – A `ResultDecoder` subclass used to decode interim results. **Return type** `Any` **Returns** Runtime job interim results. **Raises** **RuntimeJobFailureError** – If the job failed. ### job\_id Return a unique id identifying the job. **Return type** `str` ### logs Return job logs. Job logs are only available after the job finishes. **Return type** `str` **Returns** Job logs, including standard output and error. **Raises** **IBMRuntimeError** – If a network error occurred. ### metrics Return job metrics. **Return type** `Dict`\[`str`, `Any`] **Returns** Job metrics, which includes timestamp information. **Raises** **IBMRuntimeError** – If a network error occurred. ### properties Return the backend properties for this job. **Parameters** **refresh** (`bool`) – If `True`, re-query the server for the backend properties. Otherwise, return a cached version. **Return type** `Optional`\[`BackendProperties`] **Returns** The backend properties used for this job, at the time the job was run, or `None` if properties are not available. ### result Return the results of the job. **Parameters** * **timeout** (`Optional`\[`float`]) – Number of seconds to wait for job. * **decoder** (`Optional`\[`Type`\[`ResultDecoder`]]) – A `ResultDecoder` subclass used to decode job results. **Return type** `Any` **Returns** Runtime job result. **Raises** * **RuntimeJobFailureError** – If the job failed. * **RuntimeJobMaxTimeoutError** – If the job does not complete within given timeout. * **RuntimeInvalidStateError** – If the job was cancelled, and attempting to retrieve result. ### running Return whether the job is actively running. **Return type** `bool` ### status Return the status of the job. **Return type** `Literal`\[‘INITIALIZING’, ‘QUEUED’, ‘RUNNING’, ‘CANCELLED’, ‘DONE’, ‘ERROR’] **Returns** Status of this job. ### stream\_results Start streaming job results. **Parameters** * **callback** (`Callable`) – Callback function to be invoked for any interim results and final result. The callback function will receive 2 positional parameters: > 1. Job ID > 2. Job result. * **decoder** (`Optional`\[`Type`\[`ResultDecoder`]]) – A `ResultDecoder` subclass used to decode job results. **Raises** **RuntimeInvalidStateError** – If a callback function is already streaming results or if the job already finished. **Return type** `None` ### update\_tags Update the tags associated with this job. **Parameters** **new\_tags** (`List`\[`str`]) – New tags to assign to the job. **Return type** `List`\[`str`] **Returns** The new tags associated with this job. **Raises** **IBMApiError** – If an unexpected error occurred when communicating with the server or updating the job tags. ### wait\_for\_final\_state Poll for the job status from the API until the status is in a final state. **Parameters** **timeout** (`Optional`\[`float`]) – Seconds to wait for the job. If `None`, wait indefinitely. **Raises** **RuntimeJobTimeoutError** – If the job does not complete within given timeout. **Return type** `None` ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.RuntimeJobV2.mdx "--- title: RuntimeOptions description: API reference for qiskit_ibm_runtime.RuntimeOptions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.RuntimeOptions --- # RuntimeOptions Class for representing generic runtime execution options. RuntimeOptions constructor. **Parameters** * **backend** (*Optional\[str | Backend]*) – target backend to run on. This is required for `ibm_quantum` channel. * **image** (*Optional\[str]*) – the runtime image used to execute the primitive, specified in the form of `image_name:tag`. Not all accounts are authorized to select a different image. * **log\_level** (*Optional\[str]*) – logging level to set in the execution environment. The valid log levels are: `DEBUG`, `INFO`, `WARNING`, `ERROR`, and `CRITICAL`. The default level is `WARNING`. * **instance** (*Optional\[str]*) – The hub/group/project to use, in that format. This is only supported for `ibm_quantum` channel. If `None`, a hub/group/project that provides access to the target backend is randomly selected. * **job\_tags** (*Optional\[List\[str]]*) – Tags to be assigned to the job. The tags can subsequently be used as a filter in the `jobs()` function call. * **max\_execution\_time** (*Optional\[int]*) – Maximum execution time in seconds, which is based on system execution time (not wall clock time). System execution time is the amount of time that the system is dedicated to processing your job. If a job exceeds this time limit, it is forcibly cancelled. Simulator jobs continue to use wall clock time. * **session\_time** (*Optional\[int]*) – Length of session in seconds. ## Attributes ### backend ### image ### instance ### job\_tags ### log\_level ### max\_execution\_time ### session\_time ## Methods ### get\_backend\_name Get backend name. **Return type** `str` ### validate Validate options. **Parameters** **channel** (`str`) – channel type. **Raises** **IBMInputValueError** – If one or more option is invalid. **Return type** `None` ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.RuntimeOptions.mdx "--- title: Sampler description: API reference for qiskit_ibm_runtime.Sampler in_page_toc_min_heading_level: 1 python_api_type: attribute python_api_name: qiskit_ibm_runtime.Sampler --- # Sampler alias of [`SamplerV1`](qiskit_ibm_runtime.SamplerV1 ""qiskit_ibm_runtime.sampler.SamplerV1"") ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.Sampler.mdx "--- title: SamplerV1 description: API reference for qiskit_ibm_runtime.SamplerV1 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.SamplerV1 --- # SamplerV1 Class for interacting with Qiskit Runtime Sampler primitive service. Qiskit Runtime Sampler primitive service calculates quasi-probability distribution of bitstrings from quantum circuits. The [`run()`](#qiskit_ibm_runtime.SamplerV1.run ""qiskit_ibm_runtime.SamplerV1.run"") method can be used to submit circuits and parameters to the Sampler primitive. You are encouraged to use [`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.Session"") to open a session, during which you can invoke one or more primitives. Jobs submitted within a session are prioritized by the scheduler. Example: ```python from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler service = QiskitRuntimeService(channel=""ibm_cloud"") # Bell Circuit qr = QuantumRegister(2, name=""qr"") cr = ClassicalRegister(2, name=""cr"") qc = QuantumCircuit(qr, cr, name=""bell"") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr, cr) with Session(service, backend=""ibmq_qasm_simulator"") as session: sampler = Sampler(session=session) job = sampler.run(qc, shots=1024) print(f""Job ID: {job.job_id()}"") print(f""Job result: {job.result()}"") # You can run more jobs inside the session ``` Initializes the Sampler primitive. **Parameters** * **backend** (`Union`\[`str`, [`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.ibm_backend.IBMBackend""), `None`]) – Backend to run the primitive. This can be a backend name or an [`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.IBMBackend"") instance. If a name is specified, the default account (e.g. `QiskitRuntimeService()`) is used. * **session** (`Optional`\[[`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session"")]) – Session in which to call the primitive. If both `session` and `backend` are specified, `session` takes precedence. If neither is specified, and the primitive is created inside a [`qiskit_ibm_runtime.Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.Session"") context manager, then the session is used. Otherwise if IBM Cloud channel is used, a default backend is selected. * **options** (`Union`\[`Dict`, [`Options`](qiskit_ibm_runtime.options.Options ""qiskit_ibm_runtime.options.options.Options""), `None`]) – Primitive options, see `Options` for detailed description. The `backend` keyword is still supported but is deprecated. ## Attributes ### options Return options values for the sampler. :rtype: `Options` :returns: options ### session Return session used by this primitive. **Return type** `Optional`\[[`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session"")] **Returns** Session used by this primitive, or `None` if session is not used. ### version ## Methods ### run Submit a request to the sampler primitive. **Parameters** * **circuits** (*QuantumCircuit | Sequence\[QuantumCircuit]*) – A (parameterized) `QuantumCircuit` or a list of (parameterized) `QuantumCircuit`. * **parameter\_values** (*Sequence\[float] | Sequence\[Sequence\[float]] | None*) – Concrete parameters to be bound. * **\*\*kwargs** – Individual options to overwrite the default primitive options. These include the runtime options in [`qiskit_ibm_runtime.RuntimeOptions`](qiskit_ibm_runtime.RuntimeOptions ""qiskit_ibm_runtime.RuntimeOptions""). **Return type** [RuntimeJob](qiskit_ibm_runtime.RuntimeJob ""qiskit_ibm_runtime.RuntimeJob"") **Returns** Submitted job. The result of the job is an instance of `qiskit.primitives.SamplerResult`. **Raises** **ValueError** – Invalid arguments are given. ### set\_options Set options values for the sampler. **Parameters** **\*\*fields** – The fields to update the options **Return type** `None` ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.SamplerV1.mdx "--- title: SamplerV2 description: API reference for qiskit_ibm_runtime.SamplerV2 in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.SamplerV2 --- # SamplerV2 Class for interacting with Qiskit Runtime Sampler primitive service. This class supports version 2 of the Sampler interface, which uses different input and output formats than version 1. Qiskit Runtime Sampler primitive returns the sampled result according to the specified output type. For example, it returns a bitstring for each shot if measurement level 2 (bits) is requested. The [`run()`](#qiskit_ibm_runtime.SamplerV2.run ""qiskit_ibm_runtime.SamplerV2.run"") method can be used to submit circuits and parameters to the Sampler primitive. Initializes the Sampler primitive. **Parameters** * **mode** (`Union`\[`BackendV1`, `BackendV2`, [`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session""), [`Batch`](qiskit_ibm_runtime.Batch ""qiskit_ibm_runtime.batch.Batch""), `str`, `None`]) – The execution mode used to make the primitive query. It can be: * A `Backend` if you are using job mode. * A [`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.Session"") if you are using session execution mode. * A [`Batch`](qiskit_ibm_runtime.Batch ""qiskit_ibm_runtime.Batch"") if you are using batch execution mode. Refer to the [Qiskit Runtime documentation](/run). for more information about the `Execution modes`. * **backend** (`Union`\[`str`, `BackendV1`, `BackendV2`, `None`]) – Backend to run the primitive. This can be a backend name or an [`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.IBMBackend"") instance. If a name is specified, the default account (e.g. `QiskitRuntimeService()`) is used. * **session** (`Optional`\[[`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session"")]) – Session in which to call the primitive. If both `session` and `backend` are specified, `session` takes precedence. If neither is specified, and the primitive is created inside a [`qiskit_ibm_runtime.Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.Session"") context manager, then the session is used. Otherwise if IBM Cloud channel is used, a default backend is selected. * **options** (`Union`\[`Dict`, [`SamplerOptions`](qiskit_ibm_runtime.options.SamplerOptions ""qiskit_ibm_runtime.options.sampler_options.SamplerOptions""), `None`]) – Sampler options, see `SamplerOptions` for detailed description. **Raises** **NotImplementedError** – If “q-ctrl” channel strategy is used. ## Attributes ### mode Return the execution mode used by this primitive. **Return type** Optional\[[Session](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.Session"") | [Batch](qiskit_ibm_runtime.Batch ""qiskit_ibm_runtime.Batch"")] **Returns** Mode used by this primitive, or `None` if an execution mode is not used. ### options Return options **Return type** `TypeVar`(`OptionsT`, bound= `BaseOptions`) ### session Return session used by this primitive. **Return type** `Optional`\[[`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session"")] **Returns** Session used by this primitive, or `None` if session is not used. ### version ## Methods ### run Submit a request to the sampler primitive. **Parameters** * **pubs** (*Iterable\[SamplerPubLike]*) – An iterable of pub-like objects. For example, a list of circuits or tuples `(circuit, parameter_values)`. * **shots** (*int | None*) – The total number of shots to sample for each sampler pub that does not specify its own shots. If `None`, the primitive’s default shots value will be used, which can vary by implementation. **Return type** [RuntimeJobV2](qiskit_ibm_runtime.RuntimeJobV2 ""qiskit_ibm_runtime.RuntimeJobV2"") **Returns** Submitted job. The result of the job is an instance of `qiskit.primitives.containers.PrimitiveResult`. **Raises** **ValueError** – Invalid arguments are given. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.SamplerV2.mdx "--- title: Session description: API reference for qiskit_ibm_runtime.Session in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.Session --- # Session Class for creating a Qiskit Runtime session. A Qiskit Runtime `session` allows you to group a collection of iterative calls to the quantum computer. A session is started when the first job within the session is started. Subsequent jobs within the session are prioritized by the scheduler. You can open a Qiskit Runtime session using this `Session` class and submit jobs to one or more primitives. For example: ```python from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import Session, SamplerV2 as Sampler service = QiskitRuntimeService() backend = service.least_busy(operational=True, simulator=False) # Bell Circuit qr = QuantumRegister(2, name=""qr"") cr = ClassicalRegister(2, name=""cr"") qc = QuantumCircuit(qr, cr, name=""bell"") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr, cr) pm = generate_preset_pass_manager(backend=backend, optimization_level=1) isa_circuit = pm.run(qc) with Session(backend=backend) as session: sampler = Sampler(session=session) job = sampler.run([isa_circuit]) pub_result = job.result()[0] print(f""Sampler job ID: {job.job_id()}"") print(f""Counts: {pub_result.data.cr.get_counts()}"") ``` Session constructor. **Parameters** * **service** (`Optional`\[[`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")]) – Optional instance of the `QiskitRuntimeService` class. If `None`, the service associated with the backend, if known, is used. Otherwise `QiskitRuntimeService()` is used to initialize your default saved account. * **backend** (`Union`\[`str`, `BackendV1`, `BackendV2`, `None`]) – Optional instance of `Backend` class or string name of backend. If not specified, a backend will be selected automatically (IBM Cloud channel only). * **max\_time** (`Union`\[`int`, `str`, `None`]) – Maximum amount of time, a runtime session can be open before being forcibly closed. Can be specified as seconds (int) or a string like “2h 30m 40s”. This value must be less than the [system imposed maximum](/run/max-execution-time). **Raises** **ValueError** – If an input value is invalid. ## Attributes ### service Return service associated with this session. **Return type** [`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"") **Returns** [`qiskit_ibm_runtime.QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.QiskitRuntimeService"") associated with this session. ### session\_id Return the session ID. **Return type** `Optional`\[`str`] **Returns** Session ID. None if the backend is a simulator. ## Methods ### backend Return backend for this session. **Return type** `Optional`\[`str`] **Returns** Backend for this session. None if unknown. ### cancel Cancel all pending jobs in a session. **Return type** `None` ### close Close the session so new jobs will no longer be accepted, but existing queued or running jobs will run to completion. The session will be terminated once there are no more pending jobs. **Return type** `None` ### details Return session details. **Return type** `Optional`\[`Dict`\[`str`, `Any`]] **Returns** A dictionary with the sessions details. * `id`: id of the session. * `backend_name`: backend used for the session. * `interactive_timeout`: The maximum idle time (in seconds) between jobs that is allowed to occur before the session is deactivated. * `max_time`: Maximum allowed time (in seconds) for the session, subject to plan limits. * `active_timeout`: The maximum time (in seconds) a session can stay active. * `state`: State of the session - open, active, inactive, or closed. * `accepting_jobs`: Whether or not the session is accepting jobs. * `last_job_started`: Timestamp of when the last job in the session started. * `last_job_completed`: Timestamp of when the last job in the session completed. * `started_at`: Timestamp of when the session was started. * `closed_at`: Timestamp of when the session was closed. * `activated_at`: Timestamp of when the session state was changed to active. * `mode`: Execution mode of the session. * `usage_time`: The usage time, in seconds, of this Session or Batch. Usage is defined as the time a quantum system is committed to complete a job. ### from\_id Construct a Session object with a given session\_id **Parameters** * **session\_id** (`str`) – the id of the session to be created. This must be an already existing session id. * **service** (`Optional`\[[`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.qiskit_runtime_service.QiskitRuntimeService"")]) – **instance of the `QiskitRuntimeService` class.** If `None`, `QiskitRuntimeService()` is used to initialize your default saved account. **Raises:** IBMInputValueError: If given session\_id does not exist. **Return type** [`Session`](#qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.session.Session"") **Returns** A new Session with the given `session_id` ### run Run a program in the session. **Parameters** * **program\_id** (`str`) – Program ID. * **inputs** (`Dict`) – Program input parameters. These input values are passed to the runtime program. * **options** (`Optional`\[`Dict`]) – Runtime options that control the execution environment. See [`qiskit_ibm_runtime.RuntimeOptions`](qiskit_ibm_runtime.RuntimeOptions ""qiskit_ibm_runtime.RuntimeOptions"") for all available options. * **callback** (`Optional`\[`Callable`]) – Callback function to be invoked for any interim results and final result. **Return type** `Union`\[[`RuntimeJob`](qiskit_ibm_runtime.RuntimeJob ""qiskit_ibm_runtime.runtime_job.RuntimeJob""), [`RuntimeJobV2`](qiskit_ibm_runtime.RuntimeJobV2 ""qiskit_ibm_runtime.runtime_job_v2.RuntimeJobV2"")] **Returns** Submitted job. ### status Return current session status. **Return type** `Optional`\[`str`] **Returns** Session status as a string. * `Pending`: Session is created but not active. It will become active when the next job of this session is dequeued. * `In progress, accepting new jobs`: session is active and accepting new jobs. * `In progress, not accepting new jobs`: session is active and not accepting new jobs. * `Closed`: max\_time expired or session was explicitly closed. * `None`: status details are not available. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.Session.mdx "--- title: ConvertIdToDelay description: API reference for qiskit_ibm_runtime.transpiler.passes.ConvertIdToDelay in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.transpiler.passes.ConvertIdToDelay --- # ConvertIdToDelay Convert `qiskit.circuit.library.standard_gates.IGate` to a delay of the corresponding length. Convert `qiskit.circuit.library.IGate` to a Convert `qiskit.circuit.Delay`. **Parameters** * **duration** – Duration of the delay to replace the identity gate with. * **gate** (`str`) – Single qubit gate to extract duration from. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### \_\_call\_\_ Runs the pass on circuit. **Parameters** * **circuit** (*QuantumCircuit*) – The dag on which the pass is run. * **property\_set** (*PropertySet | dict | None*) – Input/output property set. An analysis pass might change the property set in-place. **Return type** QuantumCircuit **Returns** If on transformation pass, the resulting QuantumCircuit. If analysis pass, the input circuit. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** (`Any`) – Qiskit IR to optimize. * **state** (`PassManagerState`) – State associated with workflow execution by the pass manager itself. * **callback** (`Optional`\[`Callable`]) – A callback function which is caller per execution of optimization task. **Return type** `tuple`\[`Any`, `PassManagerState`] **Returns** Optimized Qiskit IR and state of the workflow. ### name Name of the pass. **Return type** `str` ### run Run a pass on the DAGCircuit. This is implemented by the pass developer. **Parameters** **dag** (`DAGCircuit`) – the dag on which the pass is run. **Raises** **NotImplementedError** – when this is left unimplemented for a pass. **Return type** `DAGCircuit` ### update\_status Update workflow status. **Parameters** * **state** (`PassManagerState`) – Pass manager state to update. * **run\_state** (`RunState`) – Completion status of current task. **Return type** `PassManagerState` **Returns** Updated pass manager state. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.transpiler.passes.ConvertIdToDelay.mdx "--- title: ALAPScheduleAnalysis description: API reference for qiskit_ibm_runtime.transpiler.passes.scheduling.ALAPScheduleAnalysis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.transpiler.passes.scheduling.ALAPScheduleAnalysis --- # ALAPScheduleAnalysis Dynamic circuits as-late-as-possible (ALAP) scheduling analysis pass. This is a scheduler designed to work for the unique scheduling constraints of the dynamic circuits backends due to the limitations imposed by hardware. This is expected to evolve over time as the dynamic circuit backends also change. In its current form this is similar to Qiskit’s ALAP scheduler in which instructions start as late as possible. The primary differences are that: * **Resets and control-flow currently trigger the end of a “quantum block”. The period between the end** of the block and the next is *nondeterministic* ie., we do not know when the next block will begin (as we could be evaluating a classical function of nondeterministic length) and therefore the next block starts at a *relative* t=0. * During a measurement it is possible to apply gates in parallel on disjoint qubits. * Measurements and resets on disjoint qubits happen simultaneously and are part of the same block. Scheduler for dynamic circuit backends. **Parameters** * **durations** (`InstructionDurations`) – Durations of instructions to be used in scheduling. * **block\_ordering\_callable** (`Optional`\[`Callable`\[\[`DAGCircuit`], `Generator`\[`DAGOpNode`, `None`, `None`]]]) – A callable used to produce an ordering of the nodes to minimize the number of blocks needed. If not provided, `block_order_op_nodes()` will be used. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### \_\_call\_\_ Runs the pass on circuit. **Parameters** * **circuit** (*QuantumCircuit*) – The dag on which the pass is run. * **property\_set** (*PropertySet | dict | None*) – Input/output property set. An analysis pass might change the property set in-place. **Return type** QuantumCircuit **Returns** If on transformation pass, the resulting QuantumCircuit. If analysis pass, the input circuit. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** (`Any`) – Qiskit IR to optimize. * **state** (`PassManagerState`) – State associated with workflow execution by the pass manager itself. * **callback** (`Optional`\[`Callable`]) – A callback function which is caller per execution of optimization task. **Return type** `tuple`\[`Any`, `PassManagerState`] **Returns** Optimized Qiskit IR and state of the workflow. ### name Name of the pass. **Return type** `str` ### run Run the ASAPSchedule pass on dag. :type dag: `DAGCircuit` :param dag: DAG to schedule. :type dag: DAGCircuit **Raises** * **TranspilerError** – if the circuit is not mapped on physical qubits. * **TranspilerError** – if conditional bit is added to non-supported instruction. **Return type** `None` **Returns** The scheduled DAGCircuit. ### update\_status Update workflow status. **Parameters** * **state** (`PassManagerState`) – Pass manager state to update. * **run\_state** (`RunState`) – Completion status of current task. **Return type** `PassManagerState` **Returns** Updated pass manager state. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.transpiler.passes.scheduling.ALAPScheduleAnalysis.mdx "--- title: ASAPScheduleAnalysis description: API reference for qiskit_ibm_runtime.transpiler.passes.scheduling.ASAPScheduleAnalysis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.transpiler.passes.scheduling.ASAPScheduleAnalysis --- # ASAPScheduleAnalysis Dynamic circuits as-soon-as-possible (ASAP) scheduling analysis pass. This is a scheduler designed to work for the unique scheduling constraints of the dynamic circuits backends due to the limitations imposed by hardware. This is expected to evolve over time as the dynamic circuit backends also change. In its current form this is similar to Qiskit’s ASAP scheduler in which instructions start as early as possible. The primary differences are that: * **Resets and control-flow currently trigger the end of a “quantum block”. The period between the end** of the block and the next is *nondeterministic* ie., we do not know when the next block will begin (as we could be evaluating a classical function of nondeterministic length) and therefore the next block starts at a *relative* t=0. * During a measurement it is possible to apply gates in parallel on disjoint qubits. * Measurements and resets on disjoint qubits happen simultaneously and are part of the same block. Scheduler for dynamic circuit backends. **Parameters** * **durations** (`InstructionDurations`) – Durations of instructions to be used in scheduling. * **block\_ordering\_callable** (`Optional`\[`Callable`\[\[`DAGCircuit`], `Generator`\[`DAGOpNode`, `None`, `None`]]]) – A callable used to produce an ordering of the nodes to minimize the number of blocks needed. If not provided, `block_order_op_nodes()` will be used. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### \_\_call\_\_ Runs the pass on circuit. **Parameters** * **circuit** (*QuantumCircuit*) – The dag on which the pass is run. * **property\_set** (*PropertySet | dict | None*) – Input/output property set. An analysis pass might change the property set in-place. **Return type** QuantumCircuit **Returns** If on transformation pass, the resulting QuantumCircuit. If analysis pass, the input circuit. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** (`Any`) – Qiskit IR to optimize. * **state** (`PassManagerState`) – State associated with workflow execution by the pass manager itself. * **callback** (`Optional`\[`Callable`]) – A callback function which is caller per execution of optimization task. **Return type** `tuple`\[`Any`, `PassManagerState`] **Returns** Optimized Qiskit IR and state of the workflow. ### name Name of the pass. **Return type** `str` ### run Run the ALAPSchedule pass on dag. :type dag: `DAGCircuit` :param dag: DAG to schedule. :type dag: DAGCircuit **Raises** * **TranspilerError** – if the circuit is not mapped on physical qubits. * **TranspilerError** – if conditional bit is added to non-supported instruction. **Return type** `DAGCircuit` **Returns** The scheduled DAGCircuit. ### update\_status Update workflow status. **Parameters** * **state** (`PassManagerState`) – Pass manager state to update. * **run\_state** (`RunState`) – Completion status of current task. **Return type** `PassManagerState` **Returns** Updated pass manager state. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.transpiler.passes.scheduling.ASAPScheduleAnalysis.mdx "--- title: BlockBasePadder description: API reference for qiskit_ibm_runtime.transpiler.passes.scheduling.BlockBasePadder in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.transpiler.passes.scheduling.BlockBasePadder --- # BlockBasePadder The base class of padding pass. This pass requires one of scheduling passes to be executed before itself. Since there are multiple scheduling strategies, the selection of scheduling pass is left in the hands of the pass manager designer. Once a scheduling analysis pass is run, `node_start_time` is generated in the `property_set`. This information is represented by a python dictionary of the expected instruction execution times keyed on the node instances. The padding pass expects all `DAGOpNode` in the circuit to be scheduled. This base class doesn’t define any sequence to interleave, but it manages the location where the sequence is inserted, and provides a set of information necessary to construct the proper sequence. Thus, a subclass of this pass just needs to implement `_pad()` method, in which the subclass constructs a circuit block to insert. This mechanism removes lots of boilerplate logic to manage whole DAG circuits. Note that padding pass subclasses should define interleaving sequences satisfying: > * Interleaved sequence does not change start time of other nodes > * Interleaved sequence should have total duration of the provided `time_interval`. Any manipulation violating these constraints may prevent this base pass from correctly tracking the start time of each instruction, which may result in violation of hardware alignment constraints. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### \_\_call\_\_ Runs the pass on circuit. **Parameters** * **circuit** (*QuantumCircuit*) – The dag on which the pass is run. * **property\_set** (*PropertySet | dict | None*) – Input/output property set. An analysis pass might change the property set in-place. **Return type** QuantumCircuit **Returns** If on transformation pass, the resulting QuantumCircuit. If analysis pass, the input circuit. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** (`Any`) – Qiskit IR to optimize. * **state** (`PassManagerState`) – State associated with workflow execution by the pass manager itself. * **callback** (`Optional`\[`Callable`]) – A callback function which is caller per execution of optimization task. **Return type** `tuple`\[`Any`, `PassManagerState`] **Returns** Optimized Qiskit IR and state of the workflow. ### name Name of the pass. **Return type** `str` ### run Run the padding pass on `dag`. **Parameters** **dag** (`DAGCircuit`) – DAG to be checked. **Returns** DAG with idle time filled with instructions. **Return type** DAGCircuit **Raises** **TranspilerError** – When a particular node is not scheduled, likely some transform pass is inserted before this node is called. ### update\_status Update workflow status. **Parameters** * **state** (`PassManagerState`) – Pass manager state to update. * **run\_state** (`RunState`) – Completion status of current task. **Return type** `PassManagerState` **Returns** Updated pass manager state. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.transpiler.passes.scheduling.BlockBasePadder.mdx "--- title: DynamicCircuitInstructionDurations description: API reference for qiskit_ibm_runtime.transpiler.passes.scheduling.DynamicCircuitInstructionDurations in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.transpiler.passes.scheduling.DynamicCircuitInstructionDurations --- # DynamicCircuitInstructionDurations For dynamic circuits the IBM Qiskit backend currently reports instruction durations that differ compared with those required for the legacy Qobj-based path. For now we use this class to report updated InstructionDurations. TODO: This would be mitigated by a specialized Backend/Target for dynamic circuit backends. Dynamic circuit instruction durations. ## Attributes ### MEASURE\_PATCH\_CYCLES ### MEASURE\_PATCH\_ODD\_OFFSET ## Methods ### from\_backend Construct a `DynamicInstructionDurations` object from the backend. :type backend: `Backend` :param backend: backend from which durations (gate lengths) and dt are extracted. **Returns** The InstructionDurations constructed from backend. **Return type** DynamicInstructionDurations ### from\_target Construct a `DynamicInstructionDurations` object from the target. :type target: `Target` :param target: target from which durations (gate lengths) and dt are extracted. **Returns** The InstructionDurations constructed from backend. **Return type** DynamicInstructionDurations ### get Get the duration of the instruction with the name, qubits, and parameters. Some instructions may have a parameter dependent duration. **Parameters** * **inst** (*str | qiskit.circuit.Instruction*) – An instruction or its name to be queried. * **qubits** (*int | list\[int]*) – Qubit indices that the instruction acts on. * **unit** (*str*) – The unit of duration to be returned. It must be ‘s’ or ‘dt’. * **parameters** (*list\[float] | None*) – The value of the parameters of the desired instruction. **Returns** The duration of the instruction on the qubits. **Return type** float|int **Raises** **TranspilerError** – No duration is defined for the instruction. ### units\_used Get the set of all units used in this instruction durations. **Return type** `set`\[`str`] **Returns** Set of units used in this instruction durations. ### update Update self with inst\_durations (inst\_durations overwrite self). Overrides the default durations for certain hardcoded instructions. **Parameters** * **inst\_durations** (`Union`\[`List`\[`Tuple`\[`str`, `Optional`\[`Iterable`\[`int`]], `float`, `Optional`\[`Iterable`\[`float`]], `str`]], `List`\[`Tuple`\[`str`, `Optional`\[`Iterable`\[`int`]], `float`, `Optional`\[`Iterable`\[`float`]]]], `List`\[`Tuple`\[`str`, `Optional`\[`Iterable`\[`int`]], `float`, `str`]], `List`\[`Tuple`\[`str`, `Optional`\[`Iterable`\[`int`]], `float`]], `InstructionDurations`, `None`]) – Instruction durations to be merged into self (overwriting self). * **dt** (`Optional`\[`float`]) – Sampling duration in seconds of the target backend. **Returns** The updated InstructionDurations. **Return type** InstructionDurations **Raises** **TranspilerError** – If the format of instruction\_durations is invalid. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.transpiler.passes.scheduling.DynamicCircuitInstructionDurations.mdx "--- title: scheduling description: API reference for qiskit_ibm_runtime.transpiler.passes.scheduling in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_runtime.transpiler.passes.scheduling --- # Transpiler scheduling passes `qiskit_ibm_runtime.transpiler.passes.scheduling` A collection of scheduling passes for working with IBM Quantum’s next-generation backends that support advanced “dynamic circuit” capabilities. Ie., circuits with support for classical control-flow/feedback based off of measurement results. You should not mix these scheduling passes with Qiskit’s builtin scheduling passes as they will negatively interact with the scheduling routines for dynamic circuits. This includes setting `scheduling_method` in `transpile()` or `generate_preset_pass_manager()`. ## Classes | | | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [`BlockBasePadder`](qiskit_ibm_runtime.transpiler.passes.scheduling.BlockBasePadder ""qiskit_ibm_runtime.transpiler.passes.scheduling.BlockBasePadder"")(\[schedule\_idle\_qubits, ...]) | The base class of padding pass. | | [`ALAPScheduleAnalysis`](qiskit_ibm_runtime.transpiler.passes.scheduling.ALAPScheduleAnalysis ""qiskit_ibm_runtime.transpiler.passes.scheduling.ALAPScheduleAnalysis"")(durations\[, ...]) | Dynamic circuits as-late-as-possible (ALAP) scheduling analysis pass. | | [`ASAPScheduleAnalysis`](qiskit_ibm_runtime.transpiler.passes.scheduling.ASAPScheduleAnalysis ""qiskit_ibm_runtime.transpiler.passes.scheduling.ASAPScheduleAnalysis"")(durations\[, ...]) | Dynamic circuits as-soon-as-possible (ASAP) scheduling analysis pass. | | [`DynamicCircuitInstructionDurations`](qiskit_ibm_runtime.transpiler.passes.scheduling.DynamicCircuitInstructionDurations ""qiskit_ibm_runtime.transpiler.passes.scheduling.DynamicCircuitInstructionDurations"")(\[...]) | For dynamic circuits the IBM Qiskit backend currently reports instruction durations that differ compared with those required for the legacy Qobj-based path. | | [`PadDelay`](qiskit_ibm_runtime.transpiler.passes.scheduling.PadDelay ""qiskit_ibm_runtime.transpiler.passes.scheduling.PadDelay"")(durations\[, fill\_very\_end, ...]) | Padding idle time with Delay instructions. | | [`PadDynamicalDecoupling`](qiskit_ibm_runtime.transpiler.passes.scheduling.PadDynamicalDecoupling ""qiskit_ibm_runtime.transpiler.passes.scheduling.PadDynamicalDecoupling"")(durations, dd\_sequences) | Dynamical decoupling insertion pass for IBM dynamic circuit backends. | ## Example usage Below we demonstrate how to schedule and pad a teleportation circuit with delays for a dynamic circuit backend’s execution model: ```python from qiskit.circuit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.transpiler.passmanager import PassManager from qiskit_ibm_runtime.transpiler.passes.scheduling import DynamicCircuitInstructionDurations from qiskit_ibm_runtime.transpiler.passes.scheduling import ALAPScheduleAnalysis from qiskit_ibm_runtime.transpiler.passes.scheduling import PadDelay from qiskit_ibm_runtime.fake_provider import FakeJakartaV2 backend = FakeJakartaV2() # Use this duration class to get appropriate durations for dynamic # circuit backend scheduling durations = DynamicCircuitInstructionDurations.from_backend(backend) # Generate the main Qiskit transpile passes. pm = generate_preset_pass_manager(optimization_level=1, backend=backend) # Configure the as-late-as-possible scheduling pass pm.scheduling = PassManager([ALAPScheduleAnalysis(durations), PadDelay(durations)]) qr = QuantumRegister(3) crz = ClassicalRegister(1, name=""crz"") crx = ClassicalRegister(1, name=""crx"") result = ClassicalRegister(1, name=""result"") teleport = QuantumCircuit(qr, crz, crx, result, name=""Teleport"") teleport.h(qr[1]) teleport.cx(qr[1], qr[2]) teleport.cx(qr[0], qr[1]) teleport.h(qr[0]) teleport.measure(qr[0], crz) teleport.measure(qr[1], crx) with teleport.if_test((crz, 1)): teleport.z(qr[2]) with teleport.if_test((crx, 1)): teleport.x(qr[2]) teleport.measure(qr[2], result) # Transpile. scheduled_teleport = pm.run(teleport) scheduled_teleport.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_0\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_0_0.png) Instead of padding with delays we may also insert a dynamical decoupling sequence using the [`PadDynamicalDecoupling`](qiskit_ibm_runtime.transpiler.passes.scheduling.PadDynamicalDecoupling ""qiskit_ibm_runtime.transpiler.passes.scheduling.PadDynamicalDecoupling"") pass as shown below: ```python from qiskit.circuit.library import XGate from qiskit_ibm_runtime.transpiler.passes.scheduling import PadDynamicalDecoupling dd_sequence = [XGate(), XGate()] pm = generate_preset_pass_manager(optimization_level=1, backend=backend) pm.scheduling = PassManager( [ ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence), ] ) dd_teleport = pm.run(teleport) dd_teleport.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_1\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_1_0.png) When compiling a circuit with Qiskit, it is more efficient and more robust to perform all the transformations in a single transpilation. This has been done above by extending Qiskit’s preset pass managers. For example, Qiskit’s `transpile()` function internally builds its pass set by using `generate_preset_pass_manager()`. This returns instances of `StagedPassManager`, which can be extended. ## Scheduling old format c\_if conditioned gates Scheduling with old format `c_if` conditioned gates is not supported. ```python qc_c_if = QuantumCircuit(1, 1) qc_c_if.x(0).c_if(0, 1) qc_c_if.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_2\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_2_0.png) The [`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.IBMBackend"") configures a translation plugin `IBMTranslationPlugin` to automatically apply transformations and optimizations for IBM hardware backends when invoking `transpile()`. This will automatically convert all old style `c_if` conditioned gates to new-style control-flow. We may then schedule the transpiled circuit without further modification. ```python # Temporary workaround for mock backends. For real backends this is not required. backend.get_translation_stage_plugin = lambda: ""ibm_dynamic_circuits"" pm = generate_preset_pass_manager(optimization_level=1, backend=backend) pm.scheduling = PassManager( [ ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence), ] ) qc_if_dd = pm.run(qc_c_if, backend) qc_if_dd.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_3\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_3_0.png) If you are not using the transpiler plugin stages to work around this please manually run the pass `qiskit.transpiler.passes.ConvertConditionsToIfOps` prior to your scheduling pass. ```python from qiskit.transpiler.passes import ConvertConditionsToIfOps pm = generate_preset_pass_manager(optimization_level=1, backend=backend) pm.scheduling = PassManager( [ ConvertConditionsToIfOps(), ALAPScheduleAnalysis(durations), PadDelay(durations), ] ) qc_if_dd = pm.run(qc_c_if) qc_if_dd.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_4\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_4_0.png) ## Exploiting IBM backend’s local parallel “fast-path” IBM quantum hardware supports a localized “fast-path” which enables a block of gates applied to a *single qubit* that are conditional on an immediately predecessor measurement *of the same qubit* to be completed with lower latency. The hardware is also able to do this in *parallel* on disjoint qubits that satisfy this condition. For example, the conditional gates below are performed in parallel with lower latency as the measurements flow directly into the conditional blocks which in turn only apply gates to the same measurement qubit. ```python qc = QuantumCircuit(2, 2) qc.measure(0, 0) qc.measure(1, 1) # Conditional blocks will be performed in parallel in the hardware with qc.if_test((0, 1)): qc.x(0) with qc.if_test((1, 1)): qc.x(1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_5\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_5_0.png) The circuit below will not use the fast-path as the conditional gate is on a different qubit than the measurement qubit. ```python qc = QuantumCircuit(2, 2) qc.measure(0, 0) with qc.if_test((0, 1)): qc.x(1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_6\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_6_0.png) Similarly, the circuit below contains gates on multiple qubits and will not be performed using the fast-path. ```python qc = QuantumCircuit(2, 2) qc.measure(0, 0) with qc.if_test((0, 1)): qc.x(0) qc.x(1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_7\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_7_0.png) A fast-path block may contain multiple gates as long as they are on the fast-path qubit. If there are multiple fast-path blocks being performed in parallel each block will be padded out to the duration of the longest block. ```python qc = QuantumCircuit(2, 2) qc.measure(0, 0) qc.measure(1, 1) # Conditional blocks will be performed in parallel in the hardware with qc.if_test((0, 1)): qc.x(0) # Will be padded out to a duration of 1600 on the backend. with qc.if_test((1, 1)): qc.delay(1600, 1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_8\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_8_0.png) This behavior is also applied to the else condition of a fast-path eligible branch. ```python qc = QuantumCircuit(1, 1) qc.measure(0, 0) # Conditional blocks will be performed in parallel in the hardware with qc.if_test((0, 1)) as else_: qc.x(0) # Will be padded out to a duration of 1600 on the backend. with else_: qc.delay(1600, 0) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_9\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_9_0.png) If a single measurement result is used with several conditional blocks, if there is a fast-path eligible block it will be applied followed by the non-fast-path blocks which will execute with the standard higher latency conditional branch. ```python qc = QuantumCircuit(2, 2) qc.measure(0, 0) # Conditional blocks will be performed in parallel in the hardware with qc.if_test((0, 1)): # Uses fast-path qc.x(0) with qc.if_test((0, 1)): # Does not use fast-path qc.x(1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_10\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_10_0.png) If you wish to prevent the usage of the fast-path you may insert a barrier between the measurement and the conditional branch. ```python qc = QuantumCircuit(1, 2) qc.measure(0, 0) # Barrier prevents the fast-path. qc.barrier() with qc.if_test((0, 1)): qc.x(0) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_11\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_11_0.png) Conditional measurements are not eligible for the fast-path. ```python qc = QuantumCircuit(1, 2) qc.measure(0, 0) with qc.if_test((0, 1)): # Does not use the fast-path qc.measure(0, 1) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_12\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_12_0.png) Similarly nested control-flow is not eligible. ```python qc = QuantumCircuit(1, 1) qc.measure(0, 0) with qc.if_test((0, 1)): # Does not use the fast-path qc.x(0) with qc.if_test((0, 1)): qc.x(0) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_13\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_13_0.png) The scheduler is aware of the fast-path behavior and will not insert delays on idle qubits in blocks that satisfy the fast-path conditions so as to avoid preventing the backend compiler from performing the necessary optimizations to utilize the fast-path. If there are fast-path blocks that will be performed in parallel they currently *will not* be padded out by the scheduler to ensure they are of the same duration in Qiskit ```python dd_sequence = [XGate(), XGate()] pm = PassManager( [ ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence), ] ) qc = QuantumCircuit(2, 2) qc.measure(0, 0) qc.measure(1, 1) with qc.if_test((0, 1)): qc.x(0) # Is currently not padded to ensure # a duration of 1000. If you desire # this you would need to manually add # qc.delay(840, 0) with qc.if_test((1, 1)): qc.delay(1000, 0) qc.draw(output=""mpl"", style=""iqp"") qc_dd = pm.run(qc) qc_dd.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_14\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_14_0.png) If there are qubits that are *not* involved in a fast-path decision it is not currently possible to use them in a fast-path branch in parallel with the fast-path qubits resulting from a measurement. This will be revised in the future as we further improve these capabilities. For example: ```python qc = QuantumCircuit(3, 2) qc.x(1) qc.measure(0, 0) with qc.if_test((0, 1)): qc.x(0) # Qubit 1 sits idle throughout the fast-path decision with qc.if_test((1, 0)): # Qubit 2 is idle but there is no measurement # to make it fast-path eligible. This will # however avoid a communication event in the hardware # since the condition is compile time evaluated. qc.x(2) qc.draw(output=""mpl"", style=""iqp"") ``` ![../\_images/qiskit\_ibm\_runtime.transpiler.passes.scheduling\_15\_0.png](/images/api/qiskit-ibm-runtime/0.25/qiskit_ibm_runtime.transpiler.passes.scheduling_15_0.png) ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.transpiler.passes.scheduling.mdx "--- title: PadDelay description: API reference for qiskit_ibm_runtime.transpiler.passes.scheduling.PadDelay in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.transpiler.passes.scheduling.PadDelay --- # PadDelay Padding idle time with Delay instructions. Consecutive delays will be merged in the output of this pass. The ASAP-scheduled circuit output may become ```python ┌────────────────┐ q_0: ┤ Delay(160[dt]) ├──■── └─────┬───┬──────┘┌─┴─┐ q_1: ──────┤ X ├───────┤ X ├ └───┘ └───┘ ``` Note that the additional idle time of 60dt on the `q_0` wire coming from the duration difference between `Delay` of 100dt (`q_0`) and `XGate` of 160 dt (`q_1`) is absorbed in the delay instruction on the `q_0` wire, i.e. in total 160 dt. See [`BlockBasePadder`](qiskit_ibm_runtime.transpiler.passes.scheduling.BlockBasePadder ""qiskit_ibm_runtime.transpiler.passes.scheduling.BlockBasePadder"") pass for details. Create new padding delay pass. **Parameters** * **durations** (`InstructionDurations`) – Durations of instructions to be used in scheduling. * **fill\_very\_end** (`bool`) – Set `True` to fill the end of circuit with delay. * **schedule\_idle\_qubits** (`bool`) – Set to true if you’d like a delay inserted on idle qubits. This is useful for timeline visualizations, but may cause issues for execution on large backends. * **block\_ordering\_callable** (`Optional`\[`Callable`\[\[`DAGCircuit`], `Generator`\[`DAGOpNode`, `None`, `None`]]]) – A callable used to produce an ordering of the nodes to minimize the number of blocks needed. If not provided, `block_order_op_nodes()` will be used. ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### \_\_call\_\_ Runs the pass on circuit. **Parameters** * **circuit** (*QuantumCircuit*) – The dag on which the pass is run. * **property\_set** (*PropertySet | dict | None*) – Input/output property set. An analysis pass might change the property set in-place. **Return type** QuantumCircuit **Returns** If on transformation pass, the resulting QuantumCircuit. If analysis pass, the input circuit. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** (`Any`) – Qiskit IR to optimize. * **state** (`PassManagerState`) – State associated with workflow execution by the pass manager itself. * **callback** (`Optional`\[`Callable`]) – A callback function which is caller per execution of optimization task. **Return type** `tuple`\[`Any`, `PassManagerState`] **Returns** Optimized Qiskit IR and state of the workflow. ### name Name of the pass. **Return type** `str` ### run Run the padding pass on `dag`. **Parameters** **dag** (`DAGCircuit`) – DAG to be checked. **Returns** DAG with idle time filled with instructions. **Return type** DAGCircuit **Raises** **TranspilerError** – When a particular node is not scheduled, likely some transform pass is inserted before this node is called. ### update\_status Update workflow status. **Parameters** * **state** (`PassManagerState`) – Pass manager state to update. * **run\_state** (`RunState`) – Completion status of current task. **Return type** `PassManagerState` **Returns** Updated pass manager state. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.transpiler.passes.scheduling.PadDelay.mdx "--- title: PadDynamicalDecoupling description: API reference for qiskit_ibm_runtime.transpiler.passes.scheduling.PadDynamicalDecoupling in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_ibm_runtime.transpiler.passes.scheduling.PadDynamicalDecoupling --- # PadDynamicalDecoupling Dynamical decoupling insertion pass for IBM dynamic circuit backends. This pass works on a scheduled, physical circuit. It scans the circuit for idle periods of time (i.e. those containing delay instructions) and inserts a DD sequence of gates in those spots. These gates amount to the identity, so do not alter the logical action of the circuit, but have the effect of mitigating decoherence in those idle periods. As a special case, the pass allows a length-1 sequence (e.g. \[XGate()]). In this case the DD insertion happens only when the gate inverse can be absorbed into a neighboring gate in the circuit (so we would still be replacing Delay with something that is equivalent to the identity). This can be used, for instance, as a Hahn echo. This pass ensures that the inserted sequence preserves the circuit exactly (including global phase). ```python import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import XGate from qiskit.transpiler import PassManager, InstructionDurations from qiskit.visualization import timeline_drawer from qiskit_ibm_runtime.transpiler.passes.scheduling import ALAPScheduleAnalysis from qiskit_ibm_runtime.transpiler.passes.scheduling import PadDynamicalDecoupling circ = QuantumCircuit(4) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.cx(2, 3) circ.measure_all() durations = InstructionDurations( [(""h"", 0, 50), (""cx"", [0, 1], 700), (""reset"", None, 10), (""cx"", [1, 2], 200), (""cx"", [2, 3], 300), (""x"", None, 50), (""measure"", None, 1000)] ) ``` ```python # balanced X-X sequence on all qubits dd_sequence = [XGate(), XGate()] pm = PassManager([ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence)]) circ_dd = pm.run(circ) circ_dd.draw() ``` ```python ┌───┐ ┌───────────────┐ ┌───┐ » q_0: ──────┤ H ├─────────■──┤ Delay(96[dt]) ├──────┤ X ├──────» ┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴─────┐» q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(48[dt]) ├» ├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘» q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■────────» ├────────────────┤ └───┘ ┌─┴─┐ » q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├──────» └────────────────┘ └───┘ » meas: 4/═════════════════════════════════════════════════════════» » « ┌────────────────┐ ┌───┐ ┌───────────────┐ » « q_0: ┤ Delay(208[dt]) ├──────┤ X ├──────┤ Delay(96[dt]) ├─────────────────» « └─────┬───┬──────┘┌─────┴───┴─────┐└─────┬───┬─────┘┌───────────────┐» « q_1: ──────┤ X ├───────┤ Delay(96[dt]) ├──────┤ X ├──────┤ Delay(56[dt]) ├» « └───┘ └───────────────┘ └───┘ └───────────────┘» « q_2: ─────────────────────────────────────────────────────────────────────» « » « q_3: ─────────────────────────────────────────────────────────────────────» « » «meas: 4/═════════════════════════════════════════════════════════════════════» « » « ░ ┌─┐ « q_0: ─░─┤M├───────── « ░ └╥┘┌─┐ « q_1: ─░──╫─┤M├────── « ░ ║ └╥┘┌─┐ « q_2: ─░──╫──╫─┤M├─── « ░ ║ ║ └╥┘┌─┐ « q_3: ─░──╫──╫──╫─┤M├ « ░ ║ ║ ║ └╥┘ «meas: 4/════╩══╩══╩══╩═ « 0 1 2 3 ``` ```python # Uhrig sequence on qubit 0 n = 8 dd_sequence = [XGate()] * n def uhrig_pulse_location(k): return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2 spacings = [] for k in range(n): spacings.append(uhrig_pulse_location(k) - sum(spacings)) spacings.append(1 - sum(spacings)) pm = PassManager( [ ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence, qubits=[0], spacings=spacings), ] ) circ_dd = pm.run(circ) circ_dd.draw() ``` ```python ┌───┐ ┌────────────────┐ ░ ┌─┐ » q_0: ──────┤ H ├─────────■──┤ Delay(500[dt]) ├───────────────────░─┤M├──────» ┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌────────────────┐ ░ └╥┘┌─┐ » q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(300[dt]) ├─░──╫─┤M├───» ├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘ ░ ║ └╥┘┌─┐» q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■──────────░──╫──╫─┤M├» ├────────────────┤ └───┘ ┌─┴─┐ ░ ║ ║ └╥┘» q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├────────░──╫──╫──╫─» └────────────────┘ └───┘ ░ ║ ║ ║ » meas: 4/═══════════════════════════════════════════════════════════════╩══╩══╩═» 0 1 2 » « « q_0: ─── « « q_1: ─── « « q_2: ─── « ┌─┐ « q_3: ┤M├ « └╥┘ «meas: 4/═╩═ « 3 ``` You need to call [`ALAPScheduleAnalysis`](qiskit_ibm_runtime.transpiler.passes.scheduling.ALAPScheduleAnalysis ""qiskit_ibm_runtime.transpiler.passes.scheduling.ALAPScheduleAnalysis"") before running dynamical decoupling to guarantee your circuit satisfies acquisition alignment constraints for dynamic circuit backends. Dynamical decoupling initializer. **Parameters** * **durations** (`InstructionDurations`) – Durations of instructions to be used in scheduling. * **dd\_sequences** (`Union`\[`List`\[`Gate`], `List`\[`List`\[`Gate`]]]) – Sequence of gates to apply in idle spots. Alternatively a list of gate sequences may be supplied that will preferentially be inserted if there is a delay of sufficient duration. This may be tuned by the optionally supplied `sequence_min_length_ratios`. * **qubits** (`Optional`\[`List`\[`int`]]) – Physical qubits on which to apply DD. If None, all qubits will undergo DD (when possible). * **spacings** (`Union`\[`List`\[`List`\[`float`]], `List`\[`float`], `None`]) – A list of lists of spacings between the DD gates. The available slack will be divided according to this. The list length must be one more than the length of dd\_sequence, and the elements must sum to 1. If None, a balanced spacing will be used \[d/2, d, d, …, d, d, d/2]. This spacing only applies to the first subcircuit, if a `coupling_map` is specified * **skip\_reset\_qubits** (`bool`) – If True, does not insert DD on idle periods that immediately follow initialized/reset qubits (as qubits in the ground state are less susceptible to decoherence). * **pulse\_alignment** (`int`) – The hardware constraints for gate timing allocation. This is usually provided from `backend.configuration().timing_constraints`. If provided, the delay length, i.e. `spacing`, is implicitly adjusted to satisfy this constraint. * **extra\_slack\_distribution** (`str`) – The option to control the behavior of DD sequence generation. The duration of the DD sequence should be identical to an idle time in the scheduled quantum circuit, however, the delay in between gates comprising the sequence should be integer number in units of dt, and it might be further truncated when `pulse_alignment` is specified. This sometimes results in the duration of the created sequence being shorter than the idle time that you want to fill with the sequence, i.e. extra slack. This option takes following values. > * ”middle”: Put the extra slack to the interval at the middle of the sequence. > * ”edges”: Divide the extra slack as evenly as possible into intervals at beginning and end of the sequence. * **sequence\_min\_length\_ratios** (`Union`\[`int`, `List`\[`int`], `None`]) – List of minimum delay length to DD sequence ratio to satisfy in order to insert the DD sequence. For example if the X-X dynamical decoupling sequence is 320dt samples long and the available delay is 384dt it has a ratio of 384dt/320dt=1.2. From the perspective of dynamical decoupling this is likely to add more control noise than decoupling error rate reductions. The defaults value is 2.0. * **insert\_multiple\_cycles** (`bool`) – If the available duration exceeds 2\*sequence\_min\_length\_ratio\*duration(dd\_sequence) enable the insertion of multiple rounds of the dynamical decoupling sequence in that delay. * **coupling\_map** (`Optional`\[`CouplingMap`]) – directed graph representing the coupling map for the device. Specifying a coupling map partitions the device into subcircuits, in order to apply DD sequences with different pulse spacings within each. Currently support 2 subcircuits. * **alt\_spacings** (`Union`\[`List`\[`List`\[`float`]], `List`\[`float`], `None`]) – A list of lists of spacings between the DD gates, for the second subcircuit, as determined by the coupling map. If None, a balanced spacing that is staggered with respect to the first subcircuit will be used \[d, d, d, …, d, d, 0]. * **schedule\_idle\_qubits** (`bool`) – Set to true if you’d like a delay inserted on idle qubits. This is useful for timeline visualizations, but may cause issues for execution on large backends. * **dd\_barrier** (`Optional`\[`str`]) – only apply DD to delays terminating with a barrier whose label contains the specified string * **block\_ordering\_callable** (`Optional`\[`Callable`\[\[`DAGCircuit`], `Generator`\[`DAGOpNode`, `None`, `None`]]]) – A callable used to produce an ordering of the nodes to minimize the number of blocks needed. If not provided, `block_order_op_nodes()` will be used. **Raises** * **TranspilerError** – When invalid DD sequence is specified. * **TranspilerError** – When pulse gate with the duration which is non-multiple of the alignment constraint value is found. * **TranspilerError** – When the coupling map is not supported (i.e., if degree > 3) ## Attributes ### is\_analysis\_pass Check if the pass is an analysis pass. If the pass is an AnalysisPass, that means that the pass can analyze the DAG and write the results of that analysis in the property set. Modifications on the DAG are not allowed by this kind of pass. ### is\_transformation\_pass Check if the pass is a transformation pass. If the pass is a TransformationPass, that means that the pass can manipulate the DAG, but cannot modify the property set (but it can be read). ## Methods ### \_\_call\_\_ Runs the pass on circuit. **Parameters** * **circuit** (*QuantumCircuit*) – The dag on which the pass is run. * **property\_set** (*PropertySet | dict | None*) – Input/output property set. An analysis pass might change the property set in-place. **Return type** QuantumCircuit **Returns** If on transformation pass, the resulting QuantumCircuit. If analysis pass, the input circuit. ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** (`Any`) – Qiskit IR to optimize. * **state** (`PassManagerState`) – State associated with workflow execution by the pass manager itself. * **callback** (`Optional`\[`Callable`]) – A callback function which is caller per execution of optimization task. **Return type** `tuple`\[`Any`, `PassManagerState`] **Returns** Optimized Qiskit IR and state of the workflow. ### name Name of the pass. **Return type** `str` ### run Run the padding pass on `dag`. **Parameters** **dag** (`DAGCircuit`) – DAG to be checked. **Returns** DAG with idle time filled with instructions. **Return type** DAGCircuit **Raises** **TranspilerError** – When a particular node is not scheduled, likely some transform pass is inserted before this node is called. ### update\_status Update workflow status. **Parameters** * **state** (`PassManagerState`) – Pass manager state to update. * **run\_state** (`RunState`) – Completion status of current task. **Return type** `PassManagerState` **Returns** Updated pass manager state. ",repo/docs/api/qiskit-ibm-runtime/0.25\qiskit_ibm_runtime.transpiler.passes.scheduling.PadDynamicalDecoupling.mdx "--- title: qiskit_ibm_runtime description: API reference for qiskit_ibm_runtime in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_runtime --- # Qiskit Runtime `qiskit_ibm_runtime` Modules related to Qiskit Runtime IBM Client. Qiskit Runtime is a new architecture that streamlines computations requiring many iterations. These experiments will execute significantly faster within its improved hybrid quantum/classical process. ## Primitives and sessions Qiskit Runtime has two predefined primitives: `Sampler` and `Estimator`. These primitives provide a simplified interface for performing foundational quantum computing tasks while also accounting for the latest developments in quantum hardware and software. Qiskit Runtime also has the concept of a session. Jobs submitted within a session are prioritized by the scheduler. A session allows you to make iterative calls to the quantum computer more efficiently. Below is an example of using primitives within a session: ```python from qiskit_ibm_runtime import QiskitRuntimeService, Session from qiskit_ibm_runtime import SamplerV2 as Sampler from qiskit_ibm_runtime import EstimatorV2 as Estimator from qiskit.circuit.library import RealAmplitudes from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.quantum_info import SparsePauliOp from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager # Initialize account. service = QiskitRuntimeService() # Prepare inputs. psi = RealAmplitudes(num_qubits=2, reps=2) H1 = SparsePauliOp.from_list([(""II"", 1), (""IZ"", 2), (""XI"", 3)]) theta = [0, 1, 1, 2, 3, 5] # Bell Circuit qr = QuantumRegister(2, name=""qr"") cr = ClassicalRegister(2, name=""cr"") qc = QuantumCircuit(qr, cr, name=""bell"") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr, cr) backend = service.least_busy(operational=True, simulator=False) pm = generate_preset_pass_manager(target=backend.target, optimization_level=1) bell_isa_circuit = pm.run(qc) psi_isa_circuit = pm.run(psi) isa_observables = H1.apply_layout(psi_isa_circuit.layout) with Session(service=service, backend=backend) as session: # Submit a request to the Sampler primitive within the session. sampler = Sampler(session=session) job = sampler.run([bell_isa_circuit]) pub_result = job.result()[0] print(f""Counts: {pub_result.data.cr.get_counts()}"") # Submit a request to the Estimator primitive within the session. estimator = Estimator(session=session) estimator.options.resilience_level = 1 # Set options. job = estimator.run( [(psi_isa_circuit, isa_observables, theta)] ) pub_result = job.result()[0] print(f""Expectation values: {pub_result.data.evs}"") ``` ## Local testing mode You can validate your quantum programs before sending them to a physical system using the local testing mode. The local testing mode is activated if one of the fake backends in `qiskit_ibm_runtime.fake_provider` or a Qiskit Aer backend instance is used when instantiating a primitive or a session. For example: ```python from qiskit_aer import AerSimulator from qiskit.circuit.library import RealAmplitudes from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.quantum_info import SparsePauliOp from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import Session from qiskit_ibm_runtime import SamplerV2 as Sampler from qiskit_ibm_runtime.fake_provider import FakeManilaV2 # Bell Circuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() # Run the sampler job locally using FakeManilaV2 fake_manila = FakeManilaV2() pm = generate_preset_pass_manager(backend=fake_manila, optimization_level=1) isa_qc = pm.run(qc) sampler = Sampler(backend=fake_manila) result = sampler.run([isa_qc]).result() # Run the sampler job locally using AerSimulator. # Session syntax is supported but ignored. aer_sim = AerSimulator() pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=1) isa_qc = pm.run(qc) with Session(backend=aer_sim) as session: sampler = Sampler(session=session) result = sampler.run([isa_qc]).result() ``` ## Backend data [`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.QiskitRuntimeService"") also has methods, such as `backend()`, `backends()`, and `least_busy()`, that allow you to query for a target backend to use. These methods return one or more [`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.IBMBackend"") instances that contains methods and attributes describing the backend. ## Supplementary Information ### Account initialization You need to initialize your account before you can start using the Qiskit Runtime service. This is done by initializing a [`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.QiskitRuntimeService"") instance with your account credentials. If you don’t want to pass in the credentials each time, you can use the [`QiskitRuntimeService.save_account()`](qiskit_ibm_runtime.QiskitRuntimeService#save_account ""qiskit_ibm_runtime.QiskitRuntimeService.save_account"") method to save the credentials on disk. Qiskit Runtime is available on both IBM Cloud and IBM Quantum, and you can specify `channel=""ibm_cloud""` for IBM Cloud and `channel=""ibm_quantum""` for IBM Quantum. The default is IBM Cloud. ### Runtime Jobs When you use the `run()` method of the [`Sampler`](qiskit_ibm_runtime.Sampler ""qiskit_ibm_runtime.Sampler"") or [`Estimator`](qiskit_ibm_runtime.Estimator ""qiskit_ibm_runtime.Estimator"") to invoke the primitive, a [`RuntimeJob`](qiskit_ibm_runtime.RuntimeJob ""qiskit_ibm_runtime.RuntimeJob"") instance is returned. This class has all the basic job methods, such as [`RuntimeJob.status()`](qiskit_ibm_runtime.RuntimeJob#status ""qiskit_ibm_runtime.RuntimeJob.status""), [`RuntimeJob.result()`](qiskit_ibm_runtime.RuntimeJob#result ""qiskit_ibm_runtime.RuntimeJob.result""), and [`RuntimeJob.cancel()`](qiskit_ibm_runtime.RuntimeJob#cancel ""qiskit_ibm_runtime.RuntimeJob.cancel""). ### Logging `qiskit-ibm-runtime` uses the `qiskit_ibm_runtime` logger. Two environment variables can be used to control the logging: > * **`QISKIT_IBM_RUNTIME_LOG_LEVEL`: Specifies the log level to use.** > > If an invalid level is set, the log level defaults to `WARNING`. The valid log levels are `DEBUG`, `INFO`, `WARNING`, `ERROR`, and `CRITICAL` (case-insensitive). If the environment variable is not set, then the parent logger’s level is used, which also defaults to `WARNING`. > > * **`QISKIT_IBM_RUNTIME_LOG_FILE`: Specifies the name of the log file to use. If specified,** > > messages will be logged to the file only. Otherwise messages will be logged to the standard error (usually the screen). For more advanced use, you can modify the logger itself. For example, to manually set the level to `WARNING`: ```python import logging logging.getLogger('qiskit_ibm_runtime').setLevel(logging.WARNING) ``` ## Classes | | | | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | [`QiskitRuntimeService`](qiskit_ibm_runtime.QiskitRuntimeService ""qiskit_ibm_runtime.QiskitRuntimeService"")(\[channel, token, url, ...]) | Class for interacting with the Qiskit Runtime service. | | [`Estimator`](qiskit_ibm_runtime.Estimator ""qiskit_ibm_runtime.Estimator"") | alias of [`EstimatorV1`](qiskit_ibm_runtime.EstimatorV1 ""qiskit_ibm_runtime.estimator.EstimatorV1"") | | [`EstimatorV1`](qiskit_ibm_runtime.EstimatorV1 ""qiskit_ibm_runtime.EstimatorV1"")(\[backend, session, options]) | Class for interacting with Qiskit Runtime Estimator primitive service. | | [`EstimatorV2`](qiskit_ibm_runtime.EstimatorV2 ""qiskit_ibm_runtime.EstimatorV2"")(\[mode, backend, session, options]) | Class for interacting with Qiskit Runtime Estimator primitive service. | | [`Sampler`](qiskit_ibm_runtime.Sampler ""qiskit_ibm_runtime.Sampler"") | alias of [`SamplerV1`](qiskit_ibm_runtime.SamplerV1 ""qiskit_ibm_runtime.sampler.SamplerV1"") | | [`SamplerV1`](qiskit_ibm_runtime.SamplerV1 ""qiskit_ibm_runtime.SamplerV1"")(\[backend, session, options]) | Class for interacting with Qiskit Runtime Sampler primitive service. | | [`SamplerV2`](qiskit_ibm_runtime.SamplerV2 ""qiskit_ibm_runtime.SamplerV2"")(\[mode, backend, session, options]) | Class for interacting with Qiskit Runtime Sampler primitive service. | | [`Session`](qiskit_ibm_runtime.Session ""qiskit_ibm_runtime.Session"")(\[service, backend, max\_time]) | Class for creating a Qiskit Runtime session. | | [`Batch`](qiskit_ibm_runtime.Batch ""qiskit_ibm_runtime.Batch"")(\[service, backend, max\_time]) | Class for running jobs in batch execution mode. | | [`IBMBackend`](qiskit_ibm_runtime.IBMBackend ""qiskit_ibm_runtime.IBMBackend"")(configuration, service, api\_client) | Backend class interfacing with an IBM Quantum backend. | | [`RuntimeJob`](qiskit_ibm_runtime.RuntimeJob ""qiskit_ibm_runtime.RuntimeJob"")(backend, api\_client, ...\[, ...]) | Representation of a runtime primitive execution. | | [`RuntimeJobV2`](qiskit_ibm_runtime.RuntimeJobV2 ""qiskit_ibm_runtime.RuntimeJobV2"")(backend, api\_client, ...\[, ...]) | Representation of a runtime V2 primitive exeuction. | | [`RuntimeOptions`](qiskit_ibm_runtime.RuntimeOptions ""qiskit_ibm_runtime.RuntimeOptions"")(\[backend, image, log\_level, ...]) | Class for representing generic runtime execution options. | | [`RuntimeEncoder`](qiskit_ibm_runtime.RuntimeEncoder ""qiskit_ibm_runtime.RuntimeEncoder"")(\*\[, skipkeys, ensure\_ascii, ...]) | JSON Encoder used by runtime service. | | [`RuntimeDecoder`](qiskit_ibm_runtime.RuntimeDecoder ""qiskit_ibm_runtime.RuntimeDecoder"")(\*args, \*\*kwargs) | JSON Decoder used by runtime service. | ",repo/docs/api/qiskit-ibm-runtime/0.25\runtime_service.mdx "--- title: passes description: API reference for qiskit_ibm_runtime.transpiler.passes in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_ibm_runtime.transpiler.passes --- # Transpiler passes `qiskit_ibm_runtime.transpiler.passes` A collection of transpiler passes for IBM backends. Refer to [transpile](/transpile) to learn more about transpilation and passes. | | | | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | [`ConvertIdToDelay`](qiskit_ibm_runtime.transpiler.passes.ConvertIdToDelay ""qiskit_ibm_runtime.transpiler.passes.ConvertIdToDelay"")(durations\[, gate]) | Convert `qiskit.circuit.library.standard_gates.IGate` to a delay of the corresponding length. | See [`qiskit_ibm_runtime.transpiler.passes.scheduling`](qiskit_ibm_runtime.transpiler.passes.scheduling#module-qiskit_ibm_runtime.transpiler.passes.scheduling ""qiskit_ibm_runtime.transpiler.passes.scheduling"") for a collection of scheduling passes. ",repo/docs/api/qiskit-ibm-runtime/0.25\transpiler.mdx "--- title: ai description: API reference for qiskit_transpiler_service.ai in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_transpiler_service.ai --- # AI `qiskit_transpiler_service.ai` ## Classes | | | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | [`AIRouting`](qiskit_transpiler_service.ai.AIRouting ""qiskit_transpiler_service.ai.AIRouting"")(\[backend\_name, coupling\_map, ...]) | The AIRouting pass acts both as a layout stage and a routing stage. | | [`AICliffordSynthesis`](qiskit_transpiler_service.ai.AICliffordSynthesis ""qiskit_transpiler_service.ai.AICliffordSynthesis"")(backend\_name\[, ...]) | Synthesis for Clifford circuits (blocks of H, S and CX gates). | | [`AILinearFunctionSynthesis`](qiskit_transpiler_service.ai.AILinearFunctionSynthesis ""qiskit_transpiler_service.ai.AILinearFunctionSynthesis"")(backend\_name\[, ...]) | Synthesis for Linear Function circuits (blocks of CX and SWAP gates). | | [`AIPermutationSynthesis`](qiskit_transpiler_service.ai.AIPermutationSynthesis ""qiskit_transpiler_service.ai.AIPermutationSynthesis"")(backend\_name\[, ...]) | Synthesis for Permutation circuits (blocks of SWAP gates). | | [`CollectCliffords`](qiskit_transpiler_service.ai.CollectCliffords ""qiskit_transpiler_service.ai.CollectCliffords"")(\[do\_commutative\_analysis, ...]) | Collects Clifford blocks as Instruction objects and stores the original sub-circuit to compare against it after synthesis. | | [`CollectLinearFunctions`](qiskit_transpiler_service.ai.CollectLinearFunctions ""qiskit_transpiler_service.ai.CollectLinearFunctions"")(\[...]) | Collects blocks of SWAP and CX as LinearFunction objects and stores the original sub-circuit to compare against it after synthesis. | | [`CollectPermutations`](qiskit_transpiler_service.ai.CollectPermutations ""qiskit_transpiler_service.ai.CollectPermutations"")(\[...]) | Collects blocks of SWAP circuits as Permutations. | ",repo/docs/api/qiskit-transpiler-service\ai.mdx "--- title: Qiskit Transpiler Service Client Docs description: API documentation for the qiskit-transpiler-service client --- # qiskit-transpiler-service API reference * [AI (`qiskit_transpiler_service.ai`)](ai) * [Qiskit Transpiler Service (`qiskit_transpiler_service.transpiler_service`)](transpiler_service) * [Utilities (`qiskit_transpiler_service.utils`)](utils) ",repo/docs/api/qiskit-transpiler-service\index.mdx "--- title: AICliffordSynthesis description: API reference for qiskit_transpiler_service.ai.AICliffordSynthesis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_transpiler_service.ai.AICliffordSynthesis --- # AICliffordSynthesis Bases: `AISynthesis` Synthesis for Clifford circuits (blocks of H, S and CX gates). Currently up to 9 qubit blocks. **Parameters** * **backend\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of the backend used for doing the AI Clifford synthesis. * **replace\_only\_if\_better** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*, optional*) – Determine if replace the original circuit with the synthesized one if it’s better, defaults to True. * **max\_threads** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Set the number of requests to send in parallel. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run a pass on the DAGCircuit. This is implemented by the pass developer. **Parameters** **dag** ([*DAGCircuit*](/api/qiskit/qiskit.dagcircuit.DAGCircuit ""(in Qiskit v1.1)"")) – the dag on which the pass is run. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – when this is left unimplemented for a pass. ### synth\_node ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"") ",repo/docs/api/qiskit-transpiler-service\qiskit_transpiler_service.ai.AICliffordSynthesis.mdx "--- title: AILinearFunctionSynthesis description: API reference for qiskit_transpiler_service.ai.AILinearFunctionSynthesis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_transpiler_service.ai.AILinearFunctionSynthesis --- # AILinearFunctionSynthesis Bases: `AISynthesis` Synthesis for Linear Function circuits (blocks of CX and SWAP gates). Currently up to 9 qubit blocks. **Parameters** * **backend\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of the backend used for doing the AI Linear Function synthesis. * **replace\_only\_if\_better** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*, optional*) – Determine if replace the original circuit with the synthesized one if it’s better, defaults to True. * **max\_threads** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Set the number of requests to send in parallel. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run a pass on the DAGCircuit. This is implemented by the pass developer. **Parameters** **dag** ([*DAGCircuit*](/api/qiskit/qiskit.dagcircuit.DAGCircuit ""(in Qiskit v1.1)"")) – the dag on which the pass is run. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – when this is left unimplemented for a pass. ### synth\_node ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"") ",repo/docs/api/qiskit-transpiler-service\qiskit_transpiler_service.ai.AILinearFunctionSynthesis.mdx "--- title: AIPermutationSynthesis description: API reference for qiskit_transpiler_service.ai.AIPermutationSynthesis in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_transpiler_service.ai.AIPermutationSynthesis --- # AIPermutationSynthesis Bases: `AISynthesis` Synthesis for Permutation circuits (blocks of SWAP gates). Currently available for 65, 33, and 27 qubit blocks. **Parameters** * **backend\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Name of the backend used for doing the AI Linear Function synthesis. * **replace\_only\_if\_better** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*, optional*) – Determine if replace the original circuit with the synthesized one if it’s better, defaults to True. * **max\_threads** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Set the number of requests to send in parallel. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run a pass on the DAGCircuit. This is implemented by the pass developer. **Parameters** **dag** ([*DAGCircuit*](/api/qiskit/qiskit.dagcircuit.DAGCircuit ""(in Qiskit v1.1)"")) – the dag on which the pass is run. **Raises** [**NotImplementedError**](https://docs.python.org/3/library/exceptions.html#NotImplementedError ""(in Python v3.12)"") – when this is left unimplemented for a pass. ### synth\_node ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"") ",repo/docs/api/qiskit-transpiler-service\qiskit_transpiler_service.ai.AIPermutationSynthesis.mdx "--- title: AIRouting description: API reference for qiskit_transpiler_service.ai.AIRouting in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_transpiler_service.ai.AIRouting --- # AIRouting Bases: [`TransformationPass`](/api/qiskit/qiskit.transpiler.TransformationPass ""(in Qiskit v1.1)"") The AIRouting pass acts both as a layout stage and a routing stage. **Parameters** * **backend\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, optional*) – Name of the backend used for doing the transpilation. * **coupling\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]], optional*) – A list of pairs that represents physical links between qubits. * **optimization\_level** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – With a range from 1 to 3, determines the computational effort to spend in the process (higher usually gives better results but takes longer), defaults to 2. * **layout\_mode** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")) – Specifies how to handle the layout selection. There are 3 layout modes: keep (respects the layout set by the previous transpiler passes), improve (uses the layout set by the previous transpiler passes as a starting point) and optimize (ignores previous layout selections), defaults to OPTIMIZE. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the AIRouting pass on dag. **Parameters** **dag** (*DAGCircuit*) – the directed acyclic graph to be mapped. **Returns** A dag mapped to be compatible with the coupling\_map. **Return type** DAGCircuit **Raises** * **TranspilerError** – if the coupling map or the layout are not * **compatible with the DAG**\*\*, or \*\***if the coupling\_map=None** – ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"") ",repo/docs/api/qiskit-transpiler-service\qiskit_transpiler_service.ai.AIRouting.mdx "--- title: CollectCliffords description: API reference for qiskit_transpiler_service.ai.CollectCliffords in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_transpiler_service.ai.CollectCliffords --- # CollectCliffords Bases: `RepeatedCollectAndCollapse` Collects Clifford blocks as Instruction objects and stores the original sub-circuit to compare against it after synthesis. **Parameters** * **do\_commutative\_analysis** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*, optional*) – Enable or disable commutative analysis, defaults to True * **min\_block\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Set the minimum size for blocks generated during the collect Cliffords pass, defaults to 2. * **max\_block\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Set the maximum size for blocks generated during the collect Cliffords pass, defaults to 9. * **collect\_from\_back** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*, optional*) – Specify if collect blocks in reverse order or not, defaults to False. * **num\_reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Specify how many times to repeat the optimization process, defaults to 10. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CollectLinearFunctions pass on dag. :param dag: the DAG to be optimized. :type dag: DAGCircuit **Returns** the optimized DAG. **Return type** DAGCircuit ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"") ",repo/docs/api/qiskit-transpiler-service\qiskit_transpiler_service.ai.CollectCliffords.mdx "--- title: CollectLinearFunctions description: API reference for qiskit_transpiler_service.ai.CollectLinearFunctions in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_transpiler_service.ai.CollectLinearFunctions --- # CollectLinearFunctions Bases: `RepeatedCollectAndCollapse` Collects blocks of SWAP and CX as LinearFunction objects and stores the original sub-circuit to compare against it after synthesis. **Parameters** * **do\_commutative\_analysis** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*, optional*) – Enable or disable commutative analysis, defaults to True * **min\_block\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Set the minimum size for blocks generated during the collect linear functions pass, defaults to 4. * **max\_block\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Set the maximum size for blocks generated during the collect linear functions pass, defaults to 9. * **collect\_from\_back** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*, optional*) – Specify if collect blocks in reverse order or not, defaults to False. * **num\_reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Specify how many times to repeat the optimization process, defaults to 10. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CollectLinearFunctions pass on dag. :param dag: the DAG to be optimized. :type dag: DAGCircuit **Returns** the optimized DAG. **Return type** DAGCircuit ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"") ",repo/docs/api/qiskit-transpiler-service\qiskit_transpiler_service.ai.CollectLinearFunctions.mdx "--- title: CollectPermutations description: API reference for qiskit_transpiler_service.ai.CollectPermutations in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_transpiler_service.ai.CollectPermutations --- # CollectPermutations Bases: `RepeatedCollectAndCollapse` Collects blocks of SWAP circuits as Permutations. **Parameters** * **do\_commutative\_analysis** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*, optional*) – Enable or disable commutative analysis, defaults to True * **min\_block\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Set the minimum size for blocks generated during the collect permutations pass, defaults to 4. * **max\_block\_size** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Set the maximum size for blocks generated during the collect permutations pass, defaults to 12. * **collect\_from\_back** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*, optional*) – Specify if collect blocks in reverse order or not, defaults to False. * **num\_reps** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*, optional*) – Specify how many times to repeat the optimization process, defaults to 10. ## Methods ### execute Execute optimization task for input Qiskit IR. **Parameters** * **passmanager\_ir** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)"")) – Qiskit IR to optimize. * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – State associated with workflow execution by the pass manager itself. * **callback** ([*Callable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable ""(in Python v3.12)"") *| None*) – A callback function which is caller per execution of optimization task. **Returns** Optimized Qiskit IR and state of the workflow. **Return type** [tuple](https://docs.python.org/3/library/stdtypes.html#tuple ""(in Python v3.12)"")\[[*Any*](https://docs.python.org/3/library/typing.html#typing.Any ""(in Python v3.12)""), [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")] ### name Name of the pass. **Return type** [str](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") ### run Run the CollectLinearFunctions pass on dag. :param dag: the DAG to be optimized. :type dag: DAGCircuit **Returns** the optimized DAG. **Return type** DAGCircuit ### update\_status Update workflow status. **Parameters** * **state** ([*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"")) – Pass manager state to update. * **run\_state** (*RunState*) – Completion status of current task. **Returns** Updated pass manager state. **Return type** [*PassManagerState*](/api/qiskit/qiskit.passmanager.PassManagerState ""(in Qiskit v1.1)"") ",repo/docs/api/qiskit-transpiler-service\qiskit_transpiler_service.ai.CollectPermutations.mdx "--- title: TranspilerService description: API reference for qiskit_transpiler_service.transpiler_service.TranspilerService in_page_toc_min_heading_level: 1 python_api_type: class python_api_name: qiskit_transpiler_service.transpiler_service.TranspilerService --- # TranspilerService Bases: [`object`](https://docs.python.org/3/library/functions.html#object ""(in Python v3.12)"") Class for using the transpiler service. **Parameters** * **optimization\_level** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – The optimization level to use during the transpilation. There are 4 optimization levels ranging from 0 to 3, where 0 is intended for not performing any optimizations and 3 spends the most effort to optimize the circuit. * **ai** ([*bool*](https://docs.python.org/3/library/functions.html#bool ""(in Python v3.12)"")*, optional*) – Specifyies if the transpilation should use AI or not, defaults to True. * **coupling\_map** ([*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*list*](https://docs.python.org/3/library/stdtypes.html#list ""(in Python v3.12)"")*\[*[*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")*]], optional*) – A list of pairs that represents physical links between qubits. * **backend\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, optional*) – Name of the backend used for doing the transpilation. * **qiskit\_transpile\_options** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict ""(in Python v3.12)"")*, optional*) – Other options to transpile with qiskit. * **ai\_layout\_mode** ([*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"")*, optional*) – Specifies how to handle the layout selection. There are 3 layout modes: keep (respects the layout set by the previous transpiler passes), improve (uses the layout set by the previous transpiler passes as a starting point) and optimize (ignores previous layout selections). ## Methods ### run Transpile the circuit(s) by calling the service /transpile endpoint. **Parameters** **circuits** ([*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)"") *|*[*QuantumCircuit*](/api/qiskit/qiskit.circuit.QuantumCircuit ""(in Qiskit v1.1)"")*] |* [*str*](https://docs.python.org/3/library/stdtypes.html#str ""(in Python v3.12)"") *|*[*QuantumCircuit*](/api/qiskit/qiskit.circuit.QuantumCircuit ""(in Qiskit v1.1)"")) – circuit(s) to transpile. **Returns** The transpiled circuit(s) ",repo/docs/api/qiskit-transpiler-service\qiskit_transpiler_service.transpiler_service.TranspilerService.mdx "--- title: transpiler_service description: API reference for qiskit_transpiler_service.transpiler_service in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_transpiler_service.transpiler_service --- # Qiskit Transpiler Service `qiskit_transpiler_service.transpiler_service` ## Classes | | | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | | [`TranspilerService`](qiskit_transpiler_service.transpiler_service.TranspilerService ""qiskit_transpiler_service.transpiler_service.TranspilerService"")(optimization\_level\[, ai, ...]) | Class for using the transpiler service. | ",repo/docs/api/qiskit-transpiler-service\transpiler_service.mdx "--- title: utils description: API reference for qiskit_transpiler_service.utils in_page_toc_min_heading_level: 2 python_api_type: module python_api_name: qiskit_transpiler_service.utils --- # Utilities `qiskit_transpiler_service.utils` ## Functions ### create\_random\_linear\_function **Parameters** * **n\_qubits** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int ""(in Python v3.12)"")) – **Return type** [*LinearFunction*](/api/qiskit/qiskit.circuit.library.LinearFunction ""(in Qiskit v1.1)"") ### get\_metrics Returns a dict with metrics from a QuantumCircuit **Parameters** **qc** ([*QuantumCircuit*](/api/qiskit/qiskit.circuit.QuantumCircuit ""(in Qiskit v1.1)"")) – **Return type** [dict](https://docs.python.org/3/library/stdtypes.html#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)"")] ",repo/docs/api/qiskit-transpiler-service\utils.mdx