A directional code with iSWAP gates

Directional codes (Gehér, Byfield and Ruban, Nature Communications, 2026) are qLDPC codes whose syndrome extraction needs only a square grid of couplers. They measure stabilisers of weight 7 with CXSWAP and CZSWAP gates, each an iSWAP up to single-qubit Cliffords. A CPSWAP gate entangles an ancilla with a data qubit and swaps the two, so every layer moves the ancillas one step across the grid, and the next layer pairs each ancilla with a data qubit it hasn’t met.

This guide builds the smallest code the paper benchmarks, the rotated N2E3N2 code [[48,12,4]] on 96 qubits, from the paper’s construction. No Deltakit code class is involved: the circuit is built in Stim, Deltakit adds its SI1000 noise, and MaestroBackend runs it. It then runs T1 decay, which Stim can only run as its Pauli twirl, on Maestro’s stabilizer.

At a glance

Step 1: Building the code from its syndrome extraction circuit

Data and ancilla qubits alternate like a chequerboard on a twisted torus wrapped by the lattice vectors v1 = (−6, 8) and v2 = (6, 8). X and Z ancillas alternate by row and column, as in the surface code. Each round resets the ancillas to |+⟩, applies seven CPSWAP layers (north, north, east, east, east, north, north) with each ancilla acting as control (CXSWAP from an X ancilla, CZSWAP from a Z ancilla), and finishes by measuring the ancillas in the X basis.

Because each CPSWAP layer swaps ancillas and data qubits in opposite directions, the circuit builder tracks which physical qubit holds each logical role and pairs each stabiliser measurement with the matching stabiliser from the previous round. The Z logical operators are derived algebraically from the check matrices as operators that commute with every X stabiliser without being products of Z stabilisers.

def directional_code(alpha: int, beta: int, d: int, rounds: int) -> tuple[stim.Circuit, int, int]:
    """Z-basis memory of the rotated N^alpha E^beta N^alpha code, as a noiseless CPSWAP circuit.

    Data and ancilla qubits alternate like a chequerboard on the torus that
    v1 = (-beta*d/2, alpha*d) and v2 = (beta*d/2, alpha*d) wrap. X and Z
    ancillas alternate by row and column, as in the surface code. Each round
    resets the ancillas to |+>, applies the CPSWAP layers with the ancilla as
    control (CXSWAP from an X ancilla, CZSWAP from a Z ancilla) and measures the
    ancillas in X. The ancillas move with every layer and the data qubits the
    other way, so stabilisers are matched across rounds by the data they touch.

    Returns the circuit, the number of data qubits and of logical qubits.
    """
    width, height = beta * d // 2, 2 * alpha * d  # (width, alpha*d), (0, height) span v1, v2

    def site(x: int, y: int) -> int:
        k = x // width
        return (x - k * width) * height + (y - k * alpha * d) % height

    coords = [(i // height, i % height) for i in range(width * height)]
    data = [i for i, (x, y) in enumerate(coords) if (x + y) % 2 == 0]
    ancillas = [i for i, (x, y) in enumerate(coords) if (x + y) % 2 == 1]
    x_type = {a: coords[a][0] % 2 == 0 for a in ancillas}
    layers = [(0, 1)] * alpha + [(1, 0)] * beta + [(0, 1)] * alpha
    where = list(range(len(coords)))  # state -> the qubit holding it
    held = list(range(len(coords)))  # qubit -> the state it holds

    circuit = stim.Circuit()
    for q, xy in enumerate(coords):
        circuit.append("QUBIT_COORDS", [q], xy)
    circuit.append("R", data)
    circuit.append("TICK")
    measured, previous, stabilisers = 0, {}, None
    for r in range(rounds):
        circuit.append("RX", sorted(where[a] for a in ancillas))
        circuit.append("TICK")
        support = {a: [] for a in ancillas}
        for dx, dy in layers:
            pairs = {True: [], False: []}
            moves = []
            for a in ancillas:
                q = where[a]
                partner = site(coords[q][0] + dx, coords[q][1] + dy)
                support[a].append(held[partner])
                pairs[x_type[a]] += [q, partner]
                moves.append((a, q, partner))
            circuit.append("CXSWAP", pairs[True])
            circuit.append("CZSWAP", pairs[False])
            circuit.append("TICK")
            # The SWAP part: the ancilla's state moves to the data qubit's site, and back.
            for a, q, partner in moves:
                state = held[partner]
                where[a], where[state], held[partner], held[q] = partner, q, a, state
        order = sorted(ancillas, key=lambda a: where[a])
        circuit.append("MX", [where[a] for a in order])
        keys = {}
        for j, a in enumerate(order):
            assert set(support[a]) <= set(data) and len(set(support[a])) == len(layers)
            keys[(x_type[a], frozenset(support[a]))] = (measured + j, coords[where[a]])
        measured += len(order)
        stabilisers = stabilisers or set(keys)
        assert set(keys) == stabilisers, "every round measures the same stabilisers"
        for key, (m, xy) in keys.items():
            if r or not key[0]:  # Z stabilisers are deterministic from the first round
                recs = [m] + ([previous[key][0]] if r else [])
                circuit.append("DETECTOR", [stim.target_rec(i - measured) for i in recs], [*xy, r])
        previous = keys
        circuit.append("TICK")

    order = sorted(data, key=lambda s: where[s])
    circuit.append("M", [where[s] for s in order])
    data_record = {s: measured + j for j, s in enumerate(order)}
    measured += len(order)
    for (is_x, support_set), (m, xy) in previous.items():
        if not is_x:
            recs = [m, *(data_record[s] for s in support_set)]
            circuit.append("DETECTOR", [stim.target_rec(i - measured) for i in recs], [*xy, rounds])

    checks = {
        kind: np.array(
            [[s in sup for s in data] for (is_x, sup) in stabilisers if is_x == kind], np.uint8
        )
        for kind in (True, False)
    }
    logicals = z_logicals(checks[True], checks[False])
    for i, v in enumerate(logicals):
        targets = [stim.target_rec(data_record[data[j]] - measured) for j in np.nonzero(v)[0]]
        circuit.append("OBSERVABLE_INCLUDE", targets, i)
    return circuit, len(data), len(logicals)


Stim’s detector_error_model() raises if a detector or observable isn’t deterministic, so the circuit is checked before any noise is added. Twelve logical qubits come out, as the paper gives for every N2E3N2 code. The lightest logical of each type has weight 4.

1. The code
  rotated N2E3N2, d=4: [[48,12]] on 96 qubits
  torus v1=(-6, 8), v2=(6, 8)
  stabilisers of weight 7, 7 CPSWAP layers a round, 4 rounds
  192 detectors and 12 observables, all deterministic

Step 2: iSWAP gates and SI1000 noise

Each CPSWAP becomes an iSWAP with single-qubit Cliffords. The identities are checked against Stim’s tableaux when the script loads:

# CXSWAP a b = H b; S_DAG a b; ISWAP a b; H a  and  CZSWAP a b = S_DAG a b; ISWAP a b
assert stim.Circuit("H 1\nS_DAG 0 1\nISWAP 0 1\nH 0").to_tableau() == stim.Tableau.from_named_gate(
    "CXSWAP"
)
assert stim.Circuit("S_DAG 0 1\nISWAP 0 1").to_tableau() == stim.Tableau.from_named_gate("CZSWAP")


A layer’s CXSWAPs and CZSWAPs become one layer of iSWAPs: H on the CXSWAP targets, S_DAG on every qubit in the layer, ISWAP, then H on the CXSWAP controls. This is the example’s own compilation, not necessarily the paper’s. Deltakit then adds SI1000 noise on a QPU whose native gates are the ones the circuit uses.

def to_iswap(circuit: stim.Circuit) -> stim.Circuit:
    """CXSWAP and CZSWAP as iSWAP with single-qubit Cliffords, and X-basis resets
    and measurements as Z-basis ones with H, one kind of gate a moment.

    ``directional_code`` puts each layer's CXSWAP before its CZSWAP, so the two
    become one layer of iSWAPs: H on the CXSWAP targets, S_DAG on every qubit
    of the layer, ISWAP, then H on the CXSWAP controls.
    """
    out = stim.Circuit()
    cx_pairs = []
    for inst in circuit:
        name, targets = inst.name, [t.value for t in inst.targets_copy()]
        if name == "CXSWAP":
            cx_pairs = targets
        elif name == "CZSWAP":
            pairs = cx_pairs + targets
            out.append("H", cx_pairs[1::2])
            out.append("TICK")
            out.append("S_DAG", pairs)
            out.append("TICK")
            out.append("ISWAP", pairs)
            out.append("TICK")
            out.append("H", cx_pairs[::2])
        elif name == "RX":
            out.append("R", targets)
            out.append("TICK")
            out.append("H", targets)
        elif name == "MX":
            out.append("H", targets)
            out.append("TICK")
            out.append("M", targets)
        else:
            out.append(inst)
    return out


def with_si1000(circuit: stim.Circuit, p: float) -> stim.Circuit:
    """``circuit`` with Deltakit's SI1000(p) noise, on a QPU whose gates are
    those the circuit uses."""
    # From Deltakit 0.9, Circuit.from_stim_circuit reads Deltakit's Stim fork;
    # given a stim.Circuit it returns an empty circuit.
    deltakit_circuit = Circuit.from_stim_circuit(DeltakitStimCircuit(str(circuit)))
    gates = NativeGateSetAndTimes(
        one_qubit_gates=dict.fromkeys([H, S_DAG], 1.0), two_qubit_gates={ISWAP: 1.0}
    )
    qpu = QPU(deltakit_circuit.qubits, native_gates_and_times=gates, noise_model=SI1000Noise(p=p))
    return to_stim(qpu.add_noise_to_circuit(deltakit_circuit))


Two things about Deltakit 0.10.2 shaped this step:

  • Circuit.from_stim_circuit reads Deltakit’s own Stim fork, deltakit_stim. Given a stim.Circuit, it returns an empty circuit, so the circuit goes in as deltakit_stim.Circuit(str(circuit)). Deltakit 0.8 has no fork and reads a stim.Circuit, which the example falls back to.

  • QPU.compile_circuit to a native gate set of ISWAP gave this circuit non-deterministic detectors, even when its input was already in iSWAP form. So the gates are rewritten in Stim, and Deltakit only adds the noise with add_noise_to_circuit.

Deltakit’s own memory circuits take use_iswap_gates=True only with a Deltakit cloud client. This circuit needs none.

2. The iSWAP circuit with SI1000(p=0.001)
  operations: R×240  H×1728  S_DAG×2688  ISWAP×1344  M×240
  noise:      DEPOLARIZE1×8064  DEPOLARIZE2×1344  X_ERROR×240, and M(p) flips

Step 3: Pauli noise against Stim

SI1000 is Pauli noise, so Maestro samples it on Pauli frames, and Stim samples the same circuit as an independent check. For Pauli noise alone, Stim is as fast or faster (see Performance); the check is here to show that the iSWAP gates run correctly.

backend = MaestroBackend()
maestro_dets = backend.simulate(noisy, shots=SHOTS_PAULI, seed=SEED).detection_events
stim_dets, _ = noisy.compile_detector_sampler(seed=SEED + 1).sample(
    SHOTS_PAULI, separate_observables=True
)
m, s = rate(maestro_dets.mean(1)), rate(stim_dets.mean(1))
print(f"  detection rate, {SHOTS_PAULI:,} shots each:")
print(f"    Maestro {m[0]:.5f} ± {m[1]:.5f}")
print(f"    Stim    {s[0]:.5f} ± {s[1]:.5f}   ratio {m[0] / s[0]:.4f}, z {z_score(m, s):+.2f}")

3. Pauli noise: Maestro's Pauli frames against Stim
  detection rate, 100,000 shots each:
    Maestro 0.07756 ± 0.00013
    Stim    0.07770 ± 0.00013   ratio 0.9982, z -0.78

Step 4: T1 decay against its Pauli twirl

t1= adds T1 decay after every gate, one- or two-qubit. The iSWAP circuit has four gates a layer, so the decay adds up: γ = p would about double the detection rate of SI1000(p), and the example takes γ = p/2. Maestro’s stabilizer runs the decay itself, shot by shot, resetting each qubit a gate touched to |0⟩ with probability γ. Its Pauli twirl, PAULI_CHANNEL_1(γ/4, γ/4, γ/4) after the same gates, runs on Pauli frames. Both are decoded with BP-OSD against the twirl’s detector error model, which is what compile_sampler gives either one. A logical error is any of the 12 observables decoded wrong.

decay = backend.compile_sampler(noisy, decoder=None, seed=SEED, t1=T1)
twirl = backend.compile_sampler(backend.twirled_circuit(noisy, t1=T1), decoder=None, seed=SEED)
assert twirl.task.detector_error_model == decay.task.detector_error_model
decoder = BpOsd(decay.task.detector_error_model)
print("  detection rate:")
print(f"    {'':<27} {'shots':>8}   {'first round':>15}   {'all rounds':>15}")
runs = {}
for label, sampler, shots in (
    ("T1 decay, shot by shot", decay, SHOTS_DECAY),
    ("Pauli twirl, Pauli frames", twirl, SHOTS_TWIRL),
):
    dets, obs = sampler.sample_detection_events(shots)
    first, every = rate(dets[:, first_round].mean(1)), rate(dets.mean(1))
    runs[label] = (dets, obs, first, every)
    print(
        f"    {label:<27} {shots:>8,}   {first[0]:.4f} ± {first[1]:.4f}   "
        f"{every[0]:.4f} ± {every[1]:.4f}"
    )
(d_dets, d_obs, d_first, d_all), (t_dets, t_obs, t_first, t_all) = runs.values()
print(
    f"    {'twirl / decay':<27} {'':>8}   {t_first[0] / d_first[0]:.3f} (z {z_score(t_first, d_first):+.1f})"
    f"    {t_all[0] / d_all[0]:.3f} (z {z_score(t_all, d_all):+.1f})"
)
# Shots come back in random order, so the first SHOTS_DECODED are a fair sample.
n_dec = SHOTS_DECODED
d_ler = rate(decoder.fails(d_dets[:n_dec], d_obs[:n_dec]).astype(float))
t_ler = rate(decoder.fails(t_dets[:n_dec], t_obs[:n_dec]).astype(float))
print(f"  logical error, any of the {k} observables, BP-OSD on {n_dec:,} shots each:")
print(f"    {'T1 decay':<27} {d_ler[0]:.4f} ± {d_ler[1]:.4f}")
print(
    f"    {'Pauli twirl':<27} {t_ler[0]:.4f} ± {t_ler[1]:.4f}   "
    f"twirl / decay {t_ler[0] / d_ler[0]:.3f} (z {z_score(t_ler, d_ler):+.1f})"
)

The decay and its twirl differ where a qubit sits in |0⟩. The decay leaves such a qubit alone, and the twirl flips it. In the first round the data qubits are still in |0⟩, so the first round’s detectors are where to look. After the X stabilisers are measured, the data qubits’ states are spread over |0⟩ and |1⟩, and the two act alike on average. T1 decay on qLDPC codes measures the same comparison on bivariate bicycle codes, with more shots.

BP-OSD is a simpler decoder than the Tesseract decoder the paper uses, so these logical error rates sit above the paper’s. Compare the decay with its twirl here, not with the paper.

4. T1 decay (gamma=0.0005) against its Pauli twirl, decoded alike with BP-OSD
  detection rate:
                                   shots       first round        all rounds
    T1 decay, shot by shot         3,000   0.0771 ± 0.0016   0.1177 ± 0.0009
    Pauli twirl, Pauli frames    100,000   0.0805 ± 0.0003   0.1193 ± 0.0001
    twirl / decay                          1.044 (z +2.0)    1.013 (z +1.8)
  logical error, any of the 12 observables, BP-OSD on 1,000 shots each:
    T1 decay                    0.3040 ± 0.0146
    Pauli twirl                 0.3250 ± 0.0148   twirl / decay 1.069 (z +1.0)
Left, the 6 by 16 square grid of the 96-qubit N2E3N2 directional code showing one ancilla's 7-step N2E3N2 nearest-neighbor CPSWAP walk in blue arrows and its 7 measured data qubits in orange. Right top, detection-event rate across time slices t=0 to t=4 for T1 decay and its Pauli twirl. Right bottom, the Pauli twirl divided by T1 decay ratio (±2σ), starting at 1.044 in the initial round where data qubits begin in |0⟩ and settling near 1.00 in bulk rounds.

Left: the 96-qubit [[48,12,4]] N2E3N2 square grid showing a single ancilla’s 7-step nearest-neighbor walk (N, N, E, E, E, N, N) and the weight-7 X stabiliser support it assembles across the twisted torus. Right: round-by-round detection rates and twirl ÷ T1 decay ratio (±2σ) from the live run above.

Key takeaways

  • A circuit built straight from a paper’s construction, with no Deltakit code class, runs through MaestroBackend like Deltakit’s own circuits, with Deltakit’s noise models.

  • Each iSWAP-family gate gets its NoiseModel noise once, after the whole gate, as a native gate would (see Supported circuits).

  • T1 decay on a 96-qubit qLDPC code runs on Maestro’s stabilizer shot by shot, and its twirl, decoded alike, shows what the Pauli approximation changes.

  • Next: Extended stabilizer beyond a statevector runs small coherent over-rotations on a 49-qubit d=5 surface code.


Full script and complete output

View full script (examples/example_directional_code.py)
"""
Directional Codes — a qLDPC code on a square grid, run with iSWAP gates
========================================================================

Directional codes (Gehér, Byfield and Ruban, Nat. Commun. 2026,
https://doi.org/10.1038/s41467-026-79572-9) are qLDPC codes whose syndrome
extraction needs only a square grid of couplers. A CXSWAP or CZSWAP gate, an
iSWAP up to single-qubit Cliffords, entangles an ancilla with a data qubit and
swaps the two, so each layer moves every ancilla one step and the next layer
pairs it with a data qubit it has not met. Seven layers, north, north, east,
east, east, north, north, measure stabilisers of weight 7.

This example builds the smallest code the paper benchmarks, the rotated N2E3N2
code [[48,12,4]] on 96 qubits, from the paper's construction, and runs it on
Maestro:

    1. The code: its CPSWAP syndrome-extraction circuit on a twisted torus, a
       4-round Z-basis memory, with detectors and observables checked to be
       deterministic.
    2. The iSWAP circuit: CXSWAP and CZSWAP rewritten in Stim as iSWAP with
       single-qubit Cliffords, and Deltakit's SI1000 noise added.
    3. Pauli noise on Maestro's Pauli frames, against Stim as a correctness
       check.
    4. T1 decay, which isn't a Pauli channel, shot by shot on Maestro's
       stabilizer, against its Pauli twirl. Both are decoded with BP-OSD from
       ``ldpc`` against the twirl's detector error model.

Deltakit enters only for the noise: its ``QPU.compile_circuit`` to an ISWAP gate
set (Deltakit 0.10.2) gave this circuit non-deterministic detectors, so the
gates are rewritten in Stim, with identities checked against Stim's tableaux.

Usage:
    pip install -e ".[examples]"    # from the project root (deltakit-maestro/)
    python examples/example_directional_code.py
    python examples/example_directional_code.py --plot directional_code.png  # needs matplotlib
"""

# Deltakit must be imported before pymatching or ldpc's dependants load: with
# pymatching 2.4 loaded first, Deltakit's circuit builders fail.
try:  # Deltakit 0.9 on reads its own Stim fork
    from deltakit_stim import Circuit as DeltakitStimCircuit
except ImportError:  # Deltakit 0.8 reads Stim
    from stim import Circuit as DeltakitStimCircuit
from deltakit.circuit import Circuit
from deltakit.circuit.gates import ISWAP, S_DAG, H
from deltakit.explorer.qpu import QPU, NativeGateSetAndTimes, SI1000Noise

# isort: split
import argparse
import itertools
import os
from collections import Counter

import numpy as np
import scipy.sparse
import stim
from ldpc import BpOsdDecoder

from deltakit_maestro import MaestroBackend, to_stim

# =============================================================================
# CONFIGURATION
# =============================================================================

ALPHA, BETA, D = 2, 3, 4  # the rotated N2E3N2 code of distance 4: [[48,12,4]]
ROUNDS = D
P = 0.001  # SI1000 noise strength
# T1 decay probability after every gate, one- or two-qubit. The iSWAP circuit has
# four gates a layer, so gamma = p would about double SI1000's detection rate.
T1 = P / 2
SHOTS_PAULI = 100_000  # Pauli frames and Stim are fast
SHOTS_DECAY = 3_000  # T1 decay runs shot by shot, ~11 ms a shot here
SHOTS_TWIRL = 100_000  # its twirl runs on Pauli frames
SHOTS_DECODED = 1_000  # per arm; BP-OSD takes ~10-20 ms a shot here
SEED = 1

# CXSWAP a b = H b; S_DAG a b; ISWAP a b; H a  and  CZSWAP a b = S_DAG a b; ISWAP a b
assert stim.Circuit("H 1\nS_DAG 0 1\nISWAP 0 1\nH 0").to_tableau() == stim.Tableau.from_named_gate(
    "CXSWAP"
)
assert stim.Circuit("S_DAG 0 1\nISWAP 0 1").to_tableau() == stim.Tableau.from_named_gate("CZSWAP")


# =============================================================================
# THE CODE
# =============================================================================


def directional_code(alpha: int, beta: int, d: int, rounds: int) -> tuple[stim.Circuit, int, int]:
    """Z-basis memory of the rotated N^alpha E^beta N^alpha code, as a noiseless CPSWAP circuit.

    Data and ancilla qubits alternate like a chequerboard on the torus that
    v1 = (-beta*d/2, alpha*d) and v2 = (beta*d/2, alpha*d) wrap. X and Z
    ancillas alternate by row and column, as in the surface code. Each round
    resets the ancillas to |+>, applies the CPSWAP layers with the ancilla as
    control (CXSWAP from an X ancilla, CZSWAP from a Z ancilla) and measures the
    ancillas in X. The ancillas move with every layer and the data qubits the
    other way, so stabilisers are matched across rounds by the data they touch.

    Returns the circuit, the number of data qubits and of logical qubits.
    """
    width, height = beta * d // 2, 2 * alpha * d  # (width, alpha*d), (0, height) span v1, v2

    def site(x: int, y: int) -> int:
        k = x // width
        return (x - k * width) * height + (y - k * alpha * d) % height

    coords = [(i // height, i % height) for i in range(width * height)]
    data = [i for i, (x, y) in enumerate(coords) if (x + y) % 2 == 0]
    ancillas = [i for i, (x, y) in enumerate(coords) if (x + y) % 2 == 1]
    x_type = {a: coords[a][0] % 2 == 0 for a in ancillas}
    layers = [(0, 1)] * alpha + [(1, 0)] * beta + [(0, 1)] * alpha
    where = list(range(len(coords)))  # state -> the qubit holding it
    held = list(range(len(coords)))  # qubit -> the state it holds

    circuit = stim.Circuit()
    for q, xy in enumerate(coords):
        circuit.append("QUBIT_COORDS", [q], xy)
    circuit.append("R", data)
    circuit.append("TICK")
    measured, previous, stabilisers = 0, {}, None
    for r in range(rounds):
        circuit.append("RX", sorted(where[a] for a in ancillas))
        circuit.append("TICK")
        support = {a: [] for a in ancillas}
        for dx, dy in layers:
            pairs = {True: [], False: []}
            moves = []
            for a in ancillas:
                q = where[a]
                partner = site(coords[q][0] + dx, coords[q][1] + dy)
                support[a].append(held[partner])
                pairs[x_type[a]] += [q, partner]
                moves.append((a, q, partner))
            circuit.append("CXSWAP", pairs[True])
            circuit.append("CZSWAP", pairs[False])
            circuit.append("TICK")
            # The SWAP part: the ancilla's state moves to the data qubit's site, and back.
            for a, q, partner in moves:
                state = held[partner]
                where[a], where[state], held[partner], held[q] = partner, q, a, state
        order = sorted(ancillas, key=lambda a: where[a])
        circuit.append("MX", [where[a] for a in order])
        keys = {}
        for j, a in enumerate(order):
            assert set(support[a]) <= set(data) and len(set(support[a])) == len(layers)
            keys[(x_type[a], frozenset(support[a]))] = (measured + j, coords[where[a]])
        measured += len(order)
        stabilisers = stabilisers or set(keys)
        assert set(keys) == stabilisers, "every round measures the same stabilisers"
        for key, (m, xy) in keys.items():
            if r or not key[0]:  # Z stabilisers are deterministic from the first round
                recs = [m] + ([previous[key][0]] if r else [])
                circuit.append("DETECTOR", [stim.target_rec(i - measured) for i in recs], [*xy, r])
        previous = keys
        circuit.append("TICK")

    order = sorted(data, key=lambda s: where[s])
    circuit.append("M", [where[s] for s in order])
    data_record = {s: measured + j for j, s in enumerate(order)}
    measured += len(order)
    for (is_x, support_set), (m, xy) in previous.items():
        if not is_x:
            recs = [m, *(data_record[s] for s in support_set)]
            circuit.append("DETECTOR", [stim.target_rec(i - measured) for i in recs], [*xy, rounds])

    checks = {
        kind: np.array(
            [[s in sup for s in data] for (is_x, sup) in stabilisers if is_x == kind], np.uint8
        )
        for kind in (True, False)
    }
    logicals = z_logicals(checks[True], checks[False])
    for i, v in enumerate(logicals):
        targets = [stim.target_rec(data_record[data[j]] - measured) for j in np.nonzero(v)[0]]
        circuit.append("OBSERVABLE_INCLUDE", targets, i)
    return circuit, len(data), len(logicals)


def row_reduce(m: np.ndarray) -> tuple[np.ndarray, list[int]]:
    """Reduced row echelon form over GF(2), and its pivot columns."""
    m = m.copy() % 2
    pivots = []
    for c in range(m.shape[1]):
        r = len(pivots)
        if r == m.shape[0]:
            break
        hits = np.nonzero(m[r:, c])[0]
        if not len(hits):
            continue
        m[[r, r + hits[0]]] = m[[r + hits[0], r]]
        for i in np.nonzero(m[:, c])[0]:
            if i != r:
                m[i] ^= m[r]
        pivots.append(c)
    return m, pivots


def z_logicals(x_checks: np.ndarray, z_checks: np.ndarray) -> list[np.ndarray]:
    """Independent Z logicals: they commute with every X stabiliser and are not
    products of Z stabilisers."""
    reduced, pivots = row_reduce(x_checks)
    n = x_checks.shape[1]
    span, logicals = z_checks, []
    for free in (c for c in range(n) if c not in pivots):
        v = np.zeros(n, np.uint8)
        v[free] = 1
        for i, p in enumerate(pivots):
            v[p] = reduced[i, free]
        grown = np.vstack([span, v])
        if len(row_reduce(grown)[1]) > len(row_reduce(span)[1]):
            span, logicals = grown, logicals + [v]
    return logicals


# =============================================================================
# THE iSWAP CIRCUIT
# =============================================================================


def to_iswap(circuit: stim.Circuit) -> stim.Circuit:
    """CXSWAP and CZSWAP as iSWAP with single-qubit Cliffords, and X-basis resets
    and measurements as Z-basis ones with H, one kind of gate a moment.

    ``directional_code`` puts each layer's CXSWAP before its CZSWAP, so the two
    become one layer of iSWAPs: H on the CXSWAP targets, S_DAG on every qubit
    of the layer, ISWAP, then H on the CXSWAP controls.
    """
    out = stim.Circuit()
    cx_pairs = []
    for inst in circuit:
        name, targets = inst.name, [t.value for t in inst.targets_copy()]
        if name == "CXSWAP":
            cx_pairs = targets
        elif name == "CZSWAP":
            pairs = cx_pairs + targets
            out.append("H", cx_pairs[1::2])
            out.append("TICK")
            out.append("S_DAG", pairs)
            out.append("TICK")
            out.append("ISWAP", pairs)
            out.append("TICK")
            out.append("H", cx_pairs[::2])
        elif name == "RX":
            out.append("R", targets)
            out.append("TICK")
            out.append("H", targets)
        elif name == "MX":
            out.append("H", targets)
            out.append("TICK")
            out.append("M", targets)
        else:
            out.append(inst)
    return out


def with_si1000(circuit: stim.Circuit, p: float) -> stim.Circuit:
    """``circuit`` with Deltakit's SI1000(p) noise, on a QPU whose gates are
    those the circuit uses."""
    # From Deltakit 0.9, Circuit.from_stim_circuit reads Deltakit's Stim fork;
    # given a stim.Circuit it returns an empty circuit.
    deltakit_circuit = Circuit.from_stim_circuit(DeltakitStimCircuit(str(circuit)))
    gates = NativeGateSetAndTimes(
        one_qubit_gates=dict.fromkeys([H, S_DAG], 1.0), two_qubit_gates={ISWAP: 1.0}
    )
    qpu = QPU(deltakit_circuit.qubits, native_gates_and_times=gates, noise_model=SI1000Noise(p=p))
    return to_stim(qpu.add_noise_to_circuit(deltakit_circuit))


# =============================================================================
# DECODING
# =============================================================================


class BpOsd:
    """BP-OSD on a detector error model: one column per error, one row per detector."""

    def __init__(self, dem: stim.DetectorErrorModel):
        checks, observables, priors = [], [], []
        for inst in dem.flattened():
            if inst.type != "error":
                continue
            column = len(priors)
            priors.append(inst.args_copy()[0])
            for t in inst.targets_copy():
                if t.is_relative_detector_id():
                    checks.append((t.val, column))
                elif t.is_logical_observable_id():
                    observables.append((t.val, column))
        self.checks = _matrix(checks, (dem.num_detectors, len(priors)))
        self.observables = _matrix(observables, (dem.num_observables, len(priors)))
        self.decoder = BpOsdDecoder(
            self.checks,
            error_channel=priors,
            max_iter=30,
            bp_method="product_sum",
            osd_method="osd0",
        )

    def fails(self, dets: np.ndarray, obs: np.ndarray) -> np.ndarray:
        errors = np.array([self.decoder.decode(d.astype(np.uint8)) for d in dets])
        predicted = (errors @ self.observables.T) % 2
        return np.any(predicted != obs, axis=1)


def _matrix(entries, shape) -> scipy.sparse.csc_matrix:
    rows, cols = zip(*entries) if entries else ((), ())
    return scipy.sparse.csc_matrix((np.ones(len(rows), dtype=np.uint8), (rows, cols)), shape=shape)


def rate(values: np.ndarray) -> tuple[float, float]:
    """Mean of per-shot values and its standard error."""
    return values.mean(), values.std(ddof=1) / np.sqrt(len(values))


def z_score(a: tuple[float, float], b: tuple[float, float]) -> float:
    return (a[0] - b[0]) / np.hypot(a[1], b[1])


# =============================================================================
# FIGURE (OPTIONAL: pass --plot PATH or set DIRECTIONAL_CODE_PLOT)
# =============================================================================


def _example_walk(
    alpha: int, beta: int, d: int, start: tuple[int, int] = (2, 9)
) -> tuple[
    int,
    int,
    list[tuple[int, int]],
    list[int],
    list[int],
    dict[int, bool],
    list[tuple[int, int]],
    list[tuple[int, int]],
]:
    """Lattice geometry, one N^alpha E^beta N^alpha ancilla trajectory, and its data support."""
    width, height = beta * d // 2, 2 * alpha * d

    def site(x: int, y: int) -> int:
        k = x // width
        return (x - k * width) * height + (y - k * alpha * d) % height

    coords = [(i // height, i % height) for i in range(width * height)]
    data = [i for i, (x, y) in enumerate(coords) if (x + y) % 2 == 0]
    ancillas = [i for i, (x, y) in enumerate(coords) if (x + y) % 2 == 1]
    x_type = {a: coords[a][0] % 2 == 0 for a in ancillas}
    layers = [(0, 1)] * alpha + [(1, 0)] * beta + [(0, 1)] * alpha
    where = list(range(len(coords)))
    held = list(range(len(coords)))
    target = coords.index(start)
    path = [start]
    support: list[int] = []

    for dx, dy in layers:
        moves = []
        for a in ancillas:
            q = where[a]
            partner = site(coords[q][0] + dx, coords[q][1] + dy)
            if a == target:
                support.append(held[partner])
            moves.append((a, q, partner))
        for a, q, partner in moves:
            state = held[partner]
            where[a], where[state], held[partner], held[q] = partner, q, a, state
            if a == target:
                path.append(coords[partner])
    return width, height, coords, data, ancillas, x_type, path, [coords[s] for s in support]


def save_figure(
    path: str,
    noisy: stim.Circuit,
    d_dets: np.ndarray,
    t_dets: np.ndarray,
) -> None:
    """Save a two-part summary figure: N2E3N2 grid walk and per-round T1 vs. twirl."""
    import matplotlib

    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    blue, orange, aqua = "#2a78d6", "#eb6834", "#1baf7a"
    ink, ink_2, grid, surface = "#0b0b0b", "#52514e", "#e4e3de", "#fcfcfb"

    plt.rcParams.update(
        {
            "figure.dpi": 110,
            "savefig.dpi": 150,
            "figure.facecolor": surface,
            "axes.facecolor": surface,
            "savefig.facecolor": surface,
            "font.size": 10,
            "axes.edgecolor": ink_2,
            "axes.labelcolor": ink,
            "axes.titlecolor": ink,
            "axes.titlesize": 11,
            "axes.titleweight": "bold",
            "axes.titlelocation": "left",
            "axes.spines.top": False,
            "axes.spines.right": False,
            "axes.grid": True,
            "grid.color": grid,
            "grid.linewidth": 0.8,
            "axes.axisbelow": True,
            "xtick.color": ink_2,
            "ytick.color": ink_2,
            "legend.frameon": False,
            "lines.linewidth": 2,
            "errorbar.capsize": 0,
        }
    )

    fig = plt.figure(figsize=(10.5, 4.8), layout="constrained")
    gs = fig.add_gridspec(2, 2, width_ratios=[0.78, 1.32], height_ratios=[1.0, 1.0])
    ax_grid = fig.add_subplot(gs[:, 0])
    ax_rate = fig.add_subplot(gs[0, 1])
    ax_ratio = fig.add_subplot(gs[1, 1], sharex=ax_rate)

    # Left panel: 6x16 square grid (96 qubits) with one N2E3N2 walk and its weight-7 support.
    width, height, coords, data, ancillas, x_type, walk, support_xy = _example_walk(ALPHA, BETA, D)
    ax_grid.grid(False)
    for x in range(width):
        ax_grid.plot([x, x], [0, height - 1], color=grid, linewidth=0.9, zorder=1)
    for y in range(height):
        ax_grid.plot([0, width - 1], [y, y], color=grid, linewidth=0.9, zorder=1)

    support_set = set(support_xy)
    other_data = [coords[q] for q in data if coords[q] not in support_set]
    x_anc = [coords[a] for a in ancillas if x_type[a]]
    z_anc = [coords[a] for a in ancillas if not x_type[a]]

    ax_grid.scatter(
        [p[0] for p in other_data],
        [p[1] for p in other_data],
        s=26,
        facecolors=surface,
        edgecolors="#9e9c96",
        linewidths=1.0,
        zorder=2,
        label="data qubit (48)",
    )
    ax_grid.scatter(
        [p[0] for p in x_anc],
        [p[1] for p in x_anc],
        s=22,
        marker="s",
        facecolors="#d8d6cf",
        edgecolors="none",
        zorder=2,
        label="X / Z ancilla (48)",
    )
    ax_grid.scatter(
        [p[0] for p in z_anc],
        [p[1] for p in z_anc],
        s=22,
        marker="^",
        facecolors="#d8d6cf",
        edgecolors="none",
        zorder=2,
    )
    ax_grid.scatter(
        [p[0] for p in support_xy],
        [p[1] for p in support_xy],
        s=68,
        facecolors=orange,
        edgecolors=surface,
        linewidths=1.2,
        zorder=4,
        label="weight-7 X check support",
    )

    # Draw the 7 nearest-neighbor CPSWAP / iSWAP steps (N, N, E, E, E, N, N).
    for (x0, y0), (x1, y1) in itertools.pairwise(walk):
        ax_grid.annotate(
            "",
            xy=(x1, y1),
            xytext=(x0, y0),
            arrowprops={
                "arrowstyle": "-|>,head_width=0.22,head_length=0.35",
                "color": blue,
                "lw": 2.2,
                "shrinkA": 3,
                "shrinkB": 4,
            },
            zorder=5,
        )
    ax_grid.scatter(
        [walk[0][0]],
        [walk[0][1]],
        s=72,
        marker="s",
        facecolors=blue,
        edgecolors=surface,
        linewidths=1.2,
        zorder=6,
        label="ancilla N2E3N2 walk",
    )
    ax_grid.annotate(
        "start",
        walk[0],
        xytext=(-8, 0),
        textcoords="offset points",
        ha="right",
        va="center",
        fontsize=8.5,
        color=blue,
        weight="bold",
    )
    ax_grid.set(
        title="N2E3N2 grid (96 qubits)",
        xlabel="grid x",
        ylabel="grid y",
        xlim=(-0.6, width - 0.4),
        ylim=(-0.7, height - 0.3),
        xticks=range(width),
        yticks=range(0, height, 3),
    )
    ax_grid.legend(
        loc="upper center",
        bbox_to_anchor=(0.48, -0.14),
        ncol=2,
        fontsize=8,
        columnspacing=0.9,
        handletextpad=0.35,
    )

    # Right panels: per-round T1 decay vs. Pauli twirl detection rates and ratio.
    det_coords = noisy.get_detector_coordinates()
    times = sorted({int(c[2]) for c in det_coords.values()})
    d_means, d_errs, t_means, t_errs, ratios, ratio_errs = [], [], [], [], [], []
    for t in times:
        idx = [i for i, c in det_coords.items() if int(c[2]) == t]
        dm, de = rate(d_dets[:, idx].mean(1))
        tm, te = rate(t_dets[:, idx].mean(1))
        r = tm / dm
        re = r * float(np.hypot(de / dm, te / tm))
        d_means.append(dm)
        d_errs.append(de)
        t_means.append(tm)
        t_errs.append(te)
        ratios.append(r)
        ratio_errs.append(re)

    t_arr = np.array(times)
    ax_rate.errorbar(
        t_arr - 0.06,
        d_means,
        yerr=[2 * e for e in d_errs],
        color=blue,
        marker="o",
        markeredgecolor=surface,
        markeredgewidth=1.4,
        markersize=7,
        elinewidth=1.5,
        label=f"T1 decay, shot by shot (γ={T1:g})",
    )
    ax_rate.errorbar(
        t_arr + 0.06,
        t_means,
        yerr=[2 * e for e in t_errs],
        color=orange,
        linestyle="--",
        marker="s",
        markerfacecolor=surface,
        markersize=6,
        elinewidth=1.5,
        label="Pauli twirl, Pauli frames",
    )
    ax_rate.set(
        title=f"T1 decay vs. Pauli twirl on [[48,12,4]] (SI1000, p={P:g})",
        ylabel="detection rate (±2σ)",
        ylim=(0.068, 0.142),
    )
    ax_rate.tick_params(labelbottom=False)
    ax_rate.legend(loc="lower center", fontsize=8.5)

    ax_ratio.axhline(1.0, color=ink_2, linewidth=1.0)
    ax_ratio.errorbar(
        t_arr,
        ratios,
        yerr=[2 * e for e in ratio_errs],
        color=aqua,
        marker="D",
        markeredgecolor=surface,
        markeredgewidth=1.4,
        markersize=6.5,
        elinewidth=1.6,
        label="twirl ÷ T1 decay (±2σ)",
    )
    ax_ratio.annotate(
        "data in |0⟩",
        (0, ratios[0]),
        xytext=(12, 6),
        textcoords="offset points",
        fontsize=8.5,
        color=ink_2,
    )
    ax_ratio.annotate(
        "twirl = decay",
        (3.5, 1.0),
        xytext=(0, -13),
        textcoords="offset points",
        ha="center",
        fontsize=8.5,
        color=ink_2,
    )
    ax_ratio.set(
        xlabel="detector time slice",
        ylabel="twirl ÷ T1 decay",
        xticks=t_arr,
        ylim=(0.965, 1.100),
    )
    ax_ratio.set_xticklabels(["t=0\n(init Z)", "t=1", "t=2", "t=3", "t=4\n(final Z)"], fontsize=9)

    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    fig.savefig(path, bbox_inches="tight")
    plt.close(fig)


# =============================================================================
# MAIN
# =============================================================================


def main(plot_path: str | None = None):
    print("=" * 86)
    print("  Directional codes: the rotated N2E3N2 code [[48,12,4]] with iSWAP gates")
    print("=" * 86)

    print("\n1. The code")
    circuit, n, k = directional_code(ALPHA, BETA, D, ROUNDS)
    circuit.detector_error_model()  # raises if a detector or observable isn't deterministic
    print(f"  rotated N{ALPHA}E{BETA}N{ALPHA}, d={D}: [[{n},{k}]] on {circuit.num_qubits} qubits")
    print(f"  torus v1=({-BETA * D // 2}, {ALPHA * D}), v2=({BETA * D // 2}, {ALPHA * D})")
    print(
        f"  stabilisers of weight {2 * ALPHA + BETA}, {2 * ALPHA + BETA} CPSWAP layers a round, {ROUNDS} rounds"
    )
    print(
        f"  {circuit.num_detectors} detectors and {circuit.num_observables} observables, all deterministic"
    )

    print(f"\n2. The iSWAP circuit with SI1000(p={P})")
    noisy = with_si1000(to_iswap(circuit), P)
    noisy.detector_error_model()  # still deterministic
    counts = Counter(inst.name for inst in noisy.flattened() for _ in inst.target_groups())
    print(
        "  operations: " + "  ".join(f"{g}×{counts[g]}" for g in ("R", "H", "S_DAG", "ISWAP", "M"))
    )
    noise = sorted(n for n in counts if stim.gate_data(n).is_noisy_gate and n != "M")
    print("  noise:      " + "  ".join(f"{n}×{counts[n]}" for n in noise) + ", and M(p) flips")
    first_round = [i for i, c in noisy.get_detector_coordinates().items() if c[2] == 0]

    print("\n3. Pauli noise: Maestro's Pauli frames against Stim")
    backend = MaestroBackend()
    maestro_dets = backend.simulate(noisy, shots=SHOTS_PAULI, seed=SEED).detection_events
    stim_dets, _ = noisy.compile_detector_sampler(seed=SEED + 1).sample(
        SHOTS_PAULI, separate_observables=True
    )
    m, s = rate(maestro_dets.mean(1)), rate(stim_dets.mean(1))
    print(f"  detection rate, {SHOTS_PAULI:,} shots each:")
    print(f"    Maestro {m[0]:.5f} ± {m[1]:.5f}")
    print(f"    Stim    {s[0]:.5f} ± {s[1]:.5f}   ratio {m[0] / s[0]:.4f}, z {z_score(m, s):+.2f}")

    print(f"\n4. T1 decay (gamma={T1}) against its Pauli twirl, decoded alike with BP-OSD")
    decay = backend.compile_sampler(noisy, decoder=None, seed=SEED, t1=T1)
    twirl = backend.compile_sampler(backend.twirled_circuit(noisy, t1=T1), decoder=None, seed=SEED)
    assert twirl.task.detector_error_model == decay.task.detector_error_model
    decoder = BpOsd(decay.task.detector_error_model)
    print("  detection rate:")
    print(f"    {'':<27} {'shots':>8}   {'first round':>15}   {'all rounds':>15}")
    runs = {}
    for label, sampler, shots in (
        ("T1 decay, shot by shot", decay, SHOTS_DECAY),
        ("Pauli twirl, Pauli frames", twirl, SHOTS_TWIRL),
    ):
        dets, obs = sampler.sample_detection_events(shots)
        first, every = rate(dets[:, first_round].mean(1)), rate(dets.mean(1))
        runs[label] = (dets, obs, first, every)
        print(
            f"    {label:<27} {shots:>8,}   {first[0]:.4f} ± {first[1]:.4f}   "
            f"{every[0]:.4f} ± {every[1]:.4f}"
        )
    (d_dets, d_obs, d_first, d_all), (t_dets, t_obs, t_first, t_all) = runs.values()
    print(
        f"    {'twirl / decay':<27} {'':>8}   {t_first[0] / d_first[0]:.3f} (z {z_score(t_first, d_first):+.1f})"
        f"    {t_all[0] / d_all[0]:.3f} (z {z_score(t_all, d_all):+.1f})"
    )
    # Shots come back in random order, so the first SHOTS_DECODED are a fair sample.
    n_dec = SHOTS_DECODED
    d_ler = rate(decoder.fails(d_dets[:n_dec], d_obs[:n_dec]).astype(float))
    t_ler = rate(decoder.fails(t_dets[:n_dec], t_obs[:n_dec]).astype(float))
    print(f"  logical error, any of the {k} observables, BP-OSD on {n_dec:,} shots each:")
    print(f"    {'T1 decay':<27} {d_ler[0]:.4f} ± {d_ler[1]:.4f}")
    print(
        f"    {'Pauli twirl':<27} {t_ler[0]:.4f} ± {t_ler[1]:.4f}   "
        f"twirl / decay {t_ler[0] / d_ler[0]:.3f} (z {z_score(t_ler, d_ler):+.1f})"
    )

    print(f"\n{'=' * 86}")

    out_plot = plot_path or os.environ.get("DIRECTIONAL_CODE_PLOT")
    if out_plot:
        save_figure(out_plot, noisy, d_dets, t_dets)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[1])
    parser.add_argument(
        "--plot", help="optional path to save a summary figure (requires matplotlib)"
    )
    main(plot_path=parser.parse_args().plot)
View complete output
======================================================================================
  Directional codes: the rotated N2E3N2 code [[48,12,4]] with iSWAP gates
======================================================================================

1. The code
  rotated N2E3N2, d=4: [[48,12]] on 96 qubits
  torus v1=(-6, 8), v2=(6, 8)
  stabilisers of weight 7, 7 CPSWAP layers a round, 4 rounds
  192 detectors and 12 observables, all deterministic

2. The iSWAP circuit with SI1000(p=0.001)
  operations: R×240  H×1728  S_DAG×2688  ISWAP×1344  M×240
  noise:      DEPOLARIZE1×8064  DEPOLARIZE2×1344  X_ERROR×240, and M(p) flips

3. Pauli noise: Maestro's Pauli frames against Stim
  detection rate, 100,000 shots each:
    Maestro 0.07756 ± 0.00013
    Stim    0.07770 ± 0.00013   ratio 0.9982, z -0.78

4. T1 decay (gamma=0.0005) against its Pauli twirl, decoded alike with BP-OSD
  detection rate:
                                   shots       first round        all rounds
    T1 decay, shot by shot         3,000   0.0771 ± 0.0016   0.1177 ± 0.0009
    Pauli twirl, Pauli frames    100,000   0.0805 ± 0.0003   0.1193 ± 0.0001
    twirl / decay                          1.044 (z +2.0)    1.013 (z +1.8)
  logical error, any of the 12 observables, BP-OSD on 1,000 shots each:
    T1 decay                    0.3040 ± 0.0146
    Pauli twirl                 0.3250 ± 0.0148   twirl / decay 1.069 (z +1.0)

======================================================================================