mimiqcircuits.mapping¶
Mapping of a circuit to a device with limited connectivity.
A MappingTarget describes a device as a set of sites, one per physical
qubit, the pairs of sites that can interact, and the widest operation the
device runs natively. map_circuit() returns an equivalent circuit that
acts on sites and applies every multi-qubit operation to sites that interact
pairwise, adding SWAP gates where the qubits of an operation are apart. The
MappingResult also tells where every qubit of the circuit starts and
ends on the device.
A circuit whose interactions fit the device is placed without SWAPs, by a bounded backtracking search in the style of VF2 (Cordella et al., 2004). Otherwise the layout and the SWAPs are chosen with SABRE (Li, Ding and Xie, 2019) and the LightSABRE refinements (Zou et al., 2024). The search runs in the native extension, which sees only the qubits, bits and z-variables each instruction touches. Operations are never opened or changed, so symbolic parameters stay symbolic.
Functions
|
Check that every instruction of |
|
Map |
Classes
|
What |
|
A device: its sites and the pairs of sites that can 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.
- edges¶
The edges, each as
(a, b)witha < b, sorted and without duplicates.
- 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 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.
- 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:
- 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:
- 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