#
# Copyright © 2026 QPerfect. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Mapping of a circuit to a device with limited connectivity.
A :class:`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. :func:`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
:class:`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.
"""
import math
import operator
import secrets
from dataclasses import dataclass
from itertools import combinations
import numpy as np
from mimiqcircuits import _core
from mimiqcircuits.circuit import Circuit
from mimiqcircuits.instruction import Instruction
from mimiqcircuits.operations.amplitude import Amplitude
from mimiqcircuits.operations.barrier import Barrier
from mimiqcircuits.operations.block import Block
from mimiqcircuits.operations.entanglement import (
BondDim,
SchmidtRank,
VonNeumannEntropy,
)
from mimiqcircuits.operations.gates.standard.swap import GateSWAP
__all__ = [
"MappingTarget",
"MappingResult",
"map_circuit",
"check_mapped",
]
# Operations whose value depends on the order of the qubits in the register.
_ORDER_DEPENDENT = (Amplitude, BondDim, SchmidtRank, VonNeumannEntropy)
def _order_dependent(op):
"""Whether ``op`` is, or holds, an operation in ``_ORDER_DEPENDENT``."""
if isinstance(op, Block):
return any(_order_dependent(inst.operation) for inst in op)
if op.iswrapper():
inner = op.get_operation()
if inner is not op:
return _order_dependent(inner)
return isinstance(op, _ORDER_DEPENDENT)
# Sites exactly ``radius`` apart have to interact, as when the radius is set
# to the spacing of a lattice, and the rounding of their coordinates can put
# them on either side of it.
_RADIUS_TOLERANCE = 1e-9
def _positions(positions):
"""Positions as tuples of floats, all with the same number of coordinates."""
positions = tuple(tuple(float(x) for x in p) for p in positions)
if len({len(p) for p in positions}) > 1:
raise ValueError("positions must all have the same number of coordinates")
return positions
[docs]
class MappingTarget:
"""A 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. :func:`map_circuit` then places the circuit
in its largest connected part.
Args:
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 ``k`` qubits runs on
any ``k`` sites that all interact with each other, such as a
``CCX`` on three sites of a triangle.
Attributes:
nsites (int): Number of sites.
edges (tuple of (int, int)): The edges, each as ``(a, b)`` with
``a < b``, sorted and without duplicates.
positions (tuple of tuple of float or None): Coordinates of the sites.
max_arity (int): Number of qubits of the widest native operation.
Raises:
ValueError: If ``nsites`` is negative, an edge joins a site to itself
or names a site outside ``0..nsites-1``, ``positions`` does not
have one entry per site or its entries differ in length, or
``max_arity`` is 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)
"""
def __init__(self, nsites, edges, positions=None, max_arity=2):
nsites = operator.index(nsites)
if nsites < 0:
raise ValueError(f"nsites must not be negative, got {nsites}")
max_arity = operator.index(max_arity)
if max_arity < 2:
raise ValueError(f"max_arity must be at least 2, got {max_arity}")
normalized = set()
for a, b in edges:
a, b = operator.index(a), operator.index(b)
if a == b:
raise ValueError(f"edge ({a}, {b}) joins a site to itself")
if not (0 <= a < nsites and 0 <= b < nsites):
raise ValueError(
f"edge ({a}, {b}) is outside the sites 0 to {nsites - 1}"
)
normalized.add((min(a, b), max(a, b)))
if positions is not None:
positions = _positions(positions)
if len(positions) != nsites:
raise ValueError(
f"positions has {len(positions)} entries, the target has {nsites} sites"
)
self._nsites = nsites
self._edges = tuple(sorted(normalized))
self._positions = positions
self._max_arity = max_arity
self._edgeset = frozenset(self._edges)
[docs]
@classmethod
def line(cls, n, max_arity=2):
"""``n`` sites in a row, each interacting with the next."""
return cls(n, [(i, i + 1) for i in range(n - 1)], max_arity=max_arity)
[docs]
@classmethod
def ring(cls, n, max_arity=2):
"""``n`` sites in a closed chain: a line whose ends also interact."""
edges = [(i, i + 1) for i in range(n - 1)]
if n > 2:
edges.append((n - 1, 0))
return cls(n, edges, max_arity=max_arity)
[docs]
@classmethod
def grid(cls, rows, cols, radius=1, max_arity=2):
"""A ``rows`` x ``cols`` square array of sites.
Sites are numbered row by row: the site in row ``r`` and column ``c``
is ``r * cols + c``, at position ``(r, c)``. Two sites interact when
their distance, in lattice spacings, is at most ``radius``: the 4
nearest neighbours for 1, 8 for ``sqrt(2)``, 12 for 2.
"""
positions = [(r, c) for r in range(rows) for c in range(cols)]
return cls.from_positions(positions, radius, max_arity=max_arity)
[docs]
@classmethod
def from_positions(cls, positions, radius, max_arity=2):
"""One site per position, interacting when at most ``radius`` apart.
``positions`` is a sequence of coordinates, all of the same length.
Site ``i`` is at ``positions[i]``, and two sites interact when their
Euclidean distance is at most ``radius``. To model an array with
missing atoms, pass only the occupied positions.
The comparison allows a relative error of ``1e-9``, so that sites
exactly ``radius`` apart 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.
"""
positions = _positions(positions)
reach = radius * (1 + _RADIUS_TOLERANCE)
# shortcut: compares every pair of sites, bin the positions in cells
# when arrays grow past tens of thousands of sites.
edges = []
if positions:
points = np.array(positions, dtype=float).reshape(len(positions), -1)
for i in range(len(points) - 1):
gap = np.sqrt(((points[i + 1 :] - points[i]) ** 2).sum(axis=1))
edges.extend((i, i + 1 + int(j)) for j in np.flatnonzero(gap <= reach))
return cls(len(positions), edges, positions=positions, max_arity=max_arity)
@property
def nsites(self):
return self._nsites
@property
def edges(self):
return self._edges
@property
def positions(self):
return self._positions
@property
def max_arity(self):
return self._max_arity
def __eq__(self, other):
if not isinstance(other, MappingTarget):
return NotImplemented
return (self._nsites, self._edges, self._positions, self._max_arity) == (
other._nsites,
other._edges,
other._positions,
other._max_arity,
)
def __hash__(self):
return hash((self._nsites, self._edges, self._positions, self._max_arity))
def __repr__(self):
return f"MappingTarget({self._nsites} sites, {len(self._edges)} edges)"
[docs]
@dataclass(frozen=True)
class MappingResult:
"""What :func:`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
run ``circuit``: the result is the state the original circuit gives, on
the sites given by ``final_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.
Attributes:
circuit (Circuit): The mapped circuit. Its qubit indices are sites.
nsites (int): Number of sites of the target. The circuit alone does
not tell it when the last sites are idle.
initial_layout (tuple of int): ``initial_layout[q]`` is the site that
holds logical qubit ``q`` before the first instruction. All
different.
final_layout (tuple of int): The same after the last instruction.
inserted_swaps (tuple of int): Positions in ``circuit`` of the SWAP
gates added by the mapping. A ``GateSWAP`` of the original circuit
is not listed.
seed (int): The seed of the search. Passing it back to
:func:`map_circuit`, with the same ``trials``, gives the same
result.
trials (int): The number of layout and routing trials.
forced (int): 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.
"""
circuit: Circuit
nsites: int
initial_layout: tuple
final_layout: tuple
inserted_swaps: tuple
seed: int
trials: int
forced: int
def _nonlocal(circuit, target):
"""Index of the first instruction that is not local on ``target`` and why,
or ``None`` if there is none."""
nsites, edges = target.nsites, target._edgeset
for i, inst in enumerate(circuit):
qubits = inst.qubits
for q in qubits:
if q >= nsites:
return i, f"acts on site {q}, the target has {nsites} sites"
if len(qubits) < 2 or isinstance(inst.operation, Barrier):
continue
if len(qubits) > target.max_arity:
return i, (
f"acts on {len(qubits)} qubits, "
f"the target runs at most {target.max_arity}"
)
for a, b in combinations(qubits, 2):
if (min(a, b), max(a, b)) not in edges:
return i, f"acts on sites {a} and {b}, which do not interact"
return None
[docs]
def check_mapped(circuit, target):
"""Check that every instruction of ``circuit`` is local on ``target``.
The qubit indices of ``circuit`` are 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 than ``target.max_arity``. A
:class:`~mimiqcircuits.Barrier` may span any sites.
Args:
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
"""
found = _nonlocal(circuit, target)
if found is not None:
i, why = found
raise ValueError(f"instruction {i} ({circuit[i]}) {why}")
[docs]
def map_circuit(circuit, target, initial_layout=None, trials=10, seed=None):
"""Map ``circuit`` to ``target``.
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
:class:`MappingResult` for the exact relation between the two circuits.
Operations on up to ``target.max_arity`` qubits are routed whole: a
``CCX`` on a target with ``max_arity=3`` is 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 ``q`` on site
``q``, 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_layout`` and ``final_layout`` are 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:
1. ``trials`` layout trials each start from a layout of the qubits in the
largest connected part of the target: qubit ``q`` on its ``q``-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.
2. ``trials`` more 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.
:attr:`MappingResult.forced` counts these.
The random choices are drawn from ``seed``, so the same circuit, target,
``trials`` and ``seed`` always give the same result.
Run :func:`~mimiqcircuits.remove_swaps` and other passes that reorder
qubits before mapping, never after: they would undo it.
Args:
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 in :attr:`MappingResult.seed`.
Returns:
MappingResult: The mapped circuit, its layouts and how it was found.
Raises:
ValueError: If ``trials`` is less than 1 or ``seed`` is out of range;
if an operation other than a barrier acts on more than
``target.max_arity`` qubits (decompose it first); if the circuit
holds an ``Amplitude``, ``BondDim``, ``SchmidtRank`` or
``VonNeumannEntropy``, directly or inside another operation such
as an ``IfStatement``, a ``Repeat`` or a ``Block``, 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; if ``initial_layout`` is not valid,
or puts the qubits of an operation on sites that no path joins;
if an operation on ``k >= 3`` qubits starts in a connected part of
the target with no ``k`` sites 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]
<BLANKLINE>
>>> 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]
<BLANKLINE>
>>> result.initial_layout, result.final_layout
((1, 0, 2, 3), (1, 0, 3, 2))
With qubit ``q`` fixed on site ``q``, 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]
<BLANKLINE>
>>> 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=3`` the 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]
<BLANKLINE>
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
"""
if isinstance(trials, bool) or isinstance(seed, bool):
raise TypeError("trials and seed must be integers, not bool")
trials = operator.index(trials)
if trials < 1:
raise ValueError(f"trials must be at least 1, got {trials}")
if seed is None:
seed = secrets.randbits(63)
seed = operator.index(seed)
if not 0 <= seed < 2**63:
raise ValueError(f"seed must be between 0 and 2**63 - 1, got {seed}")
return _map_circuit(circuit, target, initial_layout, trials, seed, None)
def _arrays(circuit, target):
"""The targets of the instructions of ``circuit`` as the native code takes
them. Raises on the operations it cannot map."""
qubits, nqubits, bits, nbits, zvars, nzvars, barriers = [], [], [], [], [], [], []
for i, inst in enumerate(circuit):
op = inst.operation
barrier = isinstance(op, Barrier)
if _order_dependent(op):
raise ValueError(
f"instruction {i} ({inst}) depends on the order of the qubits "
"and cannot be mapped"
)
if len(inst.qubits) > target.max_arity and not barrier:
raise ValueError(
f"instruction {i} ({inst}) acts on {len(inst.qubits)} qubits, "
f"the target runs at most {target.max_arity}; decompose it first"
)
qubits.extend(inst.qubits)
nqubits.append(len(inst.qubits))
bits.extend(inst.bits)
nbits.append(len(inst.bits))
zvars.extend(inst.zvars)
nzvars.append(len(inst.zvars))
barriers.append(barrier)
return qubits, nqubits, bits, nbits, zvars, nzvars, barriers
def _map_circuit(circuit, target, initial_layout, trials, seed, stall):
""":func:`map_circuit` without checks on ``trials`` and ``seed``, with two
more settings for tests.
``trials = 0`` routes once, from ``initial_layout`` or from qubit ``q`` on
the ``q``-th site of the largest connected part. ``stall`` is the number
of SWAPs without progress before an operation is routed along a shortest
path, ``None`` for 10 per placed qubit; ``0`` routes every operation that
way, with no random choice.
"""
n = circuit.num_qubits()
if initial_layout is not None:
initial_layout = [operator.index(s) for s in initial_layout]
if len(initial_layout) < n:
raise ValueError(
f"initial_layout places {len(initial_layout)} qubits, the circuit has {n}"
)
if len(set(initial_layout)) != len(initial_layout):
raise ValueError("initial_layout uses a site more than once")
for s in initial_layout:
if not 0 <= s < target.nsites:
raise ValueError(
f"initial_layout uses site {s}, outside the sites 0 to {target.nsites - 1}"
)
n = len(initial_layout)
arrays = _arrays(circuit, target)
insts = circuit.instructions
if initial_layout is None and _nonlocal(circuit, target) is None:
layout = tuple(range(n))
return MappingResult(
Circuit(list(insts)), target.nsites, layout, layout, (), seed, trials, 0
)
try:
entries, initial, final, forced = _core.map_circuit(
target.nsites, list(target.edges), *arrays,
n, initial_layout, trials, seed, stall,
)
except ValueError as e:
# The native code knows an instruction by its index only.
msg = str(e)
if msg.startswith("instruction "):
i = int(msg.split()[1])
msg = msg.replace(f"instruction {i}", f"instruction {i} ({insts[i]})", 1)
raise ValueError(msg) from None
swap = GateSWAP()
out, swaps = [], []
for i, sites in entries:
sites = tuple(sites)
if i < 0:
swaps.append(len(out))
out.append(Instruction(swap, sites))
elif sites == insts[i].qubits:
out.append(insts[i])
else:
out.append(Instruction(insts[i].operation, sites, insts[i].bits, insts[i].zvars))
mapped = Circuit(out)
check_mapped(mapped, target)
return MappingResult(
mapped, target.nsites, tuple(initial), tuple(final), tuple(swaps),
seed, trials, forced,
)
def _embed(circuit, target, budget):
"""The layout of every qubit of ``circuit`` under which it fits ``target``
with no SWAP, as :func:`map_circuit` searches for it within ``budget``
assignments, or ``None``. For tests: it assumes that the circuit passes
the checks of :func:`map_circuit`."""
layout = _core.embed(
target.nsites, list(target.edges), *_arrays(circuit, target),
circuit.num_qubits(), budget,
)
return None if layout is None else tuple(layout)