Circuits¶
On this page you can find all the information needed to build a circuit using MIMIQ. Every useful function will be presented below, accompanied by an explanation of their purpose and examples of use.
What is a circuit and what are instructions¶
A quantum circuit, similar to a classical circuit, represents a sequence of quantum gates applied to qubits, which are the carriers of quantum information. Quantum circuits are essential for designing quantum algorithms. The complexity of a quantum circuit is typically measured by two key metrics: width and depth. Width refers to the number of qubits in the circuit, while depth indicates the maximum number of sequential gates applied to any single qubit.
Here is a representation of a simple GHZ circuit on 4 qubits:
from mimiqcircuits import *
>>> ghz = Circuit()
>>> ghz.push(GateH(), 0)
1-qubit circuit with 1 instructions:
└── H @ q[0]
>>> ghz.push(GateCX(), 0, range(1, 4))
4-qubit circuit with 4 instructions:
├── H @ q[0]
├── CX @ q[0], q[1]
├── CX @ q[0], q[2]
└── CX @ q[0], q[3]
>>>
>>> ghz.draw()
┌─┐
q[0]: ╶┤H├─●──●──●────────────────────────────────────────────────────────────╴
└─┘┌┴┐ │ │
q[1]: ╶───┤X├─┼──┼────────────────────────────────────────────────────────────╴
└─┘┌┴┐ │
q[2]: ╶──────┤X├─┼────────────────────────────────────────────────────────────╴
└─┘┌┴┐
q[3]: ╶─────────┤X├───────────────────────────────────────────────────────────╴
└─┘
In this representation, each qubit is depicted by a horizontal line labeled q[x], where x is the qubit’s index. The circuit is read from left to right, with each ‘block’ or symbol along a line representing an operation applied to that specific qubit.
Circuits & Instructions in MIMIQ¶
MIMIQ implements a circuit using the Circuit structure, in essence this structure is a wrapper for a vector of Instruction to be applied on the qubits in the order of the vector. Since it is a vector a circuit can be manipulated as such, for example you can use for loops to iterate over the different instructions of the circuit, do vector comprehension or access all common vector attributes such as the length.
An Instruction is composed of the quantum operation to be applied to the qubits, and the targets on which to apply it. There are many types of quantum operations, as discussed in the unitary gates, non-unitary operations and other pages of the manual. The targets can be qubits, as well as boolean or complex number vectors where classical information can be stored.
You will generally not need to interact with the Instruction class directly (for exceptions, see special operations), but it is useful to understand how MIMIQ works.
See the following sections to learn how to add operations to your circuit.
Registers: quantum/classical/Z-register¶
Before explaining how to build a circuit it is important to make a distinction between the different target registers your operations will be applied to.
The circuits in MIMIQ are composed of three registers that can be used by the instructions:
* The Quantum Register: Used to store the qubits state. Most of the operators in MIMIQ will interact with the quatum register. When printing or drawing a circuit (with the function draw() ) the quantum registers will be denoted as q[x] with x being the index of the qubit in the quantum register.
* The classical register: Used to store the bits state. Some gates will need to interact with classical bits (ex: Measure ) and the state of the classical bits is stored in the classical register, which is a vector of booleans. When printing or drawing a circuit the classical register will be denoted by the letter c.
* The Z-register: Used to store the result of some specific operations when the expected result is a complex number (ex: ExpectationValue ). The Z-register is basically a vector of complex numbers. When printing or drawing a circuit the Z-Register will be denoted by the letter z.
For the three registers operators can be applied on an arbitrary index starting from 0 (as does Python in general contrary to Julia). When possible you should always use the minimal index available as going for an arbitrary high index N will imply that N qubits will be simulated and might result in a loss of performance and will also make the circuit drawing more complex to understand.
Here is a circuit interacting with all registers:
from mimiqcircuits import *
>>> # create empty circuit
>>> circuit = Circuit()
>>> # add X to the first qubit of the Quantum register
>>> circuit.push(GateX(), 0)
1-qubit circuit with 1 instructions:
└── X @ q[0]
>>> # compute Expectation value of qubit 1 and store complex number on the first Z-Register
>>> ev = ExpectationValue(GateZ())
>>> circuit.push(ev, 0, 0)
1-qubit, 1-zvar circuit with 2 instructions:
├── X @ q[0]
└── ⟨Z⟩ @ q[0], z[0]
>>> # Measure the qubit state and store bit into the first classical register
>>> circuit.push(Measure(), 0, 0)
1-qubit, 1-bit, 1-zvar circuit with 3 instructions:
├── X @ q[0]
├── ⟨Z⟩ @ q[0], z[0]
└── M @ q[0], c[0]
>>> # draw the circuit
>>> circuit.draw()
┌─┐┌─────────┐┌──────┐
q[0]: ╶┤X├┤ ⟨Z⟩ ├┤ M ├─────────────────────────────────────────────────╴
└─┘└────╥────┘└───╥──┘
║ ║
║ ║
c: ═════════╬═════════╩═════════════════════════════════════════════════════
║ 0
z: ═════════╩═══════════════════════════════════════════════════════════════
0
As you can see in the code above the indexing of the different registers always starts by the quantum register. If your operator interacts with the three registers the index will have to be provided in the following order: #. Index of the qantum register. #. Index of the classical register. #. Index of the z-register.
Be careful when writing information to the z-register or to the classical register as the information can be easily overwritten if the same index is used multiple times. For example if you measure two different qubits and store both in the same classical bit the results of the sampling will only report the last measurement.
To retrieve information on the number of element of each register you can use the num_qubits() , num_bits() and numz_vars() .
>>> circuit.num_qubits(), circuit.num_bits(), circuit.num_zvars()
(1, 1, 1)
In the following sections you will learn in details how to build a circuit in MIMIQ.
Creating a circuit¶
The first step in executing quantum algorithm on MIMIQ always consists in implementing the corresonding quantum circuit, a sequence of quantum operations (quantum gates, measurements, resets, etc…) that acts on a set of qubits. In MIMIQ we always start by defining an empty circuit
>>> circuit = Circuit()
There is no need to give any arguments. Not even the number of qubits, classical or Z-registers is necessary as it will be directly inferred from the operations added to the circuit.
Adding Gates¶
Once a circuit is instantiated operations can be added to it.
To see the list of gates available head to OPERATIONS , GATES , NOISECHANNELS and GENERALIZED or enter the following command in your Python session:
help(Gates)
To know more about the types of operations you can use in a circuit head to the unitary gates, non-unitary operations, noise, symbolic operations and special operations pages.
push¶
To add gates to circuits in Python we will mainly be using the push() method. The arguments needed by push() can vary, but in general it expects the following:
#. The circuit to add the operation to.
#. The operator to be added.
#. As many targets as needed by the operator (qubits/bits/zvars).
For instance you can add the gate X by simply running the following command:
>>> circuit.push(GateX(), 0)
1-qubit circuit with 1 instructions:
└── X @ q[0]
The text representation `H @ q[0]` informs us that there is an instruction which applies the Hadamard gate to the qubit of index 1.
Some gates require multiple target qubits such as the CX gate. Here is how to add such a gate to the circuit:
>>> circuit = Circuit()
>>> circuit.push(GateCX(), 0, 1)
2-qubit circuit with 1 instructions:
└── CX @ q[0], q[1]
This will add the gate GateCX using the qubit number 1 as the control qubit and number 2 as the target qubit in the circuit.
push specifics¶
push() is very versatile, it can be used to add multiple operators to multiple targets at once using iterators.
To add one type of gate to multiple qubits use:
>>> circuit = Circuit()
>>> circuit.push(GateX(), range(0, 11))
11-qubit circuit with 11 instructions:
├── X @ q[0]
├── X @ q[1]
├── X @ q[2]
├── X @ q[3]
├── X @ q[4]
├── X @ q[5]
├── X @ q[6]
├── X @ q[7]
├── X @ q[8]
├── X @ q[9]
└── X @ q[10]
This will add one X gate on each qubit from number 1 to 10.
This also works on 2-qubit gates:
>>> circuit = Circuit()
>>> circuit.push(GateID(), 0) # For documentation purpose, ignore this line
1-qubit circuit with 1 instructions:
└── ID @ q[0]
>>> # Adds 3 CX gates using respectively 1, 2 & 3 as the control qubits and 4 as the target qubit for all
>>> circuit.push(GateCX(), range(0, 3), 3)
4-qubit circuit with 4 instructions:
├── ID @ q[0]
├── CX @ q[0], q[3]
├── CX @ q[1], q[3]
└── CX @ q[2], q[3]
>>> # Adds 3 CX gates using respectively 2, 3 & 4 qubits as the target and 1 as the control qubit for all
>>> circuit.push(GateCX(), 0, range(1, 4))
4-qubit circuit with 7 instructions:
├── ID @ q[0]
├── CX @ q[0], q[3]
├── CX @ q[1], q[3]
├── CX @ q[2], q[3]
├── CX @ q[0], q[1]
├── CX @ q[0], q[2]
└── CX @ q[0], q[3]
>>> # adds 3 CX gates using respectively the couples (1, 4), (2, 5), (3, 6) as the control and target qubits
>>> circuit.push(GateCX(), range(0, 3), range(3, 6))
6-qubit circuit with 10 instructions:
├── ID @ q[0]
├── CX @ q[0], q[3]
├── CX @ q[1], q[3]
├── CX @ q[2], q[3]
├── CX @ q[0], q[1]
├── CX @ q[0], q[2]
├── CX @ q[0], q[3]
├── CX @ q[0], q[3]
├── CX @ q[1], q[4]
└── CX @ q[2], q[5]
>>> circuit.draw()
┌──┐
q[0]: ╶┤ID├─●────────●──●──●──●───────────────────────────────────────────────╴
└──┘ │ ┌┴┐ │ │ │
q[1]: ╶─────┼──●────┤X├─┼──┼──┼──●────────────────────────────────────────────╴
│ │ └─┘┌┴┐ │ │ │
q[2]: ╶─────┼──┼──●────┤X├─┼──┼──┼──●─────────────────────────────────────────╴
┌┴┐┌┴┐┌┴┐ └─┘┌┴┐┌┴┐ │ │
q[3]: ╶────┤X├┤X├┤X├──────┤X├┤X├─┼──┼─────────────────────────────────────────╴
└─┘└─┘└─┘ └─┘└─┘┌┴┐ │
q[4]: ╶─────────────────────────┤X├─┼─────────────────────────────────────────╴
└─┘┌┴┐
q[5]: ╶────────────────────────────┤X├────────────────────────────────────────╴
└─┘
Be careful when using vectors for both control and target, if one of the two vectors in longer than the other only the N first element of the vector will be accounted for with N = min(length.(vector1, vector2)).
See the output of the code below to see the implication in practice:
>>> circuit = Circuit()
>>> circuit.push(GateID(), 0) # For documentation purpose, ignore this line
1-qubit circuit with 1 instructions:
└── ID @ q[0]
>>> # Adds only 3 CX gates
>>> circuit.push(GateCX(), range(0, 3), range(3, 18))
6-qubit circuit with 4 instructions:
├── ID @ q[0]
├── CX @ q[0], q[3]
├── CX @ q[1], q[4]
└── CX @ q[2], q[5]
>>> circuit.draw()
┌──┐
q[0]: ╶┤ID├─●─────────────────────────────────────────────────────────────────╴
└──┘ │
q[1]: ╶─────┼──●──────────────────────────────────────────────────────────────╴
│ │
q[2]: ╶─────┼──┼──●───────────────────────────────────────────────────────────╴
┌┴┐ │ │
q[3]: ╶────┤X├─┼──┼───────────────────────────────────────────────────────────╴
└─┘┌┴┐ │
q[4]: ╶───────┤X├─┼───────────────────────────────────────────────────────────╴
└─┘┌┴┐
q[5]: ╶──────────┤X├──────────────────────────────────────────────────────────╴
└─┘
You can also use tuples or vectors in the exact same fashion:
>>> circuit = Circuit()
>>> circuit.push(GateID(), 0) # For documentation purpose, ignore this line
1-qubit circuit with 1 instructions:
└── ID @ q[0]
>>> circuit.push(GateCX(), (0, 1), (2, 3))
4-qubit circuit with 3 instructions:
├── ID @ q[0]
├── CX @ q[0], q[2]
└── CX @ q[1], q[3]
>>> circuit.push(GateCX(), [0, 2], [1, 3])
4-qubit circuit with 5 instructions:
├── ID @ q[0]
├── CX @ q[0], q[2]
├── CX @ q[1], q[3]
├── CX @ q[0], q[1]
└── CX @ q[2], q[3]
>>> circuit.draw()
┌──┐
q[0]: ╶┤ID├─●─────●───────────────────────────────────────────────────────────╴
└──┘ │ ┌┴┐
q[1]: ╶─────┼──●─┤X├──────────────────────────────────────────────────────────╴
┌┴┐ │ └─┘
q[2]: ╶────┤X├─┼─────●────────────────────────────────────────────────────────╴
└─┘┌┴┐ ┌┴┐
q[3]: ╶───────┤X├───┤X├───────────────────────────────────────────────────────╴
└─┘ └─┘
Insert¶
You can also insert an operation at a given index in the circuit using the insert() function:
>>> circuit = Circuit()
>>> circuit.push(GateX(), 1)
2-qubit circuit with 1 instructions:
└── X @ q[1]
>>> circuit.push(GateZ(), 1)
2-qubit circuit with 2 instructions:
├── X @ q[1]
└── Z @ q[1]
>>> # Insert the gate at a specific index
>>> circuit.insert(2, GateY(), 1)
2-qubit circuit with 3 instructions:
├── X @ q[1]
├── Z @ q[1]
└── Y @ q[1]
>>> circuit
2-qubit circuit with 3 instructions:
├── X @ q[1]
├── Z @ q[1]
└── Y @ q[1]
This will insert GateY applied on qubit `1` at the second position in the circuit.
Append¶
To append one circuit to another you can use the append() function:
>>> # Build a first circuit
>>> circuit1 = Circuit()
>>> circuit1.push(GateX(), range(1, 4))
4-qubit circuit with 3 instructions:
├── X @ q[1]
├── X @ q[2]
└── X @ q[3]
>>> # Build a second circuit
>>> circuit2 = Circuit()
>>> circuit2.push(GateY(), range(1, 4))
4-qubit circuit with 3 instructions:
├── Y @ q[1]
├── Y @ q[2]
└── Y @ q[3]
>>> # Append the second circuit to the first one
>>> circuit1.append(circuit2)
>>> circuit1
4-qubit circuit with 6 instructions:
├── X @ q[1]
├── X @ q[2]
├── X @ q[3]
├── Y @ q[1]
├── Y @ q[2]
└── Y @ q[3]
This will modify circuit1 by appending all the operations from circuit2.
This function is particularly useful for building circuits by combining smaller circuit blocks.
Visualizing circuits¶
To visualize a circuit use the draw() method.
ere is a representation of a sim
.. doctest:: python
>>> circuit = Circuit()
>>> circuit.push(GateX(), range(0, 5))
5-qubit circuit with 5 instructions:
├── X @ q[0]
├── X @ q[1]
├── X @ q[2]
├── X @ q[3]
└── X @ q[4]
>>> circuit.draw()
┌─┐
q[0]: ╶┤X├────────────────────────────────────────────────────────────────────╴
└─┘┌─┐
q[1]: ╶───┤X├─────────────────────────────────────────────────────────────────╴
└─┘┌─┐
q[2]: ╶──────┤X├──────────────────────────────────────────────────────────────╴
└─┘┌─┐
q[3]: ╶─────────┤X├───────────────────────────────────────────────────────────╴
└─┘┌─┐
q[4]: ╶────────────┤X├────────────────────────────────────────────────────────╴
└─┘
Information such as the depth() and the width (num_qubits() ) can be extracted from the circuit:
>>> circuit.depth(), circuit.num_qubits()
(1, 5)
Decompose¶
Most gates can be decomposed into a combination of U and CX gates, the decompose() function extracts such decomposition from a given circuit:
>>> circuit = Circuit()
>>> circuit.push(GateX(), 0)
1-qubit circuit with 1 instructions:
└── X @ q[0]
>>> # decompose the circuit
>>> circuit.decompose()
1-qubit circuit with 1 instructions:
└── U(pi, 0, pi, 0.0) @ q[0]
decompose() also takes a target basis from
mimiqcircuits.decomposition. For example,
CliffordTBasis rewrites the circuit into
Clifford and T gates. Rotations by multiples of \(\pi/4\) are decomposed
exactly. Other rotations are approximated by
GridSynthRewrite, by default to an
operator-norm error of \(10^{-10}\) each, and the rotations argument
selects a different tolerance or rule:
>>> from mimiqcircuits.decomposition import CliffordTBasis, GridSynthRewrite
>>> circuit = Circuit()
>>> circuit.push(GateRZ(0.123), 0)
1-qubit circuit with 1 instruction:
└── RZ(0.123) @ q[0]
>>> # approximate the rotation to 1e-10 with Clifford+T gates
>>> fine = circuit.decompose(CliffordTBasis())
>>> # a looser tolerance gives a shorter circuit
>>> shorter = circuit.decompose(CliffordTBasis(rotations=GridSynthRewrite(epsilon=1e-4)))
>>> len(shorter) < len(fine)
True
Ancillas¶
By default a decomposition only uses the qubits of the operation it
decomposes. Some operations have much shorter decompositions when they may use
other qubits as well. The bases CanonicalBasis,
CliffordTBasis and QASMBasis
take three options for that, all off by default:
borrow=Truelets a decomposition borrow qubits of the circuit that the operation does not act on. A borrowed qubit can be in any state, even entangled, and the decomposition leaves it exactly as it found it.max_ancillas=klets it add up tokclean ancillas: new qubits, numbered after those of the circuit, that start in \(|0\rangle\) and are returned to \(|0\rangle\). An ancilla freed by one operation is reused by the next one.allow_measurement=True, together withmax_ancillas, lets it undo some steps by measuring an ancilla instead of with more gates. The circuit must have classical bits; the measurements write one extra bit after them.
Today these options apply to multi-controlled X gates, where the gain is largest. With four controls and Clifford+T as the target:
>>> c = Circuit()
>>> c.push(Control(4, GateX()), 0, 1, 2, 3, 4)
5-qubit circuit with 1 instruction:
└── C₄X @ q[0:3], q[4]
>>> c.push(GateH(), 5)
6-qubit circuit with 2 instructions:
├── C₄X @ q[0:3], q[4]
└── H @ q[5]
>>> def tcount(circuit):
... return sum(isinstance(i.operation, (GateT, GateTDG)) for i in circuit)
>>> # without help, the decomposition needs small rotations, approximated
>>> tcount(c.decompose(CliffordTBasis()))
1627
>>> # borrowing qubit 5 gives Toffolis, which are exact
>>> tcount(c.decompose(CliffordTBasis(borrow=True)))
70
>>> # two clean ancillas hold the AND of the first controls
>>> d = c.decompose(CliffordTBasis(max_ancillas=2))
>>> tcount(d)
23
>>> ancillas(d)
[6, 7]
The decomposition marks each clean ancilla with an
AncillaAlloc where it starts being used and an
AncillaFree where it is back in \(|0\rangle\).
These annotations do nothing when the circuit runs, but they tell later
passes, and ancillas(), which qubits are ancillas.
check_ancillas() checks that they are consistent.
With wrap=True, a gate that uses clean ancillas becomes a call to a
GateDecl with the ancillas as its last targets, and
num_ancillas says how many of them there are. The markers go around the
call:
>>> w = decompose(c, CanonicalBasis(max_ancillas=2), wrap=True)
>>> w
8-qubit circuit with 6 instructions:
├── AncillaAlloc @ q[6]
├── AncillaAlloc @ q[7]
├── mimiq_C4X() @ q[0:4,6:7]
├── AncillaFree @ q[6]
├── AncillaFree @ q[7]
└── mimiq_H() @ q[5]
>>> w[2].operation.num_ancillas
2
With measurements, each AND costs 4 T gates and is undone for free:
>>> c.push(Measure(), 4, 0)
6-qubit, 1-bit circuit with 3 instructions:
├── C₄X @ q[0:3], q[4]
├── H @ q[5]
└── M @ q[4], c[0]
>>> m = c.decompose(CliffordTBasis(max_ancillas=3, allow_measurement=True))
>>> tcount(m)
12
>>> m.num_bits()
2
A gate declaration cannot measure, so with wrap=True such a gate becomes a
call to a BlockDecl instead. Its bit is the extra one,
and identical gates share the declaration:
>>> decompose(c, CliffordTBasis(max_ancillas=3, allow_measurement=True), wrap=True)
9-qubit, 2-bit circuit with 9 instructions:
├── AncillaAlloc @ q[6]
├── AncillaAlloc @ q[7]
├── AncillaAlloc @ q[8]
├── mimiq_C4X @ q[0], q[1], q[2], q[3], q[4], q[6], q[7], q[8], c[1]
├── AncillaFree @ q[6]
├── AncillaFree @ q[7]
├── AncillaFree @ q[8]
├── H @ q[5]
└── M @ q[4], c[0]
Ancillas are meant for exporting circuits and counting resources. A simulator gains nothing from them: it applies a multi-controlled gate directly, and every extra qubit makes the simulation larger.
Dependency graph (DAG) view¶
A circuit is stored as an ordered list of instructions, but many of those
instructions are independent: they act on different qubits and could run in any
relative order. dag() exposes this structure as a
CircuitDAG, a dependency graph whose vertices are the
instruction positions 0 .. n-1 and whose edges u -> v mean instruction
v depends on u (they share a qubit, bit, or z-variable and u is the
most recent earlier instruction on that wire). This is useful for analysing or
reordering a circuit — for example to find which gates can be fused or run in
parallel.
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]
>>> c.push(GateCX(), 0, 1)
2-qubit circuit with 2 instructions:
├── H @ q[0]
└── CX @ q[0], q[1]
>>> c.push(Measure(), 0, 0)
2-qubit, 1-bit circuit with 3 instructions:
├── H @ q[0]
├── CX @ q[0], q[1]
└── M @ q[0], c[0]
>>> dag = c.dag()
>>> dag
CircuitDAG(vertices=3, edges=2)
>>> dag.edges()
[(0, 1), (1, 2)]
The graph can be sorted into a topological order, or you can iterate the
circuit’s instructions directly in dependency order with
traverse_by_bfs() (layer by layer) or
traverse_by_dfs():
>>> topological_sort_by_bfs(dag)
[0, 1, 2]
>>> [str(inst) for inst in traverse_by_bfs(c)]
['H @ q[0]', 'CX @ q[0], q[1]', 'M @ q[0], c[0]']
With the optional networkx dependency installed (pip install
mimiqcircuits[graph]), to_networkx() returns the same
graph as a networkx.DiGraph for drawing or further analysis.
Reference¶
- class Circuit(instructions=None)[source]
Bases:
objectAn ordered list of instructions acting on qubits, classical bits and z-variables.
Operations are added one at a time with
c.push(operation, targets...), which returns the circuit so calls can be chained. The number of qubits, bits and z-variables is not declared up front: it is one more than the largest index used on each register.- Parameters:
instructions (list of Instruction) – Instructions to start with. The list is used as the circuit’s storage, not copied. Defaults to an empty circuit.
- Raises:
TypeError – If
instructionsis not a list, or holds anything other thanInstructionobjects.
Examples
>>> from mimiqcircuits import * >>> from symengine import pi
Create a new circuit object
>>> c = Circuit()
Add a GateX (Pauli-X) gate on qubit 0
>>> c.push(GateX(), 0) 1-qubit circuit with 1 instruction: └── X @ q[0]
Add a Controlled-NOT (CX) gate with control qubit 0 and target qubit 1
>>> c.push(GateCX(), 0, 1) 2-qubit circuit with 2 instructions: ├── X @ q[0] └── CX @ q[0], q[1]
Add a Parametric GateRX gate with parameters pi/4
>>> c.push(GateRX(pi / 4),0) 2-qubit circuit with 3 instructions: ├── X @ q[0] ├── CX @ q[0], q[1] └── RX((1/4)*pi) @ q[0]
Add a Reset gate on qubit 0
>>> c.push(Reset(), 0) 2-qubit circuit with 4 instructions: ├── X @ q[0] ├── CX @ q[0], q[1] ├── RX((1/4)*pi) @ q[0] └── Reset @ q[0]
Add a Barrier gate on qubits 0 and 1
>>> c.push(Barrier(2), 0, 1) 2-qubit circuit with 5 instructions: ├── X @ q[0] ├── CX @ q[0], q[1] ├── RX((1/4)*pi) @ q[0] ├── Reset @ q[0] └── Barrier @ q[0:1]
Add a Measurement gate on qubit 0, storing the result in bit 0.
>>> c.push(Measure(), 0, 0) 2-qubit, 1-bit circuit with 6 instructions: ├── X @ q[0] ├── CX @ q[0], q[1] ├── RX((1/4)*pi) @ q[0] ├── Reset @ q[0] ├── Barrier @ q[0:1] └── M @ q[0], c[0]
Add a Control gate with GateX as the target gate. The first 3 qubits are the control qubits.
>>> c.push(Control(3, GateX()), 0, 1, 2, 3) 4-qubit, 1-bit circuit with 7 instructions: ├── X @ q[0] ├── CX @ q[0], q[1] ├── RX((1/4)*pi) @ q[0] ├── Reset @ q[0] ├── Barrier @ q[0:1] ├── M @ q[0], c[0] └── C₃X @ q[0:2], q[3]
Add a 3-qubit Parallel gate with GateX
>>> c.push(Parallel(3,GateX()),0, 1, 2) 4-qubit, 1-bit circuit with 8 instructions: ├── X @ q[0] ├── CX @ q[0], q[1] ├── RX((1/4)*pi) @ q[0] ├── Reset @ q[0] ├── Barrier @ q[0:1] ├── M @ q[0], c[0] ├── C₃X @ q[0:2], q[3] └── ⨷ ³ X @ q[0], q[1], q[2]
To add operations whose size depends on the targets, such as
QFT, give the targets as registers withemplace().Note
Commonly used operations include the single-qubit gates
GateX,GateY,GateZ,GateH,GateS,GateT,GateSX,GateID,GateU,GateP,GateRX,GateRYandGateRZ; the two-qubit gatesGateCX,GateCY,GateCZ,GateCH,GateSWAP,GateISWAP,GateCS,GateCSX,GateECR,GateDCX,GateCU,GateCP,GateCRX,GateCRY,GateCRZ,GateRXX,GateRYY,GateRZZ,GateXXplusYYandGateXXminusYY; custom gates (GateCustom); the wrappersControl,Parallel,PowerandInverse; the generalized gatesQFTandPhaseGradient;MeasureandReset; andBarrier.- property instructions
Read-only view of the circuit’s instructions.
The list is the circuit’s own storage, exposed for reading and iteration. Add or remove instructions through
push(),insert(),append(), orremove(): these keep the cached dependency graph and resource counts consistent, whereas mutating the returned list in place would silently bypass that bookkeeping.
- dag()[source]
Return the circuit’s dependency graph as a
CircuitDAG.The graph is built on first use and cached. Changing the circuit through
push(),insert(),append()orremove()drops the cache, so the next call rebuilds it.- Returns:
The graph whose vertex
iis instructioni.- Return type:
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> _ = c.push(GateH(), 0) >>> _ = c.push(GateCX(), 0, 1) >>> _ = c.push(GateX(), 1) >>> # each instruction depends on the previous one on a shared qubit >>> c.dag().edges() [(0, 1), (1, 2)]
- traverse_by_bfs()[source]
Iterate the instructions in breadth-first topological order.
See
mimiqcircuits.traverse_by_bfs().
- traverse_by_dfs()[source]
Iterate the instructions in depth-first topological order.
See
mimiqcircuits.traverse_by_dfs().
- to_networkx()[source]
Return the dependency graph as a
networkx.DiGraph.See
mimiqcircuits.to_networkx(). Requires the optionalnetworkxdependency (pip install mimiqcircuits[graph]).
- num_qubits()[source]
Return the number of qubits of the circuit.
This is one more than the largest qubit index used, so unused qubits below it are counted. An empty circuit has 0 qubits.
Examples
>>> from mimiqcircuits import * >>> Circuit().push(GateX(), 3).num_qubits() 4
- num_bits()[source]
Return the number of classical bits of the circuit.
This is one more than the largest bit index used, or 0 when no instruction targets a bit.
- getparams()[source]
Return the parameters of every instruction, in circuit order.
Numeric and symbolic parameters are both returned, one entry per parameter of each operation, so a value can appear more than once.
- Returns:
The parameters of all instructions, concatenated.
- Return type:
Examples
>>> import mimiqcircuits as mc >>> from symengine import symbols >>> theta = symbols("theta") >>> c = mc.Circuit().push(mc.GateRX(theta), 0).push(mc.GateP(0.5), 1) >>> c.getparams() [theta, 0.5]
- listvars()[source]
List the symbolic variables of all the instructions of the circuit.
Operations inside a
Blockor a wrapper such asControlare included. Variables already substituted byevaluate()are not listed.- Returns:
Each
symengine.Symbolonce, in no particular order. The list is empty when the circuit has no symbolic parameters.- Return type:
Examples
>>> from mimiqcircuits import * >>> from symengine import Symbol >>> theta, phi = Symbol("theta"), Symbol("phi") >>> c = Circuit() >>> c.push(GateRX(theta), 0) 1-qubit circuit with 1 instruction: └── RX(theta) @ q[0] >>> c.push(GateRZ(phi), 1) 2-qubit circuit with 2 instructions: ├── RX(theta) @ q[0] └── RZ(phi) @ q[1] >>> sorted(c.listvars(), key=str) [phi, theta] >>> c.evaluate({theta: 0.1}).listvars() [phi]
- num_zvars()[source]
Return the number of z-variables of the circuit.
This is one more than the largest z-variable index used, or 0 when no instruction targets a z-variable.
- empty()[source]
Return
Trueif the circuit has no instructions.
- push(operation, *args)[source]
Add an operation or an instruction at the end of the circuit.
The targets are given in order: first the qubits, then the classical bits, then the z-variables, as many of each as the operation acts on. A target can be an integer or an iterable of integers. When some targets are iterables, one instruction is added for each position, zipping the iterables together and repeating the integer targets; the shortest iterable sets the number of instructions.
- Parameters:
operation (Operation or Instruction) – The operation to add, or an already-built instruction (then no targets are allowed).
- Returns:
The circuit itself, so calls can be chained.
- Return type:
- Raises:
TypeError – If
operationis not anOperationor anInstruction, or a target is neither an integer nor an iterable.ValueError – If the number of targets does not match the operation, a target index is negative or repeated, or
operationis an operator that is not a gate (such as a projector), which can only be used inside other operations.
Examples
Targets can be integers or iterables of integers. An iterable adds one instruction per element.
>>> from mimiqcircuits import * >>> from symengine import pi >>> c = Circuit() >>> c.push(GateH(), 0) 1-qubit circuit with 1 instruction: └── H @ q[0] >>> c.push(GateT(), 0) 1-qubit circuit with 2 instructions: ├── H @ q[0] └── T @ q[0] >>> c.push(GateH(), [0,2]) # one H on each of qubits 0 and 2 3-qubit circuit with 4 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] └── H @ q[2] >>> c.push(GateS(), 0) 3-qubit circuit with 5 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] ├── H @ q[2] └── S @ q[0] >>> c.push(GateCX(), [2, 0], 1) # controls 2 and 0, target 1 each time 3-qubit circuit with 7 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] ├── H @ q[2] ├── S @ q[0] ├── CX @ q[2], q[1] └── CX @ q[0], q[1] >>> c.push(GateH(), 0) 3-qubit circuit with 8 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] ├── H @ q[2] ├── S @ q[0] ├── CX @ q[2], q[1] ├── CX @ q[0], q[1] └── H @ q[0] >>> c.push(Barrier(3), *range(3)) # same as c.push(Barrier(3), 0, 1, 2) 3-qubit circuit with 9 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] ├── H @ q[2] ├── S @ q[0] ├── CX @ q[2], q[1] ├── CX @ q[0], q[1] ├── H @ q[0] └── Barrier @ q[0:2] >>> c.push(Measure(), range(3), range(3)) # measure qubit i into bit i 3-qubit, 3-bit circuit with 12 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] ├── H @ q[2] ├── S @ q[0] ├── CX @ q[2], q[1] ├── CX @ q[0], q[1] ├── H @ q[0] ├── Barrier @ q[0:2] ├── M @ q[0], c[0] ├── M @ q[1], c[1] └── M @ q[2], c[2]
- emplace(op, *regs)[source]
Add an operation at the end of the circuit, with targets given by register.
Each register is a list of indices. An operation has one register for each group of qubits, bits or z-variables it acts on (for example a
Controlhas one register for the controls and one for the targets), given in the order quantum, classical, z-variable. The registers are joined and passed topush().Operations whose size is still open, such as
QFT()orcontrol(GateX()), take their size from the length of the registers. AParalleltakes one single-element register for each qubit.- Parameters:
- Returns:
The circuit itself, so calls can be chained.
- Return type:
- Raises:
ValueError – If the number of registers or the size of one does not match the operation, or
opis an operator that is not a gate.TypeError – If
opis not an operation or a lazy expression.
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> # a fixed-size gate takes one register per group of qubits >>> c.emplace(GateRX(0.2), [0]) 1-qubit circuit with 1 instruction: └── RX(0.2) @ q[0] >>> # QFT() has no size yet: the register of 3 qubits sets it >>> c.emplace(QFT(), range(3)) 3-qubit circuit with 2 instructions: ├── RX(0.2) @ q[0] └── QFT @ q[0:2] >>> # the number of controls comes from the first register >>> c.emplace(control(GateX()), [0, 1], [2]) 3-qubit circuit with 3 instructions: ├── RX(0.2) @ q[0] ├── QFT @ q[0:2] └── C₂X @ q[0:1], q[2]
- insert(index, operation, *args)[source]
Insert an operation, an instruction or a whole circuit at a position.
The new instruction is placed before the one currently at
index, as withlist.insert. Unlikepush(), targets must be plain integers, so exactly one instruction is inserted. Whenoperationis aCircuit, all its instructions are inserted in order and no targets are given.- Parameters:
index (int) – The position to insert at.
operation (Operation, Instruction or Circuit) – What to insert.
*args (int) – The target qubits, then bits, then z-variables of
operation. Not allowed for an instruction or a circuit.
- Returns:
The circuit itself, so calls can be chained.
- Return type:
- Raises:
TypeError – If
operationis not an operation, an instruction or a circuit, orindexis not an integer when inserting a circuit.ValueError – If the number of targets is wrong, a target is invalid, or
operationis an operator that is not a gate.
Examples
>>> from mimiqcircuits import * >>> c= Circuit() >>> c.push(GateX(), 0) 1-qubit circuit with 1 instruction: └── X @ q[0] >>> c.push(GateCX(),0,1) 2-qubit circuit with 2 instructions: ├── X @ q[0] └── CX @ q[0], q[1] >>> # put an H between the X and the CX >>> c.insert(1, GateH(), 0) 2-qubit circuit with 3 instructions: ├── X @ q[0] ├── H @ q[0] └── CX @ q[0], q[1] >>> # insert a whole circuit at the start >>> c.insert(0, Circuit().push(GateZ(), 1)) 2-qubit circuit with 4 instructions: ├── Z @ q[1] ├── X @ q[0] ├── H @ q[0] └── CX @ q[0], q[1]
- append(other)[source]
Add all the instructions of another circuit at the end of this one.
The instructions are added as they are, without copying or checking them. The circuit is changed in place and nothing is returned.
- Parameters:
other (Circuit or list of Instruction) – The instructions to add.
- Raises:
TypeError – If
otheris neither a circuit nor a list.
Examples
>>> from mimiqcircuits import * >>> c = Circuit().push(GateH(), 0) >>> c.append(Circuit().push(GateCX(), 0, 1)) >>> c 2-qubit circuit with 2 instructions: ├── H @ q[0] └── CX @ q[0], q[1]
- remove(index)[source]
Remove the instruction at
index.- Parameters:
index (int) – The position of the instruction to remove. Negative indices count from the end, as for a list.
- Returns:
The circuit itself, so calls can be chained.
- Return type:
- Raises:
IndexError – If
indexis out of range.
- inverse()[source]
Return a new circuit that undoes this one.
The instructions are reversed and each operation is replaced by its inverse. The circuit itself is not changed.
- Returns:
The inverse circuit.
- Return type:
- Raises:
TypeError – If an operation has no inverse, such as a measurement or a reset.
NotImplementedError – If an operation is a Kraus channel.
Examples
>>> from mimiqcircuits import * >>> c = Circuit().push(GateH(), 0).push(GateS(), 0) >>> c.inverse() 1-qubit circuit with 2 instructions: ├── S† @ q[0] └── H @ q[0]
- decompose(basis=None)[source]
Decompose all operations in the circuit to a target basis.
Operations are rewritten recursively until every one is terminal in the basis. The circuit itself is not changed.
- Parameters:
basis – The target basis, a
DecompositionBasis, or aRewriteRuleto apply until it no longer matches. Defaults toCanonicalBasis(GateUandGateCX).- Returns:
A new circuit with every operation in the target basis.
- Return type:
Examples
Decompose to the canonical basis (the default):
>>> from mimiqcircuits import * >>> c = Circuit() >>> c.push(GateH(), 0) 1-qubit circuit with 1 instruction: └── H @ q[0] >>> c.push(GateCCX(), 0, 1, 2) 3-qubit circuit with 2 instructions: ├── H @ q[0] └── C₂X @ q[0:1], q[2] >>> decomposed = c.decompose() >>> # every gate is now a GateU or a GateCX >>> sorted({type(i.operation).__name__ for i in decomposed}) ['GateCX', 'GateU']
Decompose to Clifford+T:
>>> from mimiqcircuits import CliffordTBasis >>> decomposed = c.decompose(CliffordTBasis())
Use a specific rewrite rule:
>>> from mimiqcircuits import ZYZRewrite >>> decomposed = c.decompose(ZYZRewrite())
See also
mimiqcircuits.decompose(): Module-level decompose functionmimiqcircuits.CanonicalBasis: Default decomposition basismimiqcircuits.CliffordTBasis: Clifford+T decomposition
- decompose_step(rule=None)[source]
Apply a single decomposition step to all matching operations.
Unlike
decompose(), this method is non-recursive. Matching operations are rewritten once and the resulting instructions are kept as-is, even if they are still non-terminal in the canonical basis.- Parameters:
rule – The rewrite rule to apply. Defaults to
CanonicalRewrite.- Returns:
A new circuit with one decomposition step applied.
- Return type:
Examples
Apply the default canonical rewrite once:
>>> from mimiqcircuits import * >>> c = Circuit() >>> c.push(GateH(), 0) 1-qubit circuit with 1 instruction: └── H @ q[0] >>> c.decompose_step() 1-qubit circuit with 1 instruction: └── U((1/2)*pi, 0, pi, 0.0) @ q[0]
Apply a specific rewrite rule once:
>>> from symengine import pi >>> from mimiqcircuits import ZYZRewrite >>> c = Circuit().push(GateU(pi / 2, pi / 4, pi / 3), 0) >>> c.decompose_step(ZYZRewrite()) 1-qubit circuit with 3 instructions: ├── RZ((1/3)*pi) @ q[0] ├── RY((1/2)*pi) @ q[0] └── RZ((1/4)*pi) @ q[0]
See also
mimiqcircuits.decompose_step(): Module-level single-step decomposition functiondecompose(): Recursive decomposition to a target basis
- evaluate(d)[source]
Return a copy of the circuit with symbols replaced by values.
Each instruction is evaluated with
d. Symbols that are not indstay symbolic. The circuit itself is not modified.- Parameters:
d – Dictionary from symbols to values.
- Returns:
A new circuit with the substituted parameters.
- Return type:
Examples
>>> import mimiqcircuits as mc >>> from symengine import symbols >>> theta, phi = symbols("theta phi") >>> c = mc.Circuit().push(mc.GateRX(theta), 0).push(mc.GateRY(phi), 0) >>> c.evaluate({theta: 0.5}) 1-qubit circuit with 2 instructions: ├── RX(0.5) @ q[0] └── RY(phi) @ q[0]
- depth()[source]
Return the depth of the circuit.
The depth is the length of the longest chain of instructions that share a qubit, a classical bit or a z-variable. Barriers are not counted. A circuit without qubits has depth 0.
- Returns:
The depth.
- Return type:
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> _ = c.push(GateH(), [0, 1]) # one layer: H on both qubits >>> _ = c.push(GateCX(), 0, 1) # a second layer >>> _ = c.push(Measure(), 0, 0) # a third layer, on qubit 0 only >>> c.depth() 3
- copy()[source]
Return a shallow copy of the circuit.
The copy has its own list of instructions, so adding an instruction to one circuit does not change the other. The instructions themselves are shared. Use
deepcopy()to copy them too.- Returns:
The shallow copy.
- Return type:
- reorder_qubits(perm)[source]
Return a new circuit with every qubit index sent through
perm.An instruction acting on qubit
qacts on qubitperm[q]in the result. Operations that refer to qubits outside their targets are rewritten too: the bitstring of anAmplitude(also inside anIfStatement,RepeatorBlock) is reordered so it reads the same amplitude as before.Classical bits and z-variables are not renumbered, so the result produces the same classical and z-variable outcomes as the original.
- Parameters:
perm – A permutation of
range(self.num_qubits()), as a sequence whereperm[q]is the new index of qubitq.- Returns:
The relabeled circuit.
- Return type:
- Raises:
ValueError – If
permis not a permutation ofrange(self.num_qubits()).
Examples
>>> from mimiqcircuits import * >>> c = Circuit().push(GateH(), 0).push(GateCX(), 0, 1) >>> # swap the roles of qubits 0 and 1 >>> c.reorder_qubits([1, 0]) 2-qubit circuit with 2 instructions: ├── H @ q[1] └── CX @ q[1], q[0]
- deepcopy()[source]
Return a deep copy of the circuit.
The instructions and their operations are copied too, so the result shares nothing with the original.
- Returns:
The independent copy.
- Return type:
- get_on_qubits(target_qubits)[source]
Return the instructions that act on any of the given qubits.
- Parameters:
target_qubits (int or list of int) – The qubits to look for.
- Returns:
A new circuit with the matching instructions, in their original order and with their original targets.
- Return type:
Examples
>>> from mimiqcircuits import * >>> c = Circuit().push(GateH(), 0).push(GateX(), 2).push(GateCX(), 0, 1) >>> c.get_on_qubits(1) 2-qubit circuit with 1 instruction: └── CX @ q[0], q[1]
- saveproto(file)[source]
Save the circuit to a protobuf (binary) file.
Symbolic parameters are saved as expressions. Read the file back with
loadproto().- Parameters:
file – A file path or a binary file-like object to write to.
- Returns:
The number of bytes written.
- Return type:
Examples
>>> from mimiqcircuits import * >>> from symengine import * >>> import tempfile >>> x, y = symbols("x y") >>> c = Circuit() >>> c.push(GateH(), 0) 1-qubit circuit with 1 instruction: └── H @ q[0] >>> c.push(GateXXplusYY(x**2, y),0,1) 2-qubit circuit with 2 instructions: ├── H @ q[0] └── XXplusYY(x**2, y) @ q[0:1] >>> c.push(Measure(),0,0) 2-qubit, 1-bit circuit with 3 instructions: ├── H @ q[0] ├── XXplusYY(x**2, y) @ q[0:1] └── M @ q[0], c[0] >>> # a temporary file keeps the example self-contained; any path works >>> tmpfile = tempfile.NamedTemporaryFile(suffix=".pb", delete=True) >>> c.saveproto(tmpfile.name) 64 >>> Circuit.loadproto(tmpfile.name) 2-qubit, 1-bit circuit with 3 instructions: ├── H @ q[0] ├── XXplusYY(x**2, y) @ q[0:1] └── M @ q[0], c[0]
- static loadproto(file)[source]
Load a circuit from a protobuf (binary) file written by
saveproto().- Parameters:
file – A file path or a binary file-like object to read from.
- Returns:
The loaded circuit.
- Return type:
- Raises:
ValueError – If the file cannot be parsed.
See also
saveproto(), which has an example of saving and loading.
- draw(compact=True)[source]
Print an ASCII drawing of the circuit.
Each qubit gets a wire; the classical bits share one double wire, and so do the z-variables. When the drawing reaches the width of the canvas, the part drawn so far is printed, followed by
..., and drawing continues on a fresh canvas.- Parameters:
compact (bool) – If
True(the default), instructions on disjoint wires share a column, and consecutive instructions of the same operation on disjoint wires, such as those from one broadcastpush(), start in the same column. Instructions that touch the classical or z-variable register are always drawn one after the other. IfFalse, every instruction gets its own column, in circuit order.- Returns:
The drawing is printed, not returned.
- Return type:
None
- Raises:
ValueError – If a single instruction is wider than the canvas.
Examples
>>> from mimiqcircuits import * >>> c = Circuit().push(GateH(), 0).push(GateCX(), 0, 1) >>> c.draw()
- specify_operations()[source]
Print how many instructions the circuit has, grouped by their number of targets.
Instructions are grouped by how many qubits, bits and z-variables they act on, so an
Hand anXfall in the same group. Groups are listed in the order they first appear in the circuit.- Returns:
The summary is printed, not returned.
- Return type:
None
Examples
>>> from mimiqcircuits import * >>> c = Circuit()
Add a Pauli-X (GateX) gate on qubit 0
>>> c.push(GateX(), 0) 1-qubit circuit with 1 instruction: └── X @ q[0]
Add a Controlled-NOT (CX) gate with control qubit 0 and target qubit 1
>>> c.push(GateCX(), 0, 1) 2-qubit circuit with 2 instructions: ├── X @ q[0] └── CX @ q[0], q[1]
Add a Measurement operation on qubit 0, storing the result in bit 0
>>> c.push(Measure(), 0, 0) 2-qubit, 1-bit circuit with 3 instructions: ├── X @ q[0] ├── CX @ q[0], q[1] └── M @ q[0], c[0]
Add an ExpectationValue operation with GateX on qubit 1, storing the result in z-variable 2.
>>> c.push(ExpectationValue(GateX()), 1, 2) 2-qubit, 1-bit, 3-zvar circuit with 4 instructions: ├── X @ q[0] ├── CX @ q[0], q[1] ├── M @ q[0], c[0] └── ⟨X⟩ @ q[1], z[2]
Print a summary of the types and numbers of operations
>>> c.specify_operations() Total number of operations: 4 ├── 1 x 1_qubits ├── 1 x 2_qubits ├── 1 x 1_qubits & 1_bits └── 1 x 1_qubits & 1_zvars
- is_symbolic()[source]
Return
Trueif any operation of the circuit has a symbolic parameter.Operations nested inside wrappers such as
ControlorBlockare checked too. Useevaluate()to substitute values andlistvars()to see which symbols remain.- Returns:
Trueif at least one parameter is still symbolic.- Return type:
Examples
>>> from mimiqcircuits import * >>> from symengine import * >>> x, y = symbols("x y") >>> c = Circuit() >>> c.push(GateH(), 0) 1-qubit circuit with 1 instruction: └── H @ q[0] >>> c.is_symbolic() False >>> c.push(GateP(x), 0) 1-qubit circuit with 2 instructions: ├── H @ q[0] └── P(x) @ q[0] >>> c.is_symbolic() True >>> c = c.evaluate({x: 1, y: 2}) >>> c 1-qubit circuit with 2 instructions: ├── H @ q[0] └── P(1) @ q[0] >>> c.is_symbolic() False
- decorate_on_match_single(g, decoration, before=False)[source]
Return a copy of the circuit with
decorationadded next to eachg.Every instruction whose operation equals
ggetsdecorationright after it (or right before it), on the same qubits. The circuit itself is not changed; seeadd_noise()for the in-place version.- Parameters:
g (Operation) – The operation to match, compared with
==.decoration (krauschannel | Gate) – The gate or Kraus channel to insert. It must act on as many qubits as
g.before (bool) – If
True, insert the decoration before each match instead of after it.
- Returns:
A new, decorated circuit.
- Return type:
- Raises:
ValueError – If
decorationequalsg, or acts on a different number of qubits.
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> c.push(GateH(), 0) 1-qubit circuit with 1 instruction: └── H @ q[0] >>> c.decorate_on_match_single(GateH(), AmplitudeDamping(0.2)) 1-qubit circuit with 2 instructions: ├── H @ q[0] └── AmplitudeDamping(0.2) @ q[0] >>> # the original circuit is unchanged >>> c 1-qubit circuit with 1 instruction: └── H @ q[0]
- decorate_on_match_parallel(g, decoration, before=False)[source]
Add
decorationafter (or before) each block of parallelginstructions.A block is a run of consecutive instructions equal to
gthat act on disjoint qubits, such as the instructions from one broadcastpush(). The decorations for the whole block are inserted together, after the block or before it, each on the qubits of one matched instruction. The circuit is changed in place.- Parameters:
g (Operation) – The operation to match, compared with
==.decoration (krauschannel | Gate) – The gate or Kraus channel to insert. It must act on as many qubits as
g.before (bool) – If
True, insert the decorations before each block instead of after it.
- Returns:
The circuit itself, now decorated.
- Return type:
- Raises:
ValueError – If
decorationequalsg, or acts on a different number of qubits.
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> c.push(GateH(), range(3)) 3-qubit circuit with 3 instructions: ├── H @ q[0] ├── H @ q[1] └── H @ q[2] >>> c.decorate_on_match_parallel(GateH(), AmplitudeDamping(0.2)) 3-qubit circuit with 6 instructions: ├── H @ q[0] ├── H @ q[1] ├── H @ q[2] ├── AmplitudeDamping(0.2) @ q[0] ├── AmplitudeDamping(0.2) @ q[1] └── AmplitudeDamping(0.2) @ q[2]
- add_noise(g, kraus, before=False, parallel=False)[source]
Add the noise
krausnext to every instance ofg, in place.krausacts on the same qubits as each matched instruction, so it must act on as many qubits asg. By default it goes right after each match. Withparallel=True, runs of consecutive matches on disjoint qubits (as produced by one broadcastpush()) are kept together and their noise is added after the whole run, as indecorate_on_match_parallel().For rules that depend on more than the operation, or for many rules at once, use a
NoiseModel.- Parameters:
g (Operation | List[Operation]) – The operation to match. An operation instance matches instructions whose operation is equal to it; an operation class, such as
GateH, matches every instance of it.kraus (krauschannel | Gate | List[Gate] | List[krauschannel]) – The Kraus channel or gate to add.
before (bool | List[bool]) – If
True, add the noise before each match instead of after it. Mostly used withMeasure.parallel (bool | List[bool]) – If
True, add the noise after (or before) each run of parallel matches instead of after each match.
- Returns:
The circuit itself, with the noise added.
- Return type:
- Raises:
TypeError – If
krausis not a gate or a Kraus channel, orgis not an operation or an operation class.ValueError – If
krausacts on a different number of qubits than the matched instructions.
Examples
Adding noise after each gate:
>>> from mimiqcircuits import * >>> c = Circuit() >>> c.push(GateH(), [1,2,3]) 4-qubit circuit with 3 instructions: ├── H @ q[1] ├── H @ q[2] └── H @ q[3] >>> c.add_noise(GateH(), AmplitudeDamping(0.2)) 4-qubit circuit with 6 instructions: ├── H @ q[1] ├── AmplitudeDamping(0.2) @ q[1] ├── H @ q[2] ├── AmplitudeDamping(0.2) @ q[2] ├── H @ q[3] └── AmplitudeDamping(0.2) @ q[3]
Adding the noise after each run of parallel gates:
>>> c = Circuit() >>> c.push(GateH(), [1, 2, 3]) 4-qubit circuit with 3 instructions: ├── H @ q[1] ├── H @ q[2] └── H @ q[3] >>> c.add_noise(GateH(), AmplitudeDamping(0.2), parallel=True) 4-qubit circuit with 6 instructions: ├── H @ q[1] ├── H @ q[2] ├── H @ q[3] ├── AmplitudeDamping(0.2) @ q[1] ├── AmplitudeDamping(0.2) @ q[2] └── AmplitudeDamping(0.2) @ q[3]
Gates that share a qubit are not parallel, so each one is followed by its own noise:
>>> c = Circuit() >>> c.push(GateCZ(), 1, range(2,5)) 5-qubit circuit with 3 instructions: ├── CZ @ q[1], q[2] ├── CZ @ q[1], q[3] └── CZ @ q[1], q[4] >>> c.add_noise(GateCZ(), Depolarizing2(0.1), parallel=True) 5-qubit circuit with 6 instructions: ├── CZ @ q[1], q[2] ├── Depolarizing(0.1) @ q[1:2] ├── CZ @ q[1], q[3] ├── Depolarizing(0.1) @ q[1,3] ├── CZ @ q[1], q[4] └── Depolarizing(0.1) @ q[1,4]
Adding a bit-flip before each measurement, to model readout errors:
>>> c = Circuit() >>> c.push(Measure(), [1, 2, 3], [1, 2, 3]) 4-qubit, 4-bit circuit with 3 instructions: ├── M @ q[1], c[1] ├── M @ q[2], c[2] └── M @ q[3], c[3] >>> c.add_noise(Measure(), PauliX(0.1), before=True) 4-qubit, 4-bit circuit with 6 instructions: ├── PauliX(0.1) @ q[1] ├── M @ q[1], c[1] ├── PauliX(0.1) @ q[2] ├── M @ q[2], c[2] ├── PauliX(0.1) @ q[3] └── M @ q[3], c[3]
A unitary gate can be used as noise too, for example a small over-rotation:
>>> c = Circuit() >>> c.push(GateH(), [1, 2, 3]) 4-qubit circuit with 3 instructions: ├── H @ q[1] ├── H @ q[2] └── H @ q[3] >>> c.add_noise(GateH(), GateRX(0.01)) 4-qubit circuit with 6 instructions: ├── H @ q[1] ├── RX(0.01) @ q[1] ├── H @ q[2] ├── RX(0.01) @ q[2] ├── H @ q[3] └── RX(0.01) @ q[3]
- sample_mixedunitaries(rng=None, ids=False)[source]
Return a copy of the circuit with each mixed-unitary channel replaced by one sampled gate.
A mixed-unitary channel applies one of a fixed set of unitaries with fixed probabilities that do not depend on the state, so the choice can be made before running the circuit. Each such channel is replaced by the gate drawn with its probability. Other channels and operations are kept as they are. This is how noisy circuits are sampled when simulating with trajectories, and it can be used to draw noisy circuits without running them.
If the drawn branch is marked lossy (see the
lossyargument ofMixedUnitary), aLoss(1.0)is also added on each of its lossy qubits, to be resolved together with any other loss in the circuit.- Parameters:
rng (random.Random) – Random number generator with a
random()method. Defaults to a newrandom.Random().ids (bool) – If
True, a drawn identity gate is kept in the circuit. By default it is left out; most draws of a weak noise channel are the identity.
- Returns:
The sampled circuit. The circuit itself is not changed.
- Return type:
See also
krauschannel.ismixedunitary(),MixedUnitaryExamples
Gates and non-mixed-unitary Kraus channels remain unchanged:
>>> from mimiqcircuits import * >>> c = Circuit() >>> c.push(GateH(), [1, 2, 3]) 4-qubit circuit with 3 instructions: ├── H @ q[1] ├── H @ q[2] └── H @ q[3] >>> c.push(Depolarizing1(0.5), [1, 2, 3]) 4-qubit circuit with 6 instructions: ├── H @ q[1] ├── H @ q[2] ├── H @ q[3] ├── Depolarizing(0.5) @ q[1] ├── Depolarizing(0.5) @ q[2] └── Depolarizing(0.5) @ q[3] >>> c.push(AmplitudeDamping(0.5), [1, 2, 3]) 4-qubit circuit with 9 instructions: ├── H @ q[1] ├── H @ q[2] ├── H @ q[3] ├── Depolarizing(0.5) @ q[1] ├── Depolarizing(0.5) @ q[2] ├── Depolarizing(0.5) @ q[3] ├── AmplitudeDamping(0.5) @ q[1] ├── AmplitudeDamping(0.5) @ q[2] └── AmplitudeDamping(0.5) @ q[3]
Each depolarizing channel becomes one Pauli gate; amplitude damping is not mixed-unitary and stays. A seeded generator makes the draws reproducible:
>>> import random >>> rng = random.Random(42) >>> new_circuit = c.sample_mixedunitaries(rng=rng, ids=True) >>> print(new_circuit) 4-qubit circuit with 9 instructions: ├── H @ q[1] ├── H @ q[2] ├── H @ q[3] ├── X @ q[1] ├── I @ q[2] ├── I @ q[3] ├── AmplitudeDamping(0.5) @ q[1] ├── AmplitudeDamping(0.5) @ q[2] └── AmplitudeDamping(0.5) @ q[3]
By default, identities are not included:
>>> new_circuit = c.sample_mixedunitaries(rng=rng) >>> print(new_circuit) 4-qubit circuit with 8 instructions: ├── H @ q[1] ├── H @ q[2] ├── H @ q[3] ├── Y @ q[2] ├── Y @ q[3] ├── AmplitudeDamping(0.5) @ q[1] ├── AmplitudeDamping(0.5) @ q[2] └── AmplitudeDamping(0.5) @ q[3]
Different calls to the function generate different results:
>>> new_circuit = c.sample_mixedunitaries(rng=rng) >>> print(new_circuit) 4-qubit circuit with 7 instructions: ├── H @ q[1] ├── H @ q[2] ├── H @ q[3] ├── Z @ q[1] ├── AmplitudeDamping(0.5) @ q[1] ├── AmplitudeDamping(0.5) @ q[2] └── AmplitudeDamping(0.5) @ q[3]
>>> new_circuit = c.sample_mixedunitaries(rng=rng) >>> print(new_circuit) 4-qubit circuit with 7 instructions: ├── H @ q[1] ├── H @ q[2] ├── H @ q[3] ├── X @ q[3] ├── AmplitudeDamping(0.5) @ q[1] ├── AmplitudeDamping(0.5) @ q[2] └── AmplitudeDamping(0.5) @ q[3]
- sample_losses(rng=None)[source]
Resolve the random qubit-loss events in this circuit.
Same as
mimiqcircuits.sample_losses()applied to this circuit. EachLoss(p)becomesLoss(1.0)with probabilitypand is dropped otherwise; everything else is kept.- Parameters:
rng (random.Random) – Random number generator with a
random()method. Defaults to a newrandom.Random().- Returns:
A new circuit. The circuit itself is not changed.
- Return type:
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> _ = c.push(Loss(), 1) >>> _ = c.push(GateH(), 1) >>> c.sample_losses() 2-qubit circuit with 2 instructions: ├── Loss(1.0) @ q[1] └── H @ q[1]
- lower_losses(rng=None, lossmodel=None)[source]
Lower loss bookkeeping into primitives.
Same as
mimiqcircuits.lower_losses()applied to this circuit. It expects the randomness to be resolved already (seesample_losses()) and treats any remainingLossas a certain loss.- Parameters:
rng (random.Random) – Random number generator for stochastic rules of
lossmodel.lossmodel (LossModel) – How gates touching a lost qubit behave.
- Returns:
A new circuit with no
Lossleft.- Return type:
- resolve_losses(rng=None, lossmodel=None)[source]
Fully resolve loss into a runnable, loss-free circuit.
Same as
mimiqcircuits.resolve_losses()applied to this circuit: it runssample_losses(), thenlower_losses().- Parameters:
rng (random.Random) – Random number generator.
lossmodel (LossModel) – How gates touching a lost qubit behave.
- Returns:
A new circuit with no
Lossleft.- Return type:
Examples
In this example the
CXtouches the lost qubit 1, so it is dropped and qubit 1 is marked as lost:>>> from mimiqcircuits import * >>> c = Circuit() >>> _ = c.push(Loss(), 1) >>> _ = c.push(GateCX(), 0, 1) >>> c.resolve_losses() 2-qubit circuit with 1 instruction: └── Lost @ q[1]
- sample_loss_scenario(loss_indices, *, p=1.0, rng=None, lossmodel=None)[source]
Build a deterministic “what-if” loss scenario from this circuit.
Same as
mimiqcircuits.sample_loss_scenario()applied to this circuit: the selectedLossinstructions becomeLoss(p), the othersLoss(0.0), and the result is resolved as byresolve_losses().- Parameters:
loss_indices (int or iterable of int) – Which
Lossinstructions fire, counted from 1 in circuit order among theLossinstructions only.p (float) – The loss probability given to the selected sites.
rng (random.Random) – Random number generator.
lossmodel (LossModel) – How gates touching a lost qubit behave.
- Returns:
A new circuit with no
Lossleft.- Return type:
- Raises:
ValueError – If
pis not between 0 and 1.
Examples
Only the second
Loss(on qubit 1) fires:>>> from mimiqcircuits import * >>> c = Circuit() >>> _ = c.push(Loss(0.2), 0) >>> _ = c.push(GateCX(), 0, 1) >>> _ = c.push(Loss(0.4), 1) >>> c.sample_loss_scenario(2) 2-qubit circuit with 2 instructions: ├── CX @ q[0], q[1] └── Lost @ q[1]
- pauli_based_computation(basis=None, magic_states=False)[source]
Rewrite this circuit in Pauli-based computation form.
Equivalent to
pauli_based_computation(self, basis, magic_states). Seemimiqcircuits.pauli_based_computation()for the arguments, the form of the result and the errors raised.Here an X gate followed by a measurement of qubit 0 becomes a measurement of \(Z_0\) whose bit is then flipped, since \(X Z X = -Z\):
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> _ = c.push(GateX(), 0) >>> _ = c.push(Measure(), 0, 0) >>> c.pauli_based_computation() 1-qubit, 1-bit circuit with 2 instructions: ├── MP(Z) @ q[0], c[0] └── c[0] = !c[0]
- remove_unused()[source]
Renumber qubits, bits and z-variables so that none is left unused.
Same as
mimiqcircuits.remove_unused()applied to this circuit. The used indices of each register are renumbered0, 1, 2, ...in increasing order. The circuit itself is not changed.- Returns:
(new_circuit, qubit_map, bit_map, zvar_map), where each map is a dict from an old index to its new index.- Return type:
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> c.push(GateX(), 10) 11-qubit circuit with 1 instruction: └── X @ q[10] >>> c.push(GateSWAP(), 1, 20) 21-qubit circuit with 2 instructions: ├── X @ q[10] └── SWAP @ q[1,20] >>> c.push(GateH(), 4) 21-qubit circuit with 3 instructions: ├── X @ q[10] ├── SWAP @ q[1,20] └── H @ q[4] >>> c.remove_unused() (4-qubit circuit with 3 instructions: ├── X @ q[2] ├── SWAP @ q[0,3] └── H @ q[1] , {1: 0, 4: 1, 10: 2, 20: 3}, {}, {})
- remove_swaps(recursive=False)[source]
Remove the SWAP gates by relabeling the qubits of the gates after them.
Same as
mimiqcircuits.remove_swaps()applied to this circuit; see there for the details. The circuit itself is not changed.- Parameters:
recursive – If
True, also remove SWAP gates inside declared gates (GateCall), their inverses andBlockoperations.- Returns:
(new_circuit, qubit_permutation). Runningnew_circuitleaves the state that the original circuit leaves on qubition qubitqubit_permutation[i].- Return type:
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> c.push(GateH(), 1) 2-qubit circuit with 1 instruction: └── H @ q[1] >>> c.push(GateSWAP(), 1, 2) 3-qubit circuit with 2 instructions: ├── H @ q[1] └── SWAP @ q[1:2] >>> c.push(GateCX(), 2, 3) 4-qubit circuit with 3 instructions: ├── H @ q[1] ├── SWAP @ q[1:2] └── CX @ q[2], q[3] >>> new_c, perm = c.remove_swaps() >>> new_c 4-qubit circuit with 2 instructions: ├── H @ q[1] └── CX @ q[1], q[3] >>> # the state of qubit 1 ends on qubit 2, and that of qubit 2 on qubit 1 >>> perm [0, 2, 1, 3]
Multiple swaps example:
>>> c2 = Circuit() >>> c2.push(GateSWAP(), 1, 2) 3-qubit circuit with 1 instruction: └── SWAP @ q[1:2] >>> c2.push(GateSWAP(), 2, 3) 4-qubit circuit with 2 instructions: ├── SWAP @ q[1:2] └── SWAP @ q[2:3] >>> c2.push(GateCX(), 1, 3) 4-qubit circuit with 3 instructions: ├── SWAP @ q[1:2] ├── SWAP @ q[2:3] └── CX @ q[1], q[3] >>> new_c2, perm2 = c2.remove_swaps() >>> # an identity on qubit 3 keeps the number of qubits unchanged >>> new_c2 4-qubit circuit with 2 instructions: ├── CX @ q[2], q[1] └── ID @ q[3] >>> # what the original circuit leaves on qubit 1 is on qubit 2 of >>> # new_c2, qubit 2 on qubit 3 and qubit 3 on qubit 1 >>> perm2 [0, 2, 3, 1]
See also
mimiqcircuits.remove_swaps()
- isunitary()[source]
Return
Trueif every instruction of the circuit is unitary.An empty circuit is unitary. Measurements, resets and noise channels are not unitary.
Examples
>>> from mimiqcircuits import * >>> c = Circuit().push(GateH(), 0) >>> c.isunitary() True >>> c.push(Measure(), 0, 0).isunitary() False
- push_expval(hamiltonian, *qubits, firstzvar=None)
Append the computation of the expectation value of a Hamiltonian.
Called as a method,
circuit.push_expval(hamiltonian, *qubits). For each term \(c_j P_j\) it appends anExpectationValueof \(P_j\) into z-variablefirstzvar + jand scales it by \(c_j\) withMultiply, then sums them all withAdd, so that z-variablefirstzvarends up holding\[\langle \psi | H | \psi \rangle = \sum_j c_j \langle \psi | P_j | \psi \rangle.\]The other z-variables keep the value of each scaled term. The state is not changed.
- Parameters:
hamiltonian (Hamiltonian) – The Hamiltonian to evaluate.
*qubits (int) – The circuit qubits that the Hamiltonian qubits
0, 1, ...map to. There must be exactlyhamiltonian.num_qubits()of them.firstzvar (int, optional) – First z-variable to use. Defaults to the first unused one,
circuit.num_zvars().
- Returns:
The circuit, modified in place.
- Return type:
- Raises:
ValueError – If the number of qubits does not match the Hamiltonian.
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> h = Hamiltonian() >>> h.push(1.0, PauliString("ZZ"), 0, 1) 2-qubit Hamiltonian with 1 terms: └── 1.0 * ZZ @ q[0,1] >>> # Hamiltonian qubits 0 and 1 are circuit qubits 1 and 2 >>> c.push_expval(h, 1, 2) 3-qubit, 1-zvar circuit with 3 instructions: ├── ⟨ZZ⟩ @ q[1:2], z[0] ├── z[0] = 1.0 * z[0] └── z[0] = 0.0 + z[0]
See also
ExpectationValue,Multiply,Add
- push_lietrotter(h, qubits, t, steps)
Append the first-order (Lie-Trotter) time evolution under a Hamiltonian.
Called as a method,
circuit.push_lietrotter(h, qubits, t, steps). It approximates \(e^{-iHt}\), for \(H = \sum_{j=1}^m c_j P_j\), by\[e^{-i H t} \approx \left[ \prod_{j=1}^m e^{-i c_j P_j \Delta t} \right]^n,\]with \(n\) =
stepsand \(\Delta t = t / n\). The error per step is of order \(\Delta t^2\) and vanishes when the terms commute.One step is declared once as a gate named
trotterwith parameter \(\Delta t\), holding one Pauli rotation per term (GateRX,GateRZZ,RPauli, …). The circuit getsstepscalls to it.- Parameters:
h (Hamiltonian) – The Hamiltonian.
qubits (tuple) – The circuit qubits that the Hamiltonian qubits
0, 1, ...map to. There must be exactlyh.num_qubits()of them.t (float) – The total evolution time.
steps (int) – The number of Trotter steps \(n\).
- Returns:
The circuit, modified in place.
- Return type:
- Raises:
ValueError – If the number of qubits does not match the Hamiltonian.
See also
push_suzukitrotter(),push_yoshidatrotter(),GateDeclExamples
>>> from mimiqcircuits import * >>> c = Circuit() >>> h = Hamiltonian() >>> h.push(1.0, PauliString("ZZ"), 0, 1) 2-qubit Hamiltonian with 1 terms: └── 1.0 * ZZ @ q[0,1] >>> # evolve for t = 1 in 3 steps of 1/3 >>> c.push_lietrotter(h, (0, 1), t=1.0, steps=3) 2-qubit circuit with 3 instructions: ├── trotter(0.3333333333333333) @ q[0:1] ├── trotter(0.3333333333333333) @ q[0:1] └── trotter(0.3333333333333333) @ q[0:1]
- push_suzukitrotter(h, qubits, t, steps, order=2)
Append the time evolution under a Hamiltonian with a Suzuki-Trotter formula.
Called as a method,
circuit.push_suzukitrotter(h, qubits, t, steps, order). It approximates \(e^{-iHt}\) with the Suzuki product formula of the given evenorder, whose error per step is of order \(\Delta t^{\text{order}+1}\).The second-order formula is
\[e^{-i H t} \approx \left[ \prod_{j=1}^{m} e^{-i \frac{\Delta t}{2} H_j} \prod_{j=m}^{1} e^{-i \frac{\Delta t}{2} H_j} \right]^n\]where the Hamiltonian \(H\) is a sum of terms:
\[H = \sum_{j=1}^{m} H_j\]and the Trotter step size is:
\[\Delta t = \frac{t}{n}\]and each higher order is built from the one below by the Suzuki recursion
\[S_{2k}(\lambda) = [S_{2k-2}(p_k \lambda)]^2 \cdot S_{2k-2}((1 - 4p_k)\lambda) \cdot [S_{2k-2}(p_k \lambda)]^2\]with:
\[p_k = \left(4 - 4^{1/(2k - 1)}\right)^{-1}.\]Each order is declared once as a gate named
suzukitrotter_<order>, the higher ones calling the lower ones five times. The circuit getsstepscalls to the gate of the requested order.- Parameters:
h (Hamiltonian) – The Hamiltonian.
qubits (tuple) – The circuit qubits that the Hamiltonian qubits
0, 1, ...map to. There must be exactlyh.num_qubits()of them.t (float) – The total evolution time.
steps (int) – The number of Trotter steps \(n\).
order (int) – The order of the formula, an even integer of at least 2 (default
2).
- Returns:
The circuit, modified in place.
- Return type:
- Raises:
ValueError – If the number of qubits does not match the Hamiltonian, or
orderis not an even integer of at least 2.
See also
push_lietrotter(),push_yoshidatrotter(),GateDeclReferences
M. Suzuki, “General theory of fractal path integrals with applications to many-body theories and statistical physics”, J. Math. Phys. 32, 400 (1991).
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> h = Hamiltonian() >>> h.push(1.0, PauliString("XX"), 0, 1) 2-qubit Hamiltonian with 1 terms: └── 1.0 * XX @ q[0,1] >>> c.push_suzukitrotter(h, (0, 1), t=1.0, steps=5, order=2) 2-qubit circuit with 5 instructions: ├── suzukitrotter_2(0.2) @ q[0:1] ├── suzukitrotter_2(0.2) @ q[0:1] ├── suzukitrotter_2(0.2) @ q[0:1] ├── suzukitrotter_2(0.2) @ q[0:1] └── suzukitrotter_2(0.2) @ q[0:1]
- push_yoshidatrotter(h, qubits, t, steps, order=4)
Append the time evolution under a Hamiltonian with a Yoshida product formula.
Called as a method,
circuit.push_yoshidatrotter(h, qubits, t, steps, order). It approximates \(e^{-iHt}\) by composing second-order Trotter formulas symmetrically, which cancels the error terms up to the given evenorder. Each order makes three calls to the order below, against five forpush_suzukitrotter().The order \(2(k+1)\) formula is built from the order \(2k\) one as
\[S_{2(k+1)}(t) = S_{2k}(w_1 \cdot t) \cdot S_{2k}(w_2 \cdot t) \cdot S_{2k}(w_1 \cdot t)\]where the weights are:
\[w_1 = \frac{1}{2 - 2^{1/(2k+1)}}, \quad w_2 = -\frac{2^{1/(2k+1)}}{2 - 2^{1/(2k+1)}}\]and the base case is the standard second-order Strang splitting:
\[S_2(\Delta t) = \prod_{j=1}^{m} e^{-i \Delta t H_j / 2} \prod_{j=m}^{1} e^{-i \Delta t H_j / 2}\]Each order is declared once as a gate named
yoshida_<order>. The circuit getsstepscalls to the gate of the requested order.- Parameters:
h (Hamiltonian) – The Hamiltonian.
qubits (tuple) – The circuit qubits that the Hamiltonian qubits
0, 1, ...map to. There must be exactlyh.num_qubits()of them.t (float) – The total evolution time.
steps (int) – The number of Trotter steps \(n\).
order (int) – The order of the formula, an even integer of at least 2 (default
4).
- Returns:
The circuit, modified in place.
- Return type:
- Raises:
ValueError – If the number of qubits does not match the Hamiltonian, or
orderis not an even integer of at least 2.
See also
push_suzukitrotter(),push_lietrotter(),GateDeclReferences
H. Yoshida, “Construction of higher order symplectic integrators”, Phys. Lett. A 150, 262 (1990).
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> h = Hamiltonian() >>> h.push(1.0, PauliString("XY"), 0, 1) 2-qubit Hamiltonian with 1 terms: └── 1.0 * XY @ q[0,1] >>> h.push(0.5, PauliString("Z"), 0) 2-qubit Hamiltonian with 2 terms: ├── 1.0 * XY @ q[0,1] └── 0.5 * Z @ q[0] >>> c.push_yoshidatrotter(h, (0, 1), t=1.0, steps=3, order=4) 2-qubit circuit with 3 instructions: ├── yoshida_4(0.3333333333333333) @ q[0:1] ├── yoshida_4(0.3333333333333333) @ q[0:1] └── yoshida_4(0.3333333333333333) @ q[0:1]
- class Instruction(operation, qubits=None, bits=None, zvars=None)[source]
Bases:
objectAn operation together with the qubits, bits and z-variables it acts on.
Instructions are the elements of a
Circuit. They are usually created byCircuit.push(); build one directly to push it later or to insert it at a given position. An instruction cannot be modified after it is created.- Parameters:
operation (Operation) – The operation to apply.
qubits (tuple of int) – The target qubits, as many as
operation.num_qubits. Defaults to().bits (tuple of int) – The target classical bits, as many as
operation.num_bits. Defaults to().zvars (tuple of int) – The target z-variables, as many as
operation.num_zvars. Defaults to().
- Raises:
TypeError – If
operationis not anOperation, or a target group is not a tuple.ValueError – If a target group has the wrong length, an index is negative, or a qubit is repeated. Repeated bits or z-variables are refused too, unless the operation allows them.
Examples
>>> from mimiqcircuits import * >>> Instruction(GateX(), (0,)) X @ q[0] >>> # a measurement targets one qubit and one classical bit >>> Instruction(Measure(), (2,), (0,)) M @ q[2], c[0] >>> # consecutive targets are shown as a range >>> Instruction(Barrier(4), (0, 1, 2, 3)) Barrier @ q[0:3]
- property operation
The operation applied by the instruction (read-only).
- property qubits
The target qubits, as a tuple of int (read-only).
- property bits
The target classical bits, as a tuple of int (read-only).
- property zvars
The target z-variables, as a tuple of int (read-only).
- get_operation()[source]
Return the operation of the instruction. Same as
operation.
- get_qubits()[source]
Return the target qubits. Same as
qubits.
- get_bits()[source]
Return the target classical bits. Same as
bits.
- get_zvars()[source]
Return the target z-variables. Same as
zvars.
- num_qubits()[source]
Return the number of target qubits.
- num_bits()[source]
Return the number of target classical bits.
- num_zvars()[source]
Return the number of target z-variables.
- getparams()[source]
Return the parameters of the operation, as a list.
See
Operation.getparams().
- listvars()[source]
List the symbolic variables of the operation of the instruction.
See
Operation.listvars().
- inverse()[source]
Return the instruction applying the inverse operation on the same targets.
- Raises:
TypeError – If the operation has no inverse, such as a measurement.
NotImplementedError – If the operation is a Kraus channel.
Examples
>>> from mimiqcircuits import * >>> Instruction(GateS(), (1,)).inverse() S† @ q[1]
- isunitary()[source]
Return
Trueif the operation of the instruction is unitary.
- copy()[source]
Return a shallow copy of the instruction.
The copy shares its operation with the original. Use
deepcopy()to copy the operation too.
- deepcopy()[source]
Return a deep copy of the instruction, operation included.
- decompose()[source]
Return a circuit with one decomposition step of the operation.
The operation is replaced by the instructions of its own decomposition, placed on the instruction’s targets. Operations that have no simpler form, such as
GateUorGateCX, come back unchanged. UseCircuit.decompose()to decompose to a basis.- Returns:
The decomposed instruction.
- Return type:
Examples
>>> from mimiqcircuits import * >>> Instruction(GateCZ(), (0, 1)).decompose() 2-qubit circuit with 3 instructions: ├── H @ q[1] ├── CX @ q[0], q[1] └── H @ q[1]
- evaluate(d)[source]
Return the instruction with symbols replaced by values from
d.Symbols not in
dstay symbolic. When nothing changes, the instruction itself is returned.- Parameters:
d (dict) – Map from symbols to values.
- Returns:
The evaluated instruction.
- Return type:
Examples
>>> from mimiqcircuits import * >>> from symengine import Symbol >>> theta = Symbol("theta") >>> Instruction(GateRX(theta), (0,)).evaluate({theta: 0.5}) RX(0.5) @ q[0]
- matrix(nq=None)[source]
Return the matrix of the instruction on the full register of
nqqubits.The matrix of the operation is placed on the target qubits and extended with the identity on the other ones.
- Parameters:
nq (int) – The number of qubits of the register. Defaults to one more than the largest target qubit.
- Returns:
The
2**nqby2**nqmatrix, as a symengine matrix.- Raises:
ValueError – If
nqis not given and the instruction has no target qubits.
Examples
>>> from mimiqcircuits import * >>> # X on qubit 0 of a 2-qubit register: X ⊗ I >>> Instruction(GateX(), (0,)).matrix(2) [0, 0, 1.0, 0] [0, 0, 0, 1.0] [1.0, 0, 0, 0] [0, 1.0, 0, 0]
- push(self, operation, *args)
Add an operation or an instruction at the end of the circuit.
The targets are given in order: first the qubits, then the classical bits, then the z-variables, as many of each as the operation acts on. A target can be an integer or an iterable of integers. When some targets are iterables, one instruction is added for each position, zipping the iterables together and repeating the integer targets; the shortest iterable sets the number of instructions.
- Parameters:
operation (Operation or Instruction) – The operation to add, or an already-built instruction (then no targets are allowed).
- Returns:
The circuit itself, so calls can be chained.
- Return type:
- Raises:
TypeError – If
operationis not anOperationor anInstruction, or a target is neither an integer nor an iterable.ValueError – If the number of targets does not match the operation, a target index is negative or repeated, or
operationis an operator that is not a gate (such as a projector), which can only be used inside other operations.
Examples
Targets can be integers or iterables of integers. An iterable adds one instruction per element.
>>> from mimiqcircuits import * >>> from symengine import pi >>> c = Circuit() >>> c.push(GateH(), 0) 1-qubit circuit with 1 instruction: └── H @ q[0] >>> c.push(GateT(), 0) 1-qubit circuit with 2 instructions: ├── H @ q[0] └── T @ q[0] >>> c.push(GateH(), [0,2]) # one H on each of qubits 0 and 2 3-qubit circuit with 4 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] └── H @ q[2] >>> c.push(GateS(), 0) 3-qubit circuit with 5 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] ├── H @ q[2] └── S @ q[0] >>> c.push(GateCX(), [2, 0], 1) # controls 2 and 0, target 1 each time 3-qubit circuit with 7 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] ├── H @ q[2] ├── S @ q[0] ├── CX @ q[2], q[1] └── CX @ q[0], q[1] >>> c.push(GateH(), 0) 3-qubit circuit with 8 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] ├── H @ q[2] ├── S @ q[0] ├── CX @ q[2], q[1] ├── CX @ q[0], q[1] └── H @ q[0] >>> c.push(Barrier(3), *range(3)) # same as c.push(Barrier(3), 0, 1, 2) 3-qubit circuit with 9 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] ├── H @ q[2] ├── S @ q[0] ├── CX @ q[2], q[1] ├── CX @ q[0], q[1] ├── H @ q[0] └── Barrier @ q[0:2] >>> c.push(Measure(), range(3), range(3)) # measure qubit i into bit i 3-qubit, 3-bit circuit with 12 instructions: ├── H @ q[0] ├── T @ q[0] ├── H @ q[0] ├── H @ q[2] ├── S @ q[0] ├── CX @ q[2], q[1] ├── CX @ q[0], q[1] ├── H @ q[0] ├── Barrier @ q[0:2] ├── M @ q[0], c[0] ├── M @ q[1], c[1] └── M @ q[2], c[2]
- insert(self, index, operation, *args)
Insert an operation, an instruction or a whole circuit at a position.
The new instruction is placed before the one currently at
index, as withlist.insert. Unlikepush(), targets must be plain integers, so exactly one instruction is inserted. Whenoperationis aCircuit, all its instructions are inserted in order and no targets are given.- Parameters:
index (int) – The position to insert at.
operation (Operation, Instruction or Circuit) – What to insert.
*args (int) – The target qubits, then bits, then z-variables of
operation. Not allowed for an instruction or a circuit.
- Returns:
The circuit itself, so calls can be chained.
- Return type:
- Raises:
TypeError – If
operationis not an operation, an instruction or a circuit, orindexis not an integer when inserting a circuit.ValueError – If the number of targets is wrong, a target is invalid, or
operationis an operator that is not a gate.
Examples
>>> from mimiqcircuits import * >>> c= Circuit() >>> c.push(GateX(), 0) 1-qubit circuit with 1 instruction: └── X @ q[0] >>> c.push(GateCX(),0,1) 2-qubit circuit with 2 instructions: ├── X @ q[0] └── CX @ q[0], q[1] >>> # put an H between the X and the CX >>> c.insert(1, GateH(), 0) 2-qubit circuit with 3 instructions: ├── X @ q[0] ├── H @ q[0] └── CX @ q[0], q[1] >>> # insert a whole circuit at the start >>> c.insert(0, Circuit().push(GateZ(), 1)) 2-qubit circuit with 4 instructions: ├── Z @ q[1] ├── X @ q[0] ├── H @ q[0] └── CX @ q[0], q[1]
- append(self, other)
Add all the instructions of another circuit at the end of this one.
The instructions are added as they are, without copying or checking them. The circuit is changed in place and nothing is returned.
- Parameters:
other (Circuit or list of Instruction) – The instructions to add.
- Raises:
TypeError – If
otheris neither a circuit nor a list.
Examples
>>> from mimiqcircuits import * >>> c = Circuit().push(GateH(), 0) >>> c.append(Circuit().push(GateCX(), 0, 1)) >>> c 2-qubit circuit with 2 instructions: ├── H @ q[0] └── CX @ q[0], q[1]
- draw(self, compact=True)
Print an ASCII drawing of the circuit.
Each qubit gets a wire; the classical bits share one double wire, and so do the z-variables. When the drawing reaches the width of the canvas, the part drawn so far is printed, followed by
..., and drawing continues on a fresh canvas.- Parameters:
compact (bool) – If
True(the default), instructions on disjoint wires share a column, and consecutive instructions of the same operation on disjoint wires, such as those from one broadcastpush(), start in the same column. Instructions that touch the classical or z-variable register are always drawn one after the other. IfFalse, every instruction gets its own column, in circuit order.- Returns:
The drawing is printed, not returned.
- Return type:
None
- Raises:
ValueError – If a single instruction is wider than the canvas.
Examples
>>> from mimiqcircuits import * >>> c = Circuit().push(GateH(), 0).push(GateCX(), 0, 1) >>> c.draw()
- decompose(self, basis=None)
Decompose all operations in the circuit to a target basis.
Operations are rewritten recursively until every one is terminal in the basis. The circuit itself is not changed.
- Parameters:
basis – The target basis, a
DecompositionBasis, or aRewriteRuleto apply until it no longer matches. Defaults toCanonicalBasis(GateUandGateCX).- Returns:
A new circuit with every operation in the target basis.
- Return type:
Examples
Decompose to the canonical basis (the default):
>>> from mimiqcircuits import * >>> c = Circuit() >>> c.push(GateH(), 0) 1-qubit circuit with 1 instruction: └── H @ q[0] >>> c.push(GateCCX(), 0, 1, 2) 3-qubit circuit with 2 instructions: ├── H @ q[0] └── C₂X @ q[0:1], q[2] >>> decomposed = c.decompose() >>> # every gate is now a GateU or a GateCX >>> sorted({type(i.operation).__name__ for i in decomposed}) ['GateCX', 'GateU']
Decompose to Clifford+T:
>>> from mimiqcircuits import CliffordTBasis >>> decomposed = c.decompose(CliffordTBasis())
Use a specific rewrite rule:
>>> from mimiqcircuits import ZYZRewrite >>> decomposed = c.decompose(ZYZRewrite())
See also
mimiqcircuits.decompose(): Module-level decompose functionmimiqcircuits.CanonicalBasis: Default decomposition basismimiqcircuits.CliffordTBasis: Clifford+T decomposition