Circuit compilation & optimization¶
MIMIQ provides tools to optimize and transform quantum circuits.
Cleaning circuits¶
Remove unused¶
The remove_unused() function cleans up a circuit by removing unused qubits, classical bits, and Z-variables.
new_circuit, qubit_map, bit_map, zvar_map = remove_unused(circuit)
It returns:
The new optimized
Circuit.A mapping (dict) of old qubit indices to new ones.
A mapping (dict) of old bit indices to new ones.
A mapping (dict) of old Z-variable indices to new ones.
Example:
>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]
>>> c.push(GateCX(), 0, 2) # Qubit 1 is unused
3-qubit circuit with 2 instructions:
├── H @ q[0]
└── CX @ q[0], q[2]
>>> new_c, qmap, bmap, zmap = remove_unused(c)
>>> new_c
2-qubit circuit with 2 instructions:
├── H @ q[0]
└── CX @ q[0], q[1]
Optimization passes¶
Remove SWAPs¶
The remove_swaps() function eliminates SWAP gates by tracking qubit permutations and remapping subsequent operations.
new_circuit, final_permutation = remove_swaps(circuit, recursive=False)
Arguments:
circuit: The input circuit.recursive(defaultFalse): IfTrue, recursively removes swaps from nested blocks.
It returns:
A new
Circuitwithout SWAP gates.A list representing the final physical permutation of qubits.
Example:
>>> 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 = remove_swaps(c)
>>> new_c
4-qubit circuit with 2 instructions:
├── H @ q[1]
└── CX @ q[1], q[3]
>>> perm
[0, 2, 1, 3]
Pauli-based computation¶
In Pauli-based computation a circuit is expressed with two kinds of operations only: \(\pi/8\) rotations about multi-qubit Pauli operators, and measurements of multi-qubit Pauli operators. This is the form used by lattice-surgery architectures for surface codes, where every logical operation is a Pauli product measurement.
The pauli_based_computation() function (also available as pauli_based_computation()) performs this rewrite:
new_circuit = pauli_based_computation(circuit, basis=None, magic_states=False)
Arguments:
circuit: The input circuit.basis(defaultCliffordTBasis): The basis used to decompose the circuit into Clifford+T gates first. Measurements, resets and conditional Pauli operators are kept whole, whatever the basis.magic_states(defaultFalse): IfTrue, each rotation is further replaced by the injection of a magic state.
The circuit is decomposed into Clifford+T, then every Clifford gate is moved to the end of the circuit. On the way it changes each T gate into an RPauli rotation of angle \(\pm\pi/4\) and each measurement of a Pauli product (Measure, MeasureX, MeasureXX, MeasurePauli and the like) into a MeasurePauli. The Cliffords that end up after the last measurement do not change any outcome, so they are dropped. The new circuit gives the same measurement statistics as the original one, but not the same final state.
Example:
Prepare a Bell pair, apply a T gate to qubit 1 and measure both qubits:
>>> from mimiqcircuits import *
>>> c = Circuit()
>>> _ = c.push(GateH(), 0)
>>> _ = c.push(GateCX(), 0, 1)
>>> _ = c.push(GateT(), 1)
>>> _ = c.push(Measure(), range(2), range(2))
>>> pauli_based_computation(c)
2-qubit, 2-bit circuit with 3 instructions:
├── R("XZ", (1/4)*pi) @ q[0:1]
├── MP(X) @ q[0], c[0]
└── MP(XZ) @ q[0:1], c[1]
The Hadamard and CX gates before the T gate map \(Z_1\) to \(X_0 Z_1\), so the T gate becomes a \(\pi/8\) rotation about \(X_0 Z_1\) (RPauli with angle \(\pi/4\)). The same gates turn the measurements of \(Z_0\) and \(Z_1\) into measurements of \(X_0\) and \(X_0 Z_1\), written to the original bits.
Conditional operations and resets¶
An IfStatement whose body contains only Pauli operators, directly or inside a PauliString, Block, Parallel, Repeat or GateCall, applies one Pauli product. It becomes one conditional PauliString, with the Clifford gates before it moved past it like past a measurement. A conditional T or T† gate becomes a conditional RPauli rotation.
A reset (Reset, ResetX, ResetY) measures its qubit into a new bit, placed after the bits of the circuit, then applies a conditional Pauli that brings the qubit back to the reset state. The measure-and-reset operations do the same with the bit they are given.
>>> c2 = Circuit()
>>> _ = c2.push(GateH(), 0)
>>> _ = c2.push(Measure(), 0, 0)
>>> _ = c2.push(GateH(), 1)
>>> _ = c2.push(IfStatement(GateZ(), BitString("1")), 1, 0)
>>> _ = c2.push(Reset(), 0)
>>> _ = c2.push(Measure(), range(2), range(1, 3))
>>> pauli_based_computation(c2)
2-qubit, 4-bit circuit with 6 instructions:
├── MP(X) @ q[0], c[0]
├── IF(c==1) X @ q[1], condition[0]
├── MP(X) @ q[0], c[3]
├── IF(c==1) Z @ q[0], condition[3]
├── MP(X) @ q[0], c[1]
└── MP(X) @ q[1], c[2]
The Hadamard gate on qubit 1 turns the conditional \(Z_1\) into a conditional \(X_1\). The reset of qubit 0 measures \(X_0\) into the new bit 3 and applies \(Z_0\) when the outcome is 1.
Other conditional operations are refused with a ValueError. After a conditional Clifford gate, such as a conditional Hadamard, the Clifford gates to move would depend on the condition bits, so the later rotations and measurements could not be computed before the circuit runs.
Magic-state injection¶
A \(\pi/8\) rotation can itself be carried out with Pauli product measurements by consuming a magic state \(T\ket{+}\), prepared with PrepareStateT. With magic_states=True every rotation is replaced in this way, using one extra ancilla qubit, two extra bits per rotation and two bits per data qubit for the Pauli frame:
>>> pauli_based_computation(c, magic_states=True)
3-qubit, 8-bit circuit with 8 instructions:
├── PrepareStateT @ q[2]
├── MP(XZZ) @ q[0:2], c[2]
├── IF(c==0) MP(X) @ q[2], c[3], condition[2]
├── IF(c==1) MP(Y) @ q[2], c[3], condition[2]
├── c[4] ^= c[3]
├── c[7] ^= c[3]
├── MP(X) @ q[0], c[0]
└── MP(XZ) @ q[0:1], c[1]
Reading the result line by line:
PrepareStateTputs the ancilla (qubit 2) in the magic state.MP(XZZ)measures the rotation axis \(X_0 Z_1\) together with \(Z\) on the ancilla, into bit 2.Depending on bit 2, the ancilla is measured in X or in Y, into bit 3. The two
IfStatementlines implement this choice.The two
Xorlines record the byproduct described below in the Pauli frame.The final measurements are the same as before.
When bit 3 is 1 the rotation comes with an extra Pauli \(X_0 Z_1\) on the data qubits. It is not corrected with gates. Instead, the product of all such Paulis is kept in classical bits, the Pauli frame: bit 4 holds its X part on qubit 0 and bit 7 its Z part on qubit 1. Later outcomes that the frame would flip are corrected in place with 3-bit Xor operations. Here both final measurements commute with \(X_0 Z_1\), so no correction is needed.
With magic states a conditional Pauli is not applied either: it multiplies the frame when its condition holds. A conditional T or T† gate is refused, since a magic state cannot be injected conditionally.
Mapping to a device¶
On many devices a two-qubit gate can act only on certain pairs of qubits: neighbours on a chip, or atoms within the interaction radius of each other. The map_circuit() function rewrites a circuit for such a device. It places every qubit of the circuit on a site of the device and adds SWAP gates wherever two qubits have to be brought next to each other.
result = map_circuit(circuit, target, initial_layout=None, trials=10, seed=None)
Arguments:
circuit: The input circuit. It is not modified.target: AMappingTarget, the device to map to.initial_layout(defaultNone): The site on which each qubit starts. If given, it is kept as it is.trials(default10): How many starting layouts to try, and how many routings to try from the best one. At least 1.seed(defaultNone): Seed of the random choices of the search, between 0 and2**63 - 1. Without one a seed is drawn at random.
It returns a MappingResult with:
circuit: The mapped circuit. Its qubit indices are sites of the device.nsites: The number of sites of the device.initial_layoutandfinal_layout: The site holding each qubit before the first and after the last instruction. The two differ because the SWAPs are not undone at the end.inserted_swaps: The positions incircuitof the SWAPs that were added.seedandtrials: The settings that produced the result. Passing them back tomap_circuitgives the same result.forced: How many operations the search could not place by its score, and routed along a shortest path instead.
Describing the device¶
A MappingTarget is a number of sites and the pairs of sites that can interact. A site is one physical qubit. Give the pairs directly, or use one of the constructors:
MappingTarget(4, [(0, 1), (1, 2), (1, 3)]) # any graph
MappingTarget.line(5) # a chain
MappingTarget.ring(5) # a closed chain
MappingTarget.grid(3, 4) # a square array
MappingTarget.grid(3, 4, radius=2) # the same, with a longer range
MappingTarget.from_positions(positions, 1.5) # atoms at arbitrary positions
grid and from_positions connect every two sites at most radius apart, which is how atoms in an array interact. An atom inside a square array has 4 neighbours with radius=1, 8 with radius=math.sqrt(2) and 12 with radius=2. For an array with missing atoms, pass the positions of the atoms that are there.
Example:
A circuit in which qubit 0 interacts with all the others, on a chain of four sites:
>>> from mimiqcircuits import *
>>> c = Circuit()
>>> _ = c.push(GateH(), 0)
>>> _ = c.push(GateCX(), 0, range(1, 4))
>>> _ = c.push(Measure(), range(4), range(4))
>>> target = MappingTarget.line(4)
>>> result = map_circuit(c, target, seed=7)
>>> result.circuit
4-qubit, 4-bit circuit with 9 instructions:
├── H @ q[1]
├── CX @ q[1], q[0]
├── CX @ q[1], q[2]
├── M @ q[0], c[1]
├── M @ q[2], c[2]
├── SWAP @ q[1:2]
├── CX @ q[2], q[3]
├── M @ q[2], c[0]
└── M @ q[3], c[3]
>>> result.inserted_swaps
(5,)
>>> result.initial_layout, result.final_layout
((1, 0, 2, 3), (2, 0, 1, 3))
Every CX now acts on two neighbouring sites. Qubit 0 starts on site 1, between qubits 1 and 2, and one SWAP moves it to site 2, next to qubit 3, as the layouts say. Each measurement still writes to the bit it had in the original circuit, wherever its qubit has moved: the measurement into bit 0 reads qubit 0 on site 2, where the SWAP took it. Samples of the mapped circuit therefore read like samples of the original one.
Where the qubits start matters. Fixing qubit q on site q leaves qubit 0 at the end of the chain, and two SWAPs are needed:
>>> result = map_circuit(c, target, initial_layout=[0, 1, 2, 3], seed=7)
>>> result.inserted_swaps
(3, 6)
>>> result.final_layout
(2, 0, 1, 3)
Without initial_layout, a circuit that already fits the device is returned unchanged, with qubit q on site q.
A circuit that fits the device once its qubits are placed well is placed without any SWAP. The qubits of this chain of CX gates are not in chain order, but every qubit interacts with at most two others, along a path:
>>> chain = Circuit()
>>> _ = chain.push(GateH(), 0)
>>> _ = chain.push(GateCX(), [0, 2, 1], [2, 1, 3])
>>> placed = map_circuit(chain, target, seed=7)
>>> placed.circuit
4-qubit circuit with 4 instructions:
├── H @ q[0]
├── CX @ q[0], q[1]
├── CX @ q[1], q[2]
└── CX @ q[2], q[3]
>>> placed.initial_layout, placed.final_layout, placed.inserted_swaps
((0, 2, 1, 3), (0, 2, 1, 3), ())
To find such a placement, map_circuit matches the pairs of qubits that share an operation to pairs of sites that interact, with a backtracking search in the style of VF2 (Cordella et al., 2004), inside the largest connected part of the device. The instructions keep their order, the two layouts are the same, and qubits that share no operation take the lowest sites left. The search gives up after a fixed number of steps, so that it stays cheap on circuits that do not fit; the search below then runs instead. A given initial_layout skips it.
How the mapping is searched¶
When no placement without SWAPs is found, map_circuit uses SABRE (Li, Ding and Xie, 2019) with the refinements of LightSABRE (Zou et al., 2024). A routing pass goes through the circuit and emits each instruction as soon as the ones it depends on are emitted and its qubits are neighbours. When every waiting operation has its qubits apart, it adds the SWAP that brings them, and the operations that follow, closest together, choosing at random between equally good SWAPs. If many SWAPs pass without progress, it takes them back and moves the qubits of the closest waiting operation along a shortest path instead; MappingResult.forced counts these.
The search has two stages, each of trials passes:
Layout trials choose where the qubits start, inside the largest connected part of the device. The first trial starts from qubit
qon theq-th site, the second from a greedy placement that puts the qubits that interact most near the centre of the device, and the others from random placements near the centre. Each trial routes the circuit forward and backward five times, then forward once more, each pass starting where the previous one ended, so that the layout adapts to both the start and the end of the circuit.Routing trials route the circuit again from the best layout found, with different random choices.
The pass with the fewest SWAPs is returned, then the one with the smallest depth counted in two-qubit operations and SWAPs. With initial_layout given, only the routing trials run, from that layout.
All the random choices come from seed, so the same circuit, device, trials and seed give the same result. Without a seed, the one drawn is stored in the result:
>>> result = map_circuit(c, target, trials=5)
>>> map_circuit(c, target, trials=5, seed=result.seed) == result
True
More trials take longer and can find fewer SWAPs.
What can be mapped¶
Gates, measurements, resets and noise channels are mapped, with their parameters untouched, symbolic or not, as long as they act on at most target.max_arity qubits (2 unless set, see below). A Barrier of any width is kept. Wider operations are refused with a ValueError naming the instruction: decompose them first. So are Amplitude, BondDim, SchmidtRank and VonNeumannEntropy, whose meaning depends on the order of the qubits.
The added SWAPs are ordinary GateSWAP gates. remove_swaps() would remove them and undo the mapping, so run it before map_circuit, never after.
To test whether a circuit fits a device without changing it, use check_mapped(). It raises a ValueError at the first instruction that does not:
>>> check_mapped(c, target)
Traceback (most recent call last):
...
ValueError: instruction 2 (CX @ q[0], q[2]) acts on sites 0 and 2, which do not interact
>>> check_mapped(result.circuit, target)
Native multi-qubit gates¶
Some devices run gates on three or more qubits directly. Neutral atoms within the interaction radius of each other can run a CCZ or a Toffoli in one step, which costs much less than its decomposition into two-qubit gates. Set max_arity on the target to the number of qubits of its widest native gate. An operation on k qubits then runs on any k sites that all interact with each other, and map_circuit moves its qubits onto such sites instead of decomposing it.
On a square array with radius=math.sqrt(2), every site interacts with its diagonal neighbours, so any two neighbours in a row and the site below them form a triangle. Here a Toffoli starts with its qubits on three corners:
>>> import math
>>> wide = Circuit()
>>> _ = wide.push(GateH(), 0)
>>> _ = wide.push(GateCCX(), 0, 1, 2)
>>> _ = wide.push(GateCX(), 2, 3)
>>> grid = MappingTarget.grid(3, 3, radius=math.sqrt(2), max_arity=3)
>>> mapped = map_circuit(wide, grid, initial_layout=[0, 2, 6, 8], seed=3)
>>> mapped.circuit
9-qubit circuit with 5 instructions:
├── H @ q[0]
├── SWAP @ q[4,6]
├── SWAP @ q[0:1]
├── C₂X @ q[1:2], q[4]
└── CX @ q[4], q[8]
>>> mapped.final_layout
(1, 2, 4, 8)
Two SWAPs move qubit 0 to site 1, next to qubit 1 on site 2, and qubit 2 to site 4, which interacts with both, and the Toffoli runs there as one gate.
With radius=1 a site interacts only with the four sites next to it, and no three sites all interact. A device like that cannot run the gate, and map_circuit says so before routing anything:
>>> square = MappingTarget.grid(3, 3, max_arity=3)
>>> map_circuit(wide, square)
Traceback (most recent call last):
...
ValueError: instruction 1 (C₂X @ q[0:1], q[2]) acts on 3 qubits, the target has no 3 sites that all interact
The check looks at the connected part of the device the qubits start in: a device in several parts needs such sites in the part that holds the circuit.
Mapping in backends¶
A backend declares its connectivity with topology(). When that is not AllToAll, execute maps every circuit onto it with MapCircuitPass, after the decomposition and before gate fusion. mapping_target() turns the topology into the target: a LinearChain(n) into MappingTarget.line(n), a CouplingMap into a target with the same edges, converted from 1-based to 0-based. The seed of the mapping comes from the seed of the run, so the same seed maps the same way.
For a circuit without classical bits, bit q of each result reads logical qubit q, wherever the mapping left it, so the results look as if the circuit had run unmapped. mapping=False turns the mapping off. On an all-to-all backend mapping=True raises, since there is nothing to map to; to map onto a device of your choice there, put the pass in passes:
from mimiqcircuits.backends import MapCircuitPass, PassPipeline
# Map onto a five-site line before running on any backend.
pipeline = PassPipeline([MapCircuitPass(MappingTarget.line(5), trials=20)])
results = backend.execute(circuit, passes=pipeline, seed=1)
A mapping and qubit reordering cannot run together: reordering after a mapping would undo it. execute raises when both are asked for.
Reference¶
- remove_unused(self)[source]
Renumber qubits, bits and z-variables so that none is left unused.
The qubits used by the circuit are renumbered
0, 1, 2, ...in increasing order, and likewise the bits and the z-variables. The operations are kept as they are. The input circuit is not changed.- Parameters:
self (Circuit) – The circuit to compact.
- 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(GateH(), 0) 1-qubit circuit with 1 instruction: └── H @ q[0] >>> c.push(GateCX(), 0, 2) # qubit 1 is unused 3-qubit circuit with 2 instructions: ├── H @ q[0] └── CX @ q[0], q[2] >>> c.push(Measure(), 2, 2) # bits 0 & 1 are unused 3-qubit, 3-bit circuit with 3 instructions: ├── H @ q[0] ├── CX @ q[0], q[2] └── M @ q[2], c[2] >>> c.push(ExpectationValue(GateX()), 0, 1) # zvar 0 is unused 3-qubit, 3-bit, 2-zvar circuit with 4 instructions: ├── H @ q[0] ├── CX @ q[0], q[2] ├── M @ q[2], c[2] └── ⟨X⟩ @ q[0], z[1] >>> new_c, qmap, bmap, zmap = remove_unused(c) >>> new_c 2-qubit, 1-bit, 1-zvar circuit with 4 instructions: ├── H @ q[0] ├── CX @ q[0], q[1] ├── M @ q[1], c[0] └── ⟨X⟩ @ q[0], z[0]
>>> qmap {0: 0, 2: 1} >>> bmap {2: 0} >>> zmap {1: 0}
- remove_swaps(circuit, recursive=False, cache=None)[source]
Remove the SWAP gates of a circuit by relabeling the qubits of the gates after them.
Each
GateSWAPon qubits(i, j)is dropped, and every later instruction that would act oniacts onjinstead, and the other way round. The result applies the same operations as the original, with the qubits permuted at the end byqubit_permutation. Classical bits and z-variables are not changed. If the last instructions no longer touch the highest qubits,GateIDinstructions are added so the result keeps the same number of qubits.SWAP gates inside a
Controlor anIfStatementare never removed, since they do not always run.- Parameters:
circuit (Circuit) – The circuit to rewrite. It is not changed.
recursive (bool) – If
True, also remove SWAP gates inside declared gates (GateCall), inverses of declared gates andBlockoperations. Each one gets a new declaration without SWAP gates, and its own final permutation is folded into the relabeling of the outer circuit. Defaults toFalse.cache (dict) – Rewritten declarations, shared across recursive calls. Leave it unset.
- 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] >>> # the CX after the swap now acts where the state of qubit 1 still is >>> new_c, perm = remove_swaps(c) >>> new_c 4-qubit circuit with 2 instructions: ├── H @ q[1] └── CX @ q[1], q[3] >>> # the original ends with qubits 1 and 2 exchanged >>> perm [0, 2, 1, 3]
Two swaps compose into a cycle of three qubits:
>>> c = Circuit() >>> c.push(GateSWAP(), 1, 2) 3-qubit circuit with 1 instruction: └── SWAP @ q[1:2] >>> c.push(GateSWAP(), 2, 3) 4-qubit circuit with 2 instructions: ├── SWAP @ q[1:2] └── SWAP @ q[2:3] >>> c.push(GateCX(), 1, 3) 4-qubit circuit with 3 instructions: ├── SWAP @ q[1:2] ├── SWAP @ q[2:3] └── CX @ q[1], q[3] >>> new_c, perm = remove_swaps(c) >>> # an identity on qubit 3 keeps the number of qubits unchanged >>> new_c 4-qubit circuit with 2 instructions: ├── CX @ q[2], q[1] └── ID @ q[3] >>> perm [0, 2, 3, 1]
With
recursive=True, SWAP gates inside nested gate declarations are removed too. Here each level of declaration starts with a SWAP:>>> inner = Circuit() >>> _ = inner.push(GateSWAP(), 0, 1) >>> _ = inner.push(GateCX(), 1, 0) >>> Inner = GateDecl("Inner", [], inner)
>>> mid = Circuit() >>> _ = mid.push(GateSWAP(), 0, 1) >>> _ = mid.push(GateCall(Inner, ()), 0, 1) >>> Mid = GateDecl("Mid", [], mid)
>>> outer = Circuit() >>> _ = outer.push(GateSWAP(), 1, 2) >>> _ = outer.push(GateCall(Mid, ()), 1, 2) >>> Outer = GateDecl("Outer", [], outer)
>>> c = Circuit() >>> _ = c.push(GateSWAP(), 1, 2) >>> _ = c.push(GateCall(Outer, ()), 0, 1, 2)
>>> c 3-qubit circuit with 2 instructions: ├── SWAP @ q[1:2] └── Outer() @ q[0:2] >>> new_c, _ = remove_swaps(c, recursive=True) >>> # no SWAP is left at the top level... >>> any(isinstance(i.get_operation(), GateSWAP) for i in new_c) False >>> # ...nor in the rewritten declaration of Outer >>> outer_decl = new_c.instructions[0].get_operation().decl >>> any(isinstance(i.get_operation(), GateSWAP) for i in outer_decl.circuit) False
- pauli_based_computation(circuit, basis=None, magic_states=False)[source]
Rewrite a circuit in Pauli-based computation form.
The result is a sequence of \(\pi/8\) Pauli product rotations (
RPauliwith angle \(\pm\pi/4\)) and Pauli product measurements (MeasurePauli), with no Clifford gates left.The circuit is first decomposed with
basis, which must produce Clifford+T gates, the measurements and resets listed below, and the conditional operations described below. Those measurements, resets and conditional Pauli products are kept whole, whateverbasisdoes with them. Each Clifford \(C\) is then moved past every later T gate and measurement, conjugating them: a T gate on qubit \(q\) becomes the rotation \(\exp(-i \frac{\pi}{8} C^\dagger Z_q C)\), and a measurement of \(Z_q\) becomes a measurement of \(C^\dagger Z_q C\). When the conjugated observable has a minus sign, the rotation angle is negated, or the measured bit is flipped withNot.The Cliffords left after the last measurement do not change any outcome and are dropped. The result therefore reproduces the measurement statistics of
circuit, not its final quantum state, and each rotation is exact up to a global phase. Classical operations and annotations are kept in place; barriers and identity gates are dropped.Measurements, resets and conditional operations
Measure,MeasureX,MeasureY,MeasureXX,MeasureYY,MeasureZZandMeasurePaulimeasure a Pauli product \(P\) and become aMeasurePauliof \(C^\dagger P C\).A reset in the Z, X or Y basis (
Reset,ResetX,ResetY) measures \(Z\), \(X\) or \(Y\) into a new bit, then applies, if the outcome is 1, the Pauli that maps the \(-1\) eigenstate to the \(+1\) one: \(X\) for the Z and Y bases, \(Z\) for the X basis. The measure-and-reset operations (MeasureReset,MeasureResetX,MeasureResetY) do the same with the bit they are given.An
IfStatementwhose body is made only of Pauli operators applies one Pauli product \(P\) when its condition holds. The body can beGateX,GateY,GateZ,GateID, aPauliString, or aBlock,Parallel,RepeatorGateCallholding only such operations, at any depth. It becomes oneIfStatementof thePauliString\(C^\dagger P C\) with the same condition. The phase of \(P\) is dropped, as it only multiplies one classical branch.A conditional T or T† gate becomes a conditional
RPaulirotation with the same condition.
Any other conditional operation is refused. After a conditional Clifford gate, the accumulated Clifford would depend on the condition bits, so the later rotations and measurements could not be computed before the circuit runs.
Magic-state injection
With
magic_states=Truethe rotations are removed as well. Each \(\pi/8\) rotation on \(P\) consumes a magic state \(T\ket{+}\), prepared withPrepareStateTon one ancilla qubit that is reused for every rotation:MeasurePauliof \(P \otimes Z\) on the data qubits and the ancilla, with outcome \(m_1\).MeasurePauliof \(X\) on the ancilla if \(m_1 = 0\), of \(Y\) if \(m_1 = 1\) (swapped for a negative angle), with outcome \(m_2\). The choice is made by twoIfStatementoperations.
When \(m_2 = 1\) the rotation is applied together with a Pauli byproduct \(P\). Byproducts are not corrected with gates. Instead, their product \(F\) is tracked in classical bits, the Pauli frame: one bit for the X part and one for the Z part of \(F\) on each data qubit. When \(m_2 = 1\),
Xoroperations multiply the frame by \(P\). Each later \(m_1\) or measurement outcome whose Pauli anticommutes with \(F\) is flipped in place, again withXor, so the bits hold the outcomes of the ideal circuit.A conditional Pauli, including the correction of a reset, is not applied either: it multiplies the frame when its condition holds, with the same
Xoroperations. A condition other than a single bit equal to 1 is first evaluated into one extra bit withSetBit1and 3-bitAndoperations; each condition bit compared with 0 is flipped withNotwhile it is read and flipped back right after. A conditional T or T† gate is refused, since a magic state cannot be injected conditionally.Every classical operation added is therefore a 3-bit
XororAnd, aNotor aSetBit1, whatever the size of the circuit. The result contains only Pauli product measurements, magic-state preparations and classical logic.Bit layout
Qubits and bits are counted from 0. With \(n_b\) the number of bits of the decomposed circuit and \(r\) its number of resets, the \(j\)-th reset (counting from 0) writes its outcome to bit \(n_b + j\). With magic states, let \(n'_b = n_b + r\), \(n\) be the number of qubits and \(t\) the number of T and T† gates of the decomposed circuit. The ancilla is qubit \(n\). The \(k\)-th rotation (counting from 0) writes \(m_1\) to bit \(n'_b + 2k\) and \(m_2\) to bit \(n'_b + 2k + 1\). The frame bits of qubit \(q\) follow: the X part at bit \(n'_b + 2t + q\) and the Z part at bit \(n'_b + 2t + n + q\). The condition of a conditional Pauli, when it needs its own bit, goes to bit \(n'_b + 2t + 2n\).
- Parameters:
circuit (Circuit) – the circuit to rewrite.
basis (DecompositionBasis or RewriteRule, optional) – the basis used for the first decomposition. A rewrite rule is wrapped in a
RuleBasis. Defaults toCliffordTBasis.magic_states (bool, optional) – replace every rotation by magic-state injection. Defaults to
False.
- Returns:
a new circuit made of
RPauli,MeasurePauli, conditionalPauliStringandRPaulioperations, classical operations and annotations. Withmagic_states=True,PrepareStateT, conditionalMeasurePaulioperations and classical logic replace the rotations and conditional Paulis.- Return type:
- Raises:
ValueError – if the decomposed circuit contains anything other than Clifford+T gates, the measurements and resets listed above, the conditional operations listed above, classical operations and annotations: for example a non-Clifford gate, a conditional Clifford gate or a conditional measurement. With
magic_states=True, a conditional T or T† gate also raises aValueError.DecompositionError – if
basiscannot decompose an operation, such as a noise channel.
Examples
Prepare a Bell pair, apply a T gate to qubit 1 and measure both qubits:
>>> from mimiqcircuits import * >>> c = Circuit() >>> _ = c.push(GateH(), 0) >>> _ = c.push(GateCX(), 0, 1) >>> _ = c.push(GateT(), 1) >>> _ = c.push(Measure(), range(2), range(2)) >>> pauli_based_computation(c) 2-qubit, 2-bit circuit with 3 instructions: ├── R("XZ", (1/4)*pi) @ q[0:1] ├── MP(X) @ q[0], c[0] └── MP(XZ) @ q[0:1], c[1]
The Clifford before the T gate is \(C = \mathrm{CX}_{01} H_0\), so the T gate becomes a \(\pi/8\) rotation on \(C^\dagger Z_1 C = X_0 Z_1\). The two measurements of \(Z_0\) and \(Z_1\) become measurements of \(X_0\) and \(X_0 Z_1\), and write to the same bits as before.
With magic states, the rotation becomes an injection on the ancilla qubit 2, whose outcomes \(m_1\) and \(m_2\) go to the new bits 2 and 3:
>>> pauli_based_computation(c, magic_states=True) 3-qubit, 8-bit circuit with 8 instructions: ├── PrepareStateT @ q[2] ├── MP(XZZ) @ q[0:2], c[2] ├── IF(c==0) MP(X) @ q[2], c[3], condition[2] ├── IF(c==1) MP(Y) @ q[2], c[3], condition[2] ├── c[4] ^= c[3] ├── c[7] ^= c[3] ├── MP(X) @ q[0], c[0] └── MP(XZ) @ q[0:1], c[1]
The ancilla is measured in X or Y depending on \(m_1\) (bit 2). The byproduct \(X_0 Z_1\) goes into the frame: bit 4 holds its X part on qubit 0 and bit 7 its Z part on qubit 1. The final measurements commute with it, so their bits are not corrected.
A conditional Pauli and a reset. The Hadamard gate before the conditional \(Z_1\) turns it into a conditional \(X_1\), and the reset of qubit 0 after its Hadamard gate measures \(X_0\) into the new bit 3, then applies \(Z_0\) if the outcome is 1:
>>> c = Circuit() >>> _ = c.push(GateH(), 0) >>> _ = c.push(Measure(), 0, 0) >>> _ = c.push(GateH(), 1) >>> _ = c.push(IfStatement(GateZ(), BitString("1")), 1, 0) >>> _ = c.push(Reset(), 0) >>> _ = c.push(Measure(), range(2), range(1, 3)) >>> pauli_based_computation(c) 2-qubit, 4-bit circuit with 6 instructions: ├── MP(X) @ q[0], c[0] ├── IF(c==1) X @ q[1], condition[0] ├── MP(X) @ q[0], c[3] ├── IF(c==1) Z @ q[0], condition[3] ├── MP(X) @ q[0], c[1] └── MP(X) @ q[1], c[2]
References
D. Litinski, “A Game of Surface Codes: Large-Scale Quantum Computing with Lattice Surgery”, Quantum 3, 128 (2019).
S. Bravyi, G. Smith, J. A. Smolin, “Trading Classical and Quantum Computational Resources”, Phys. Rev. X 6, 021043 (2016).
See also
MeasurePauli,PrepareStateT,RPauli,CliffordTBasis
- map_circuit(circuit, target, initial_layout=None, trials=10, seed=None)[source]
Map
circuittotarget.Returns a circuit on the sites of the target in which every operation on two or more qubits acts on sites that all interact with each other, together with the position of every logical qubit before and after. See
MappingResultfor the exact relation between the two circuits.Operations on up to
target.max_arityqubits are routed whole: aCCXon a target withmax_arity=3is moved onto three sites of a triangle, not decomposed.Instructions are kept whole and only moved to the sites of their qubits. Where the qubits of an operation are apart, SWAP gates bring them together. Instructions that share no qubit, bit or z-variable may come out in a different order.
If the circuit is already local on the target, with qubit
qon siteq, it is returned as it is. Otherwise, if its interactions fit the target, it is placed without any SWAP: a bounded search looks for sites, in the largest connected part of the target, such that every two qubits sharing an operation sit on sites that interact. The instructions then keep their order,initial_layoutandfinal_layoutare the same, and qubits that share no operation take the lowest sites left. When the search finds no such sites, or gives up, the mapping searches, with SABRE, for few SWAPs:trialslayout trials each start from a layout of the qubits in the largest connected part of the target: qubitqon itsq-th site, a greedy placement of the qubits that interact most around its centre, and random placements near the centre. Routing the circuit forward and backward five times, then forward once more, improves that layout.trialsmore routing passes start from the best layout found.
The pass with the fewest SWAPs is returned, then the one with the smallest depth in two-qubit operations and SWAPs. A pass picks each SWAP by how much closer it brings the qubits of the waiting operations and of the next ones, choosing at random between equally good SWAPs. When that stops making progress it brings the qubits of the closest waiting operation together directly: two qubits meet in the middle of a shortest path, more gather on the nearest set of sites that all interact.
MappingResult.forcedcounts these.The random choices are drawn from
seed, so the same circuit, target,trialsandseedalways give the same result.Run
remove_swaps()and other passes that reorder qubits before mapping, never after: they would undo it.- Parameters:
circuit (Circuit) – The circuit to map. It is not modified.
target (MappingTarget) – The device.
initial_layout (sequence of int, optional) – The site of every logical qubit at the start, all different. It may be longer than the circuit is wide, to place qubits the circuit does not use. When given it is kept: only the routing passes run, also if the circuit is already local.
trials (int) – The number of layout trials and of routing trials, at least 1, 10 by default. More trials take longer and may find fewer SWAPs.
seed (int, optional) – Seed of the random choices, between 0 and
2**63 - 1. Drawn at random when not given; the result keeps it inMappingResult.seed.
- Returns:
The mapped circuit, its layouts and how it was found.
- Return type:
- Raises:
ValueError – If
trialsis less than 1 orseedis out of range; if an operation other than a barrier acts on more thantarget.max_arityqubits (decompose it first); if the circuit holds anAmplitude,BondDim,SchmidtRankorVonNeumannEntropy, directly or inside another operation such as anIfStatement, aRepeator aBlock, whose meaning depends on the order of the qubits; if the circuit has more qubits than the largest connected part of the target has sites; ifinitial_layoutis not valid, or puts the qubits of an operation on sites that no path joins; if an operation onk >= 3qubits starts in a connected part of the target with noksites that all interact. The message names the instruction.
Examples
A CX between qubits 0 and 2 does not fit a three-site line as written, but its one interaction fits the line. Qubit 2 is placed next to qubit 0, and the idle qubit 1 takes the site left:
>>> from mimiqcircuits import Circuit, GateCX, GateH >>> from mimiqcircuits.mapping import MappingTarget, map_circuit >>> c = Circuit().push(GateCX(), 0, 2) >>> target = MappingTarget.line(3) >>> result = map_circuit(c, target, seed=1) >>> result.initial_layout (0, 2, 1) >>> result.circuit 2-qubit circuit with 1 instruction: └── CX @ q[0], q[1] >>> result.inserted_swaps ()
Qubit 0 of a GHZ circuit interacts with three others, and no site of a line has three neighbours, so the search places qubit 0 between two of them and one SWAP brings the third:
>>> ghz = Circuit().push(GateH(), 0).push(GateCX(), 0, range(1, 4)) >>> result = map_circuit(ghz, MappingTarget.line(4), seed=1) >>> result.circuit 4-qubit circuit with 5 instructions: ├── H @ q[1] ├── CX @ q[1], q[0] ├── CX @ q[1], q[2] ├── SWAP @ q[2:3] └── CX @ q[1], q[2] >>> result.initial_layout, result.final_layout ((1, 0, 2, 3), (1, 0, 3, 2))
With qubit
qfixed on siteq, a SWAP brings the qubits together:>>> result = map_circuit(c, target, initial_layout=[0, 1, 2], seed=1) >>> result.circuit 3-qubit circuit with 2 instructions: ├── SWAP @ q[1:2] └── CX @ q[0], q[1] >>> result.final_layout (0, 2, 1)
A Toffoli needs three sites that interact pairwise. On a grid whose sites reach their diagonal neighbours there are such triangles, and with
max_arity=3the gate is routed whole. Its qubits start on the first row, where sites 0 and 2 do not interact; one SWAP moves qubit 2 to the centre site 4, next to both others:>>> import math >>> from mimiqcircuits import GateCCX >>> toffoli = Circuit().push(GateCCX(), 0, 1, 2) >>> grid = MappingTarget.grid(3, 3, radius=math.sqrt(2), max_arity=3) >>> map_circuit(toffoli, grid, initial_layout=[0, 1, 2], seed=1).circuit 5-qubit circuit with 2 instructions: ├── SWAP @ q[2,4] └── C₂X @ q[0:1], q[4]
A grid without diagonals has no triangle, so it cannot run the gate:
>>> map_circuit(toffoli, MappingTarget.grid(3, 3, max_arity=3)) Traceback (most recent call last): ... ValueError: instruction 0 (C₂X @ q[0:1], q[2]) acts on 3 qubits, the target has no 3 sites that all interact
The seed is kept, so a result can be reproduced:
>>> again = map_circuit(c, target, initial_layout=[0, 1, 2], seed=result.seed) >>> again == result True
- check_mapped(circuit, target)[source]
Check that every instruction of
circuitis local ontarget.The qubit indices of
circuitare read as sites. An instruction is local when its sites exist and, if it acts on two or more of them, when they interact pairwise and are not more thantarget.max_arity. ABarriermay span any sites.- Parameters:
circuit (Circuit) – The circuit to check.
target (MappingTarget) – The device.
- Raises:
ValueError – At the first instruction that is not local, with its index and the reason.
Examples
>>> from mimiqcircuits import Circuit, GateCX >>> from mimiqcircuits.mapping import MappingTarget, check_mapped >>> c = Circuit().push(GateCX(), 0, 1).push(GateCX(), 0, 2) >>> check_mapped(c, MappingTarget.line(3)) Traceback (most recent call last): ... ValueError: instruction 1 (CX @ q[0], q[2]) acts on sites 0 and 2, which do not interact
- class MappingTarget(nsites, edges, positions=None, max_arity=2)[source]
Bases:
objectA device: its sites and the pairs of sites that can interact.
A site is one physical qubit. Sites are numbered from 0. Edges have no direction:
(a, b)and(b, a)are the same edge, and repeated edges count once.The target may be disconnected.
map_circuit()then places the circuit in its largest connected part.- Parameters:
nsites (int) – Number of sites.
edges (iterable of (int, int)) – Pairs of sites that can interact.
positions (iterable of coordinates, optional) – Coordinates of every site, kept for display. All sites have the same number of coordinates.
max_arity (int) – Number of qubits of the widest operation the device runs natively, at least 2. An operation on
kqubits runs on anyksites that all interact with each other, such as aCCXon three sites of a triangle.
- nsites
Number of sites.
- Type:
- edges
The edges, each as
(a, b)witha < b, sorted and without duplicates.
- max_arity
Number of qubits of the widest native operation.
- Type:
- Raises:
ValueError – If
nsitesis negative, an edge joins a site to itself or names a site outside0..nsites-1,positionsdoes not have one entry per site or its entries differ in length, ormax_arityis less than 2.
Examples
Three sites in a row, with a reversed and a repeated edge:
>>> from mimiqcircuits.mapping import MappingTarget >>> target = MappingTarget(3, [(1, 0), (1, 2), (0, 1)]) >>> target.edges ((0, 1), (1, 2))
A 3 x 3 array where sites interact along rows, columns and diagonals:
>>> import math >>> target = MappingTarget.grid(3, 3, radius=math.sqrt(2)) >>> target.nsites, len(target.edges) (9, 20)
- classmethod line(n, max_arity=2)[source]
nsites in a row, each interacting with the next.
- classmethod ring(n, max_arity=2)[source]
nsites in a closed chain: a line whose ends also interact.
- classmethod grid(rows, cols, radius=1, max_arity=2)[source]
A
rowsxcolssquare array of sites.Sites are numbered row by row: the site in row
rand columncisr * cols + c, at position(r, c). Two sites interact when their distance, in lattice spacings, is at mostradius: the 4 nearest neighbours for 1, 8 forsqrt(2), 12 for 2.
- classmethod from_positions(positions, radius, max_arity=2)[source]
One site per position, interacting when at most
radiusapart.positionsis a sequence of coordinates, all of the same length. Siteiis atpositions[i], and two sites interact when their Euclidean distance is at mostradius. To model an array with missing atoms, pass only the occupied positions.The comparison allows a relative error of
1e-9, so that sites exactlyradiusapart interact however their coordinates are rounded. Setting the radius to the spacing of a lattice connects nearest neighbours.- Raises:
ValueError – If the positions differ in length.
- class MappingResult(circuit, nsites, initial_layout, final_layout, inserted_swaps, seed, trials, forced)[source]
Bases:
objectWhat
map_circuit()returns.For a circuit of gates, the mapped circuit does on the device what the original does on its qubits. Put a state of the logical qubits on the sites given by
initial_layout, with every other site in|0>, and runcircuit: the result is the state the original circuit gives, on the sites given byfinal_layout, with every other site in|0>. The two agree exactly, global phase included.The layouts differ whenever SWAPs were inserted: no SWAPs are added at the end to bring the qubits back. Classical bits and z-variables are never renamed, so measurements write where they did in the original circuit.
- circuit
The mapped circuit. Its qubit indices are sites.
- Type:
- nsites
Number of sites of the target. The circuit alone does not tell it when the last sites are idle.
- Type:
- initial_layout
initial_layout[q]is the site that holds logical qubitqbefore the first instruction. All different.
- inserted_swaps
Positions in
circuitof the SWAP gates added by the mapping. AGateSWAPof the original circuit is not listed.
- seed
The seed of the search. Passing it back to
map_circuit(), with the sametrials, gives the same result.- Type:
- trials
The number of layout and routing trials.
- Type:
- forced
The number of operations of the returned routing that the search could not place by its score within its step limit and whose qubits were brought together directly instead. The limit counts SWAPs, not distance, so a single operation on distant qubits can be forced with an optimal SWAP count. A count that is high relative to the circuit means the search did poorly on this circuit.
- Type: