API reference

Clifford Noise Reduction (CliNR) in Stim.

An implementation of the scheme of [1] in eight modules: protocol builds the CliNR circuits, those of its variant CZNR for circuits of CZ gates, and the direct baseline; checks draws the stabilizer checks they measure; accounting counts the operations of the built circuits, bounds turns those counts into analytic bounds on the logical error rate and the gate overhead; estimators measures the same quantities by Monte Carlo; first_order computes them exactly to first order in the error rates; circuits supplies random Clifford circuits; and noise_models holds the error rates.

The modules are the namespace: clinr.bounds.plog_bound, not a re-export from clinr.

References

[1]

N. Delfosse and E. Tham, “Low-cost noise reduction for Clifford circuits”, arXiv:2407.06583 (2024).

clinr.protocol

Construction of the CliNR and CZNR circuits and the direct baseline.

build_clinr_tr() builds CliNR_{t,r}(C) of [1], Sec. III: C is split into t chunks, and each chunk is applied by gate teleportation through its own resource state, guarded by r stabilizer checks that the caller supplies (clinr.checks.draw_checks() draws them). All r checks of a chunk are measured before its resource is accepted or discarded, where the paper restarts at the first nontrivial outcome; the two accept the same shots. build_direct() builds the baseline, C applied directly, and build_cznr_tr() builds CZNR_{t,r}(C), the variant of [1], App. E, for circuits of CZ gates, with n resource qubits per chunk. All three carry a Choi harness that reads out whether the implemented channel is C, and all three are exact at zero noise: every detector and observable is deterministic.

Register layout of build_clinr_tr(), 4n + 1 qubits, or 4n without checks:

b1  [0,   n)     data input of the first chunk
b2  [n,  2n)     resource half the data is teleported against
b3  [2n, 3n)     resource half carrying the chunk
ref [3n, 4n)     Choi reference, noiseless apparatus
anc 4n           ancilla for the check gadget

After each chunk, b1 and b3 exchange roles by relabeling, with no gates, so the output ends on b3 when t is odd and on b1 when t is even. build_cznr_tr() has 3n + 1 qubits, or 3n without checks: the data [0, n), the graph state [n, 2n), the reference [2n, 3n) and the ancilla 3n, with the data and graph-state blocks exchanging roles after each chunk.

Noise follows a clinr.noise_models.NoiseModel: DEPOLARIZE1 at p1 after single-qubit gates, DEPOLARIZE2 at p2 after two-qubit gates, a flipped outcome at p_m for each measurement, and at p_prep an X_ERROR after R or a Z_ERROR after RX. Idle qubits and the Choi harness are noiseless.

Three modeling choices depart from [1], Sec. II, and the analytic bounds count them as such:

  1. By default |+> is a reset followed by a Hadamard, two fault locations where the paper charges one; native_plus=True prepares it with one RX, as the paper does.

  2. A preparation error is a flip with probability p_prep, where the paper’s depolarizing error flips a fresh preparation with probability 2p/3.

  3. The Pauli correction Q of Eq. (1) is never applied: it is tracked as a Pauli frame and folded into the observables, so the circuit implements C up to that frame and Q is not a fault location, where the paper applies and charges it after every chunk.

References

[1] (1,2,3)

N. Delfosse and E. Tham, “Low-cost noise reduction for Clifford circuits”, arXiv:2407.06583 (2024).

clinr.protocol.gate_list(circuit: Circuit) → list[tuple[str, list[int]]]

Return the gates of circuit, one (name, targets) per gate.

REPEAT blocks are unrolled and fused instructions are split by the gate’s arity. Identity gates and annotations (instructions with no effect on the state, no measurement record and no error) are dropped, since neither is a fault location.

Parameters:
circuitstim.Circuit

A circuit of single- and two-qubit unitary gates on qubit targets, possibly with annotations.

Returns:
list of tuple of (str, list of int)

The gates in order.

Raises:
TypeError

If circuit is not a stim.Circuit.

ValueError

If an instruction is a noise channel, a measurement or a reset, if a unitary acts on more than two qubits, or if a gate has a target other than a qubit.

clinr.protocol.stabilizer_gens(tableau: Tableau, bare: list[int], image: list[int], total: int) → list[PauliString]

Return generators of the stabilizer group of the resource state.

With n = len(tableau), the resource is n Bell pairs joining bare[i] to image[i], with the Clifford C of tableau applied to image. Its stabilizer group is generated by X_{bare[i]} (C X_i C^dag)_{image} and Z_{bare[i]} (C Z_i C^dag)_{image} for i in range(n).

Parameters:
tableaustim.Tableau

Tableau of C, on at least one qubit. A tableau taken from a circuit is only as wide as the highest qubit the circuit touches, so pad the circuit first (the chunks of chunk_circuit() are).

barelist of int

The n indices of the half C does not act on.

imagelist of int

The n indices of the half carrying C.

totalint

Length of the returned Pauli strings. Every index in bare and image must lie in [0, total), and no index may repeat.

Returns:
list of stim.PauliString

2n independent, pairwise commuting generators, ordered X-type then Z-type for each pair in turn, each with the sign under which it stabilizes the resource.

Raises:
TypeError

If total is not an integer.

ValueError

If tableau acts on no qubits, if bare or image does not hold len(tableau) indices, or if the indices repeat or fall outside [0, total).

clinr.protocol.chunk_circuit(circuit: Circuit, n: int, t: int) → list[Circuit]

Split circuit into t contiguous chunks.

The gates of gate_list() are cut in order into t pieces, the first s mod t of size ceil(s/t) and the rest of size floor(s/t), as in arXiv:2407.06583, Sec. III. When t exceeds the gate count s the surplus chunks are empty.

Parameters:
circuitstim.Circuit

The Clifford circuit C, as accepted by gate_list(), on qubits [0, n).

nint

Number of data qubits. Must be at least 1.

tint

Number of chunks. Must be at least 1.

Returns:
list of stim.Circuit

t chunks whose gates, concatenated, are gate_list() of circuit. Each begins with an identity on all n qubits, so its tableau is n wide.

Raises:
TypeError

If circuit is not a stim.Circuit or n or t is not an integer.

ValueError

If n < 1, t < 1, or circuit acts on a qubit index of n or more.

clinr.protocol.build_clinr_tr(circuit: Circuit, n: int, checks: list[list[PauliString]], noise: NoiseModel, *, noisy_checks: bool = True, native_plus: bool = False) → Circuit

Build CliNR_{t,r}(C) with the Choi harness.

The chunks are those of chunk_circuit() with t = len(checks). The teleportation byproduct is tracked as a Pauli frame and folded into the observables, so the circuit needs no feedback. t = 1 is the circuit of Lemma 1 of arXiv:2407.06583.

Parameters:
circuitstim.Circuit

The Clifford circuit C, as accepted by gate_list(), on qubits [0, n).

nint

Number of data qubits. Must be at least 1.

checkslist of list of stim.PauliString

One list of r checks per chunk, the same r for every chunk, laid out as clinr.checks.draw_checks() returns them: length 2n, the bare half on [0, n) and the half carrying the chunk on [n, 2n). Each must be a stabilizer of its chunk’s resource state; the identity is allowed. There must be at least one chunk.

noiseNoiseModel
noisy_checksbool, optional

If True, measure each check with the noisy ancilla gadget; if False, with the same gadget without noise, so that the checks detect faults but cause none.

native_plusbool, optional

If True, prepare every |+> with one RX, as in arXiv:2407.06583, Sec. II, so that a weight-w check costs w + 3 locations rather than w + 4. If False, |+> is R then H.

Returns:
stim.Circuit

On 4n + 1 qubits, or 4n without checks, with one detector per check in chunk order and 2n observables, the Choi stabilizers of C; exact at zero noise. Every noise channel is tagged with the region it belongs to in chunk k, counted from 0, as clinr.accounting divides it: prep/k for the preparation of the resource, gates/k for the chunk’s gates, check/k/j for its j-th check, and teleport/k for the teleportation.

Raises:
TypeError

If circuit is not a stim.Circuit, n is not an integer, noise is not a clinr.noise_models.NoiseModel, or checks is not a list of lists of stim.PauliString.

ValueError

If n < 1, if checks holds no chunks, if circuit is not as gate_list() accepts or acts on a qubit index of n or more, if the chunks have different numbers of checks, or if a check does not have length 2n or does not stabilize its chunk’s resource state with its sign.

clinr.protocol.build_direct(circuit: Circuit, n: int, noise: NoiseModel) → Circuit

Build the direct implementation of C with the Choi harness.

C is applied to b1 with circuit-level noise, with no resource state, teleportation or checks.

Parameters:
circuitstim.Circuit

The Clifford circuit C, as accepted by gate_list(), on qubits [0, n).

nint

Number of data qubits. Must be at least 1.

noiseNoiseModel
Returns:
stim.Circuit

On 4n qubits, b1 and ref, with no detectors and 2n observables, the Choi stabilizers of C; exact at zero noise. Every noise channel is tagged gates/0.

Raises:
TypeError

If circuit is not a stim.Circuit, n is not an integer, or noise is not a clinr.noise_models.NoiseModel.

ValueError

If n < 1, if circuit is not as gate_list() accepts, or if it acts on a qubit index of n or more.

clinr.protocol.require_cz_only(circuit: Circuit) → None

Raise unless every gate of circuit is a CZ, as CZNR requires.

Parameters:
circuitstim.Circuit
Raises:
ValueError

If circuit has a gate other than CZ, naming the others.

clinr.protocol.graph_state_gens(tableau: Tableau) → list[PauliString]

Return generators of the stabilizer group of a graph state.

For the unitary U_G of a circuit of CZ gates, the graph state U_G |+>^n is stabilized by U_G X_i U_G^dag = X_i prod_j Z_j, the product over the neighbors j of i in the graph G whose edges are the CZ gates taken with odd multiplicity.

Parameters:
tableaustim.Tableau

Tableau of U_G, on at least one qubit, padded to its full width as for stabilizer_gens().

Returns:
list of stim.PauliString

The n generators, in qubit order, on n qubits, each with the sign under which it stabilizes the graph state.

Raises:
ValueError

If tableau acts on no qubits, or is not the tableau of a circuit of CZ gates: one that fixes every Z_i and takes each X_i to X_i times a product of Z_j with j != i.

clinr.protocol.build_cznr_tr(circuit: Circuit, n: int, checks: list[list[PauliString]], noise: NoiseModel, *, noisy_checks: bool = True, native_plus: bool = False) → Circuit

Build CZNR_{t,r}(C) with the Choi harness.

This is the variant of arXiv:2407.06583, App. E. C must consist of CZ gates. Each chunk C_k is applied by one-bit teleportation through its graph state: n resource qubits are prepared in |+> and the chunk’s gates applied to them; the checks are measured; then each data qubit i takes a CX from resource qubit i and is measured, which leaves the chunk’s output on the resource qubits up to the Pauli U_{G_k} X_i U_{G_k}^dag for each nontrivial outcome. As in build_clinr_tr(), that correction is tracked as a Pauli frame and folded into the observables, all r checks of an attempt are measured, and the Choi harness is noiseless.

Register layout, 3n + 1 qubits, or 3n without checks: the first chunk’s data on [0, n), its resource on [n, 2n), the Choi reference on [2n, 3n) and the check ancilla at 3n. After each chunk the data and resource blocks exchange roles by relabeling.

Parameters:
circuitstim.Circuit

The circuit C, of CZ gates only, as accepted by chunk_circuit(), on qubits [0, n).

nint

Number of data qubits. Must be at least 1.

checkslist of list of stim.PauliString

One list of r checks per chunk, the same r for every chunk, as clinr.checks.draw_cznr_checks() returns them: length n, each a stabilizer of its chunk’s graph state; the identity is allowed. There must be at least one chunk.

noiseNoiseModel
noisy_checksbool, optional

As in build_clinr_tr().

native_plusbool, optional

As in build_clinr_tr().

Returns:
stim.Circuit

On 3n + 1 qubits, or 3n without checks, with one detector per check in chunk order and 2n observables, the Choi stabilizers of C; exact at zero noise. Every noise channel is tagged with its region in chunk k: prep/k for the |+> of the resource, gates/k for the chunk’s gates, check/k/j for its j-th check, and teleport/k for the teleportation.

Raises:
TypeError

As in build_clinr_tr().

ValueError

If n < 1, if checks holds no chunks, if circuit has a gate other than CZ or acts on a qubit of index n or more, if the chunks have different numbers of checks, or if a check does not have length n or does not stabilize its chunk’s graph state with its sign.

clinr.checks

Choosing which stabilizers of a chunk’s resource state to measure.

The r checks of a chunk are drawn independently and identically, with replacement, from one of two families: the full stabilizer group, identity included, whose elements have weight at most 2n, as the proof of Theorem 1 of [1] assumes; or the restricted family of [1], Sec. V, the 3n stabilizers propagated from the Bell pairs, whose weight is at most n + 1. clinr.protocol measures the checks and clinr.bounds prices what each family detects. For CZNR, the variant for circuits of CZ gates, the checks are drawn from the full stabilizer group of a graph state, as Appendix E of [1] assumes.

References

[1] (1,2,3)

N. Delfosse and E. Tham, “Low-cost noise reduction for Clifford circuits”, arXiv:2407.06583 (2024).

clinr.checks.restricted_family(tableau: Tableau, bare: list[int], image: list[int], total: int) → list[PauliString]

Return the restricted check family of arXiv:2407.06583, Sec. V.

With n = len(tableau), the family is the images of the Bell stabilizers XX, ZZ and YY of each pair under I ⊗ C, in that order, pair by pair. The third of each triple is the product of the first two, with the sign under which it stabilizes the resource.

Parameters:
tableau, bare, image, total

As in clinr.protocol.stabilizer_gens().

Returns:
list of stim.PauliString

3n stabilizers of the resource state, none the identity, each of weight 1 on bare and at most n on image.

clinr.checks.draw_checks(circuit: Circuit, n: int, t: int, r: int, rng: Generator, *, restricted_checks: bool = False) → list[list[PauliString]]

Draw r checks for each of the t chunks of circuit.

The r checks of a chunk are drawn independently and identically, with replacement, the convention of arXiv:2407.06583, App. B, so a check may be drawn twice.

Parameters:
circuitstim.Circuit

The Clifford circuit C, as accepted by clinr.protocol.chunk_circuit(), on qubits [0, n).

nint

Number of data qubits. Must be at least 1.

tint

Number of chunks. Must be at least 1.

rint

Number of checks per chunk. Must be non-negative.

rngnumpy.random.Generator

Source of randomness, drawn from in chunk order.

restricted_checksbool, optional

If True, draw uniformly from restricted_family(). If False, draw uniformly from the full stabilizer group, identity included: each generator of clinr.protocol.stabilizer_gens() enters the product with probability 1/2.

Returns:
list of list of stim.PauliString

t lists of r checks, in chunk order, as clinr.protocol.build_clinr_tr() takes them: length 2n, the bare half on [0, n) and the half carrying the chunk on [n, 2n).

Raises:
TypeError

If rng is not a numpy.random.Generator, circuit is not a stim.Circuit, or n, t or r is not an integer.

ValueError

If r is negative, or as clinr.protocol.chunk_circuit() raises for circuit, n and t.

clinr.checks.draw_cznr_checks(circuit: Circuit, n: int, t: int, r: int, rng: Generator) → list[list[PauliString]]

Draw r checks for each of the t chunks of a CZ circuit.

The checks are drawn independently and uniformly, with replacement, from the stabilizer group of each chunk’s graph state (clinr.protocol.graph_state_gens()), identity included: each generator enters the product with probability 1/2.

Parameters:
circuitstim.Circuit

The circuit C, of CZ gates only, on qubits [0, n).

n, t, r, rng

As in draw_checks().

Returns:
list of list of stim.PauliString

t lists of r checks, in chunk order, of length n, as clinr.protocol.build_cznr_tr() takes them.

Raises:
TypeError

As in draw_checks().

ValueError

If r is negative, if circuit has a gate other than CZ, or as clinr.protocol.chunk_circuit() raises for circuit, n and t.

clinr.accounting

Operation counts for the circuits clinr.protocol builds.

A Region counts the operations of one part of a built circuit by kind. clinr.bounds turns a region into a fault probability and clinr.estimators into an operation count, so both read the same numbers for the same circuit.

Per chunk the protocol of [1] has four regions: the resource preparation, the chunk’s own gates, its checks, and the teleportation after the last check. CZNR, its variant for circuits of CZ gates ([1], App. E), has the same four, with a smaller preparation and teleportation. A Scheme holds the two that differ.

References

[1] (1,2)

N. Delfosse and E. Tham, “Low-cost noise reduction for Clifford circuits”, arXiv:2407.06583 (2024).

class clinr.accounting.Region(n1: int, n2: int, nm: int, n_prep: int)

Operation counts for one region of a built circuit.

Parameters:
n1int

Single-qubit gates.

n2int

Two-qubit gates.

nmint

Measurements.

n_prepint

Preparations.

clinr.accounting.ZERO = (0, 0, 0, 0)

The empty region, which add() returns for no regions.

clinr.accounting.gate_counts(circuit: Circuit) → tuple[int, int]

Return (s1, s2), the numbers of single- and two-qubit gates.

Parameters:
circuitstim.Circuit

As accepted by clinr.protocol.gate_list(), whose gates are the ones counted.

Returns:
tuple of (int, int)
clinr.accounting.add(*regions: Region) → Region

Return the elementwise sum of regions, or ZERO if none.

clinr.accounting.prep_region(n: int, native_plus: bool) → Region

Return the region of one resource preparation of n Bell pairs.

The region has 2n preparations and n CX either way, plus n Hadamards unless native_plus is true, in which case |+> is one RX rather than R then H.

Parameters:
nint

Number of Bell pairs. Must be at least 1.

native_plusbool
Returns:
Region
Raises:
TypeError

If n is not an integer.

ValueError

If n < 1.

clinr.accounting.check_region(count: int, weight: int, native_plus: bool) → Region

Return the region of count checks of total weight weight.

A weight-w check is one preparation, two Hadamards (one under native_plus), w controlled Paulis and one measurement: w + 4 operations, or w + 3. The count is the same whether or not the checks are noisy; noiseless checks merely have no fault locations.

Parameters:
countint

Number of checks. Must be non-negative.

weightint

Their total weight. Must be non-negative.

native_plusbool
Returns:
Region
Raises:
TypeError

If count or weight is not an integer.

ValueError

If count or weight is negative.

clinr.accounting.teleport_region(n: int) → Region

Return the region of the teleportation after a chunk’s last check.

n CX, n Hadamards and 2n measurements: the 4n of the paper’s 5n that remain when the Pauli correction is tracked classically (arXiv:2407.06583, proof of Lemma 1).

Parameters:
nint

Number of data qubits. Must be at least 1.

Returns:
Region
Raises:
TypeError

If n is not an integer.

ValueError

If n < 1.

clinr.accounting.cznr_prep_region(n: int, native_plus: bool) → Region

Return the region of one graph-state preparation’s |+> states.

n preparations, plus n Hadamards unless native_plus. The graph state’s CZ gates are the chunk’s own and are counted with it.

Parameters:
nint

Number of qubits of the graph state. Must be at least 1.

native_plusbool
Returns:
Region
Raises:
TypeError

If n is not an integer.

ValueError

If n < 1.

clinr.accounting.cznr_teleport_region(n: int) → Region

Return the region of CZNR’s one-bit teleportation of n qubits.

n CX and n measurements: the 2n of the paper’s 3n (arXiv:2407.06583, App. E) that remain when the Pauli correction is tracked classically.

Parameters:
nint

Number of data qubits. Must be at least 1.

Returns:
Region
Raises:
TypeError

If n is not an integer.

ValueError

If n < 1.

class clinr.accounting.Scheme(prep: Region, teleport: Region)

The regions a scheme adds around each chunk: CliNR’s or CZNR’s.

Parameters:
prepRegion

The resource preparation, the same for every chunk.

teleportRegion

The teleportation after a chunk’s last check.

prep: Region

Alias for field number 0

teleport: Region

Alias for field number 1

clinr.accounting.clinr_scheme(n: int, native_plus: bool) → Scheme

Return CliNR’s regions on n data qubits.

The regions are those of prep_region() and teleport_region().

Parameters:
nint

Number of data qubits. Must be at least 1.

native_plusbool
Returns:
Scheme
clinr.accounting.cznr_scheme(n: int, native_plus: bool) → Scheme

Return CZNR’s regions on n data qubits.

The regions are those of cznr_prep_region() and cznr_teleport_region().

Parameters:
nint

Number of data qubits. Must be at least 1.

native_plusbool
Returns:
Scheme
clinr.accounting.protected_region(prep: Region, s1: int, s2: int, checks: Region) → Region

Return the region of one attempt at a chunk, through its last check.

Parameters:
prepRegion

The resource preparation, from prep_region() or cznr_prep_region().

s1int

Single-qubit gates in the chunk. Must be non-negative.

s2int

Two-qubit gates in the chunk. Must be non-negative.

checksRegion

All of the chunk’s checks, from check_region().

Returns:
Region
Raises:
TypeError

If s1 or s2 is not an integer.

ValueError

If s1 or s2 is negative.

clinr.accounting.expected_overhead(counts: list[tuple[int, int]], scheme: Scheme, check_regions: list[Region], acceptance: list[float]) → float

Return the expected number of operations per gate of the circuit.

Every attempt at chunk k runs all of its checks, so it costs the m_k operations of its protected_region(), and the number of attempts is geometric with mean 1 / q_k. Each chunk also pays its teleportation once. This is Eq. (B4) of arXiv:2407.06583 with the acceptance q_k in place of 1 - p_res and the scheme’s teleportation, 4n for CliNR, in place of 5n. The total is divided by the number of gates across the chunks.

Parameters:
countslist of tuple of (int, int)

(s1, s2) for each chunk, in chunk order, not all zero.

schemeScheme

The preparation and teleportation of every chunk, from clinr_scheme() or cznr_scheme().

check_regionslist of Region

Each chunk’s checks, in chunk order.

acceptancelist of float

Each chunk’s acceptance probability q_k, in chunk order, in [0, 1]. Analytic bounds and measured frequencies are both accepted; the result is a bound or an estimate accordingly.

Returns:
float

The expected overhead, or math.inf if any q_k is zero.

Raises:
TypeError

If a gate count is not an integer.

ValueError

If counts, check_regions and acceptance differ in length, if a gate count or an operation count of a region is negative, if the chunks hold no gates, or if an acceptance probability lies outside [0, 1].

clinr.bounds

Analytic bounds on the logical error rate and gate overhead of CliNR.

plog_bound() and overhead_bound() rederive Theorem 1 of [1] for the circuits clinr.protocol builds, and choose_tr() picks (t, r), or the direct implementation, by them. The bounds are deterministic.

They differ from Theorem 1 mostly in what they count:

  • four rates, one per kind of operation (clinr.accounting), where the paper has one;

  • the exact size of each chunk, where the paper charges every chunk the largest;

  • 4n operations to finish a teleportation, where the paper’s 5n includes applying the Pauli correction, which is tracked here instead (2n for CZNR, where the paper has 3n);

  • the probability that r checks all miss a damaging fault, and the sum over gadgets of the probability that a fault arising in one escapes every later check, for whichever family clinr.checks.draw_checks() draws from, where the paper has 2^-r and 2 for the full group;

  • no conditioning on acceptance when r == 0, since every attempt is then accepted.

cznr_plog_bound() and cznr_overhead_bound() do the same for CZNR, rederiving Theorem 3 of [1] with the same departures.

References

[1] (1,2)

N. Delfosse and E. Tham, “Low-cost noise reduction for Clifford circuits”, arXiv:2407.06583 (2024).

class clinr.bounds.ChunkTerms(resource: float, check: float, teleport: float, acceptance: float, checks: int, per_check_miss: float)

The terms of one chunk’s bound on the logical error rate, r >= 1.

The chunk’s bound is (resource * miss + check * escapes + teleport) / acceptance, with miss = q**r and escapes = 1 + q + ... + q**(r - 1) for q the per-check miss.

Parameters:
resourcefloat

Probability that some operation of the resource faults.

checkfloat

Probability that some operation of one check gadget faults, at the family’s worst-case weight; 0 for noiseless checks.

teleportfloat

Probability that some operation of the teleportation faults.

acceptancefloat

Probability that no operation of the protected region faults, a lower bound on the chunk’s acceptance.

checksint

The number of checks r.

per_check_missfloat

The worst-case probability q that one check misses a damaging fault: 1/2 for uniform checks, 1 - 2/(3n) for restricted ones.

resource: float

Alias for field number 0

check: float

Alias for field number 1

teleport: float

Alias for field number 2

acceptance: float

Alias for field number 3

checks: int

Alias for field number 4

per_check_miss: float

Alias for field number 5

property miss: float

The worst-case probability that all r checks miss.

property escapes: float

The sum over gadgets of the probability that later checks miss.

property bound: float

The chunk’s bound, infinite if no attempt can be accepted.

clinr.bounds.direct_plog_bound(circuit: Circuit, noise: NoiseModel) → float

Bound the logical error rate of the direct implementation of a circuit.

The probability that some gate of circuit faults, the paper’s g_p(s) with one rate per kind of gate. A logical error needs a fault, so this is an upper bound, and nearly exact to first order: a single fault in a Clifford circuit leaves a nontrivial Pauli on its output.

Parameters:
circuitstim.Circuit

The Clifford circuit C, as accepted by clinr.accounting.gate_counts().

noiseNoiseModel
Returns:
float

An upper bound on the logical error rate of the circuit that clinr.protocol.build_direct() builds.

Raises:
TypeError

If circuit is not a stim.Circuit or noise is not a clinr.noise_models.NoiseModel.

ValueError

If circuit is not as clinr.protocol.gate_list() accepts.

clinr.bounds.plog_bound(circuit: Circuit, n: int, t: int, r: int, noise: NoiseModel, *, noisy_checks: bool = True, restricted_checks: bool = False, native_plus: bool = False) → float

Bound the logical error rate of CliNR_{t,r} applied to circuit.

The sum over chunks of the bound of Lemma 1 of arXiv:2407.06583, Eq. (B1), with each chunk counted exactly, where Theorem 1 multiplies the largest chunk’s bound by t.

Parameters:
circuitstim.Circuit

The Clifford circuit C, as accepted by clinr.protocol.chunk_circuit(), on qubits [0, n).

nint

Number of data qubits. Must be at least 1.

tint

Number of chunks. Must be at least 1.

rint

Number of checks per chunk. Must be non-negative.

noiseNoiseModel
noisy_checksbool, optional

If True, charge each check the fault locations of the ancilla gadget; if False, none, as for noisy_checks in clinr.protocol.build_clinr_tr(). The checks’ operations count toward the overhead either way.

restricted_checksbool, optional

If True, price draws from clinr.checks.restricted_family(); if False, from the full stabilizer group.

native_plusbool, optional

If True, price |+> as one preparation, as in clinr.protocol.build_clinr_tr().

Returns:
float

An upper bound on the logical error rate of the circuit that clinr.protocol.build_clinr_tr() builds with the same options, averaged over the checks clinr.checks.draw_checks() draws. Not clipped to [0, 1], and infinite when some chunk with checks can never be accepted. With r == 0 it is the probability that some operation outside the checks faults, since no attempt is rejected.

Raises:
TypeError

If circuit is not a stim.Circuit, n, t or r is not an integer, or noise is not a clinr.noise_models.NoiseModel.

ValueError

If n < 1, r < 0, t < 1, or circuit is not as clinr.protocol.gate_list() accepts or acts on a qubit index of n or more.

clinr.bounds.plog_terms(circuit: Circuit, n: int, t: int, r: int, noise: NoiseModel, *, noisy_checks: bool = True, restricted_checks: bool = False, native_plus: bool = False) → list[ChunkTerms]

Return the terms of plog_bound(), one entry per chunk.

plog_bound() is the sum of the entries’ ChunkTerms.bound. Without checks the bound is a single fault probability, with no terms.

Parameters:
circuit, n, t, noise, noisy_checks, restricted_checks, native_plus

As in plog_bound().

rint

Number of checks per chunk. Must be at least 1.

Returns:
list of ChunkTerms

The terms of each chunk, in chunk order.

Raises:
TypeError

If circuit is not a stim.Circuit, n, t or r is not an integer, or noise is not a clinr.noise_models.NoiseModel.

ValueError

If n < 1, r < 1, t < 1, or circuit is not as clinr.protocol.gate_list() accepts or acts on a qubit index of n or more.

clinr.bounds.overhead_bound(circuit: Circuit, n: int, t: int, r: int, noise: NoiseModel, *, noisy_checks: bool = True, restricted_checks: bool = False, native_plus: bool = False) → float

Bound the gate overhead of CliNR_{t,r} applied to circuit.

clinr.accounting.expected_overhead() with every check at its family’s worst-case weight and each chunk’s acceptance probability replaced by the probability that nothing in its protected region faults, which is at most the true acceptance. With r == 0 no attempt is rejected, so the acceptance is 1 and the value is exact.

Parameters:
circuitstim.Circuit

The Clifford circuit C, as accepted by clinr.protocol.chunk_circuit(), on qubits [0, n), with at least one gate.

n, t, r, noise, noisy_checks, restricted_checks, native_plus

As in plog_bound().

Returns:
float

An upper bound on the expected number of operations per gate of circuit, infinite when some chunk with checks can never be accepted.

Raises:
TypeError

If circuit is not a stim.Circuit, n, t or r is not an integer, or noise is not a clinr.noise_models.NoiseModel.

ValueError

If n < 1, r < 0, t < 1, if circuit is not as clinr.protocol.gate_list() accepts or acts on a qubit index of n or more, or if the chunks hold no gates.

clinr.bounds.choose_tr(circuit: Circuit, n: int, noise: NoiseModel, *, max_overhead: float, r_max: int, t_max: int | None = None, noisy_checks: bool = True, restricted_checks: bool = False, native_plus: bool = False) → tuple[int, int] | None

Return the implementation with the least logical error rate bound.

The candidates are the direct implementation, whose bound is the probability that one of the gates of circuit faults and whose overhead is 1, and every CliNR_{t,r} with 1 <= t <= t_max and 0 <= r <= r_max whose overhead bound is at most max_overhead. Ties go to the direct implementation, then to the smaller t, then to the smaller r.

Parameters:
circuitstim.Circuit

The Clifford circuit C, as accepted by clinr.protocol.chunk_circuit(), on qubits [0, n), with at least one gate.

nint

Number of data qubits. Must be at least 1.

noiseNoiseModel
max_overheadfloat

Largest acceptable overhead bound. Must be at least 1, the overhead of the direct implementation.

r_maxint

Largest number of checks per chunk to try. Must be non-negative.

t_maxint, optional

Largest number of chunks to try, at least 1. Defaults to the gate count of circuit, beyond which chunks are empty and only add cost.

noisy_checks, restricted_checks, native_plusbool, optional

As in plog_bound(), applied to both bounds.

Returns:
tuple of (int, int) or None

(t, r), or None when the direct implementation’s bound is the least. A result with r == r_max may mean the cap binds.

Raises:
TypeError

If circuit is not a stim.Circuit, n, r_max or t_max is not an integer, max_overhead is not a number, or noise is not a clinr.noise_models.NoiseModel.

ValueError

If n < 1, r_max < 0, t_max < 1, max_overhead is less than 1, or circuit has no gates, is not as clinr.protocol.gate_list() accepts, or acts on a qubit index of n or more.

clinr.bounds.cznr_plog_bound(circuit: Circuit, n: int, t: int, r: int, noise: NoiseModel, *, noisy_checks: bool = True, native_plus: bool = False) → float

Bound the logical error rate of CZNR_{t,r} applied to circuit.

The bound of plog_bound(), with CZNR’s regions in place of CliNR’s: Theorem 3 of arXiv:2407.06583 with the same departures from the paper as plog_bound()’s from Theorem 1. A check drawn uniformly from the graph state’s stabilizer group misses a damaging fault with probability 1/2 and weighs at most n.

Parameters:
circuitstim.Circuit

The circuit C, of CZ gates only, on qubits [0, n).

n, t, r, noise, noisy_checks, native_plus

As in plog_bound().

Returns:
float

An upper bound on the logical error rate of the circuit that clinr.protocol.build_cznr_tr() builds with the same options, averaged over the checks clinr.checks.draw_cznr_checks() draws, as for plog_bound().

Raises:
TypeError

If circuit is not a stim.Circuit, n, t or r is not an integer, or noise is not a clinr.noise_models.NoiseModel.

ValueError

If n < 1, r < 0, t < 1, or circuit has a gate other than CZ or acts on a qubit index of n or more.

clinr.bounds.cznr_overhead_bound(circuit: Circuit, n: int, t: int, r: int, noise: NoiseModel, *, noisy_checks: bool = True, native_plus: bool = False) → float

Bound the gate overhead of CZNR_{t,r} applied to circuit.

overhead_bound() with CZNR’s regions and the checks of cznr_plog_bound().

Parameters:
circuitstim.Circuit

The circuit C, of CZ gates only, on qubits [0, n), with at least one gate.

n, t, r, noise, noisy_checks, native_plus

As in cznr_plog_bound().

Returns:
float

An upper bound on the expected number of operations per gate of circuit, infinite when some chunk with checks can never be accepted.

Raises:
TypeError

If circuit is not a stim.Circuit, n, t or r is not an integer, or noise is not a clinr.noise_models.NoiseModel.

ValueError

If n < 1, r < 0, t < 1, if circuit has a gate other than CZ or acts on a qubit index of n or more, or if the chunks hold no gates.

clinr.estimators

Monte Carlo estimates of CliNR, CZNR and the direct implementation.

estimate_clinr(), estimate_cznr() and estimate_direct() sample the circuits clinr.protocol builds and return an Estimate of raw counts, from which the point estimates, their intervals and the measured gate overhead are all computed, so a sweep never has to be rerun for another statistic.

A CliNR shot is accepted when every check of every chunk passes, and the logical error rate is taken over accepted shots. This conditioning gives the output distribution of the protocol of [1], which re-prepares a rejected resource offline and never lets a failed attempt touch the data; the cost of re-preparation appears in gate_overhead() instead.

One estimate is one draw of the checks, and its shots share those checks. logical_error_rate(), gate_overhead_over_draws() and design_effect() treat draws, not shots, as the unit of observation. The protocol draws new checks for every attempt, which the first two estimate by default from the same draws; they also give the rates with one check set kept for every attempt.

estimate_clinr_given() and estimate_cznr_given() sample the same circuits with checks the caller chooses. Such an estimate is not a draw, so those three reject it; its interval is Estimate.interval() and its gate overhead gate_overhead().

References

[1]

N. Delfosse and E. Tham, “Low-cost noise reduction for Clifford circuits”, arXiv:2407.06583 (2024).

clinr.estimators.wilson_interval(errors: int, trials: int, confidence: float = 0.95) → tuple[float, float, float]

Return (point, lo, hi), a Wilson score interval for a proportion.

Parameters:
errorsint

Number of errors, the events whose proportion is estimated. Must be between 0 and trials.

trialsint

Number of independent trials. Must be non-negative.

confidencefloat, optional

Confidence level, strictly between 0 and 1.

Returns:
tuple of (float, float, float)

The point estimate errors / trials and the interval’s bounds, which lie in [0, 1]. With no trials the point estimate is nan and the interval is (0, 1).

Raises:
TypeError

If errors or trials is not an integer.

ValueError

If trials or errors is negative, if errors exceeds trials, or if confidence is not strictly between 0 and 1.

class clinr.estimators.Estimate(shots: int, accepted: int, errors: int, s1: int, s2: int, n: int, chunk_accepted: tuple[int, ...] = (), chunk_checks: tuple[int, ...] = (), chunk_weight: tuple[int, ...] = (), chunk_counts: tuple[tuple[int, int], ...] = (), noisy_checks: bool = True, restricted_checks: bool = False, native_plus: bool = False, cznr: bool = False, given_checks: bool = False)

Counts from one Monte Carlo run on one circuit.

The four per-chunk tuples have one length: the number of chunks, or zero for the direct implementation. All counts are non-negative.

Parameters:
shotsint

Shots sampled. Must be positive.

acceptedint

Shots in which every check passed, at most shots.

errorsint

Accepted shots with a nontrivial output error, at most accepted.

s1, s2int

Single- and two-qubit gate counts of the circuit.

nint

Number of data qubits. Must be at least 1.

chunk_acceptedtuple of int, optional

For each chunk, in order, the shots its own checks accepted: between accepted and shots. A chunk without checks accepts every shot.

chunk_checkstuple of int, optional

Checks measured in each chunk.

chunk_weighttuple of int, optional

Total weight of each chunk’s checks: at most its number of checks times the family’s worst-case weight, n if cznr, n + 1 if restricted_checks and 2n otherwise, and at least its number of checks if restricted_checks, since that family excludes the identity.

chunk_countstuple of tuple of (int, int), optional

Gate counts (s1, s2) of each chunk, summing to (s1, s2).

noisy_checks, restricted_checks, native_plusbool, optional

The options the circuit was built and its checks drawn with, as in estimate_clinr(). The direct implementation keeps the defaults.

cznrbool, optional

True for an estimate of CZNR (estimate_cznr()), whose checks are drawn uniformly, so restricted_checks is then False.

given_checksbool, optional

True for an estimate with checks the caller chose (estimate_clinr_given(), estimate_cznr_given()), which belong to no family, so restricted_checks is then False, and whose weights are bounded as the uniform family’s are.

Raises:
TypeError

If a count is not an integer or an option is not a bool.

ValueError

If any of the constraints above fails.

property size: int

Gate count of the circuit.

property acceptance: float

Fraction of shots in which every check passed.

property p_log: float

Logical error rate among accepted shots; nan if none.

interval(confidence: float = 0.95) → tuple[float, float, float]

Return wilson_interval() of errors in accepted.

For CliNR or CZNR, the interval is for the rate given this estimate’s checks, not for the protocol’s rate over draws of them, which logical_error_rate() estimates.

clinr.estimators.estimate_clinr(circuit: Circuit, n: int, t: int, r: int, noise: NoiseModel, shots: int, rng: Generator, *, noisy_checks: bool = True, restricted_checks: bool = False, native_plus: bool = False) → Estimate

Sample CliNR_{t,r} applied to circuit under fresh checks.

The checks are drawn by clinr.checks.draw_checks() and the circuit built by clinr.protocol.build_clinr_tr(). rng supplies the draws and then seeds Stim’s sampler, so one generator drives the whole estimate.

Parameters:
circuit, n, t, r

As in clinr.checks.draw_checks().

noiseNoiseModel
shotsint

Shots to sample. Must be positive.

rngnumpy.random.Generator

Source of randomness.

noisy_checks, native_plusbool, optional

As in clinr.protocol.build_clinr_tr().

restricted_checksbool, optional

As in clinr.checks.draw_checks().

Returns:
Estimate

With one entry per chunk in each per-chunk tuple.

Raises:
TypeError

If rng is not a numpy.random.Generator, shots is not an integer, or noise is not a clinr.noise_models.NoiseModel; or as the functions it calls raise for the other arguments.

ValueError

If shots is not positive, or as the functions it calls raise for the other arguments.

clinr.estimators.estimate_clinr_given(circuit: Circuit, n: int, checks: list[list[PauliString]], noise: NoiseModel, shots: int, rng: Generator, *, noisy_checks: bool = True, native_plus: bool = False) → Estimate

Sample CliNR_{t,r} applied to circuit with the given checks.

The circuit is built by clinr.protocol.build_clinr_tr() from checks, with t = len(checks); rng seeds Stim’s sampler.

Parameters:
circuit, n, checks

As in clinr.protocol.build_clinr_tr().

noiseNoiseModel
shotsint

Shots to sample. Must be positive.

rngnumpy.random.Generator

Source of randomness.

noisy_checks, native_plusbool, optional

As in clinr.protocol.build_clinr_tr().

Returns:
Estimate

With given_checks set and one entry per chunk in each per-chunk tuple.

Raises:
TypeError

If rng is not a numpy.random.Generator, shots is not an integer, or noise is not a clinr.noise_models.NoiseModel; or as the functions it calls raise for the other arguments.

ValueError

If shots is not positive, or as the functions it calls raise for the other arguments.

clinr.estimators.estimate_cznr(circuit: Circuit, n: int, t: int, r: int, noise: NoiseModel, shots: int, rng: Generator, *, noisy_checks: bool = True, native_plus: bool = False) → Estimate

Sample CZNR_{t,r} applied to a CZ circuit under fresh checks.

estimate_clinr() for CZNR: the checks are drawn by clinr.checks.draw_cznr_checks() and the circuit built by clinr.protocol.build_cznr_tr().

Parameters:
circuitstim.Circuit

The circuit C, of CZ gates only, on qubits [0, n).

n, t, r, noise, shots, rng

As in estimate_clinr().

noisy_checks, native_plusbool, optional

As in clinr.protocol.build_cznr_tr().

Returns:
Estimate

With cznr set, and one entry per chunk in each per-chunk tuple.

Raises:
TypeError

If rng is not a numpy.random.Generator, shots is not an integer, or noise is not a clinr.noise_models.NoiseModel; or as the functions it calls raise for the other arguments.

ValueError

If shots is not positive, or as the functions it calls raise for the other arguments.

clinr.estimators.estimate_cznr_given(circuit: Circuit, n: int, checks: list[list[PauliString]], noise: NoiseModel, shots: int, rng: Generator, *, noisy_checks: bool = True, native_plus: bool = False) → Estimate

Sample CZNR_{t,r} applied to circuit with the given checks.

The circuit is built by clinr.protocol.build_cznr_tr() from checks, with t = len(checks); rng seeds Stim’s sampler.

Parameters:
circuit, n, checks

As in clinr.protocol.build_cznr_tr().

noiseNoiseModel
shotsint

Shots to sample. Must be positive.

rngnumpy.random.Generator

Source of randomness.

noisy_checks, native_plusbool, optional

As in clinr.protocol.build_cznr_tr().

Returns:
Estimate

With cznr and given_checks set and one entry per chunk in each per-chunk tuple.

Raises:
TypeError

If rng is not a numpy.random.Generator, shots is not an integer, or noise is not a clinr.noise_models.NoiseModel; or as the functions it calls raise for the other arguments.

ValueError

If shots is not positive, or as the functions it calls raise for the other arguments.

clinr.estimators.estimate_direct(circuit: Circuit, n: int, noise: NoiseModel, shots: int, rng: Generator) → Estimate

Sample the direct implementation of circuit.

The circuit is built by clinr.protocol.build_direct(); rng seeds Stim’s sampler.

Parameters:
circuit, n

As in clinr.protocol.build_direct().

noiseNoiseModel
shotsint

Shots to sample. Must be positive.

rngnumpy.random.Generator

Source of randomness.

Returns:
Estimate

With every shot accepted and empty per-chunk tuples.

Raises:
TypeError

If rng is not a numpy.random.Generator, shots is not an integer, or noise is not a clinr.noise_models.NoiseModel; or as the functions it calls raise for the other arguments.

ValueError

If shots is not positive, or as the functions it calls raise for the other arguments.

clinr.estimators.sweep_clinr(circuits: list[Circuit], n: int, t: int, r: int, noise: NoiseModel, shots: int, rng: Generator, *, noisy_checks: bool = True, restricted_checks: bool = False, native_plus: bool = False) → list[Estimate]

Return estimate_clinr() of each of circuits, in order.

One generator is threaded through the sweep, so the circuits’ checks and shots are drawn independently. Every other argument is as in estimate_clinr().

Raises:
ValueError

If circuits is empty.

clinr.estimators.sweep_direct(circuits: list[Circuit], n: int, noise: NoiseModel, shots: int, rng: Generator) → list[Estimate]

Return estimate_direct() of each of circuits, in order.

One generator is threaded through the sweep, so the circuits’ shots are drawn independently. Every other argument is as in estimate_direct().

Raises:
ValueError

If circuits is empty.

clinr.estimators.gate_overhead(estimate: Estimate) → float

Return the gate overhead measured by estimate.

clinr.accounting.expected_overhead(), as in clinr.bounds.overhead_bound(), but with each chunk’s checks at the weight actually drawn and its acceptance probability the fraction of shots its checks accepted. Every attempt runs all of a chunk’s checks, so that fraction is the only estimated quantity; everything else is read from estimate.

Parameters:
estimateEstimate

From estimate_clinr(), estimate_cznr() or their _given forms, with at least one gate and every chunk accepting at least one shot.

Returns:
float
Raises:
ValueError

If estimate has no chunks or a chunk accepted no shots.

clinr.estimators.logical_error_rate(estimates: list[Estimate], confidence: float = 0.95, *, checks: Literal['fresh', 'kept'] = 'fresh') → tuple[float, float, float]

Return (point, lo, hi) for the logical error rate over draws.

With checks="fresh", the rate of the protocol of arXiv:2407.06583, Sec. III, which draws new checks for every attempt. Check sets that accept more often are then over-represented among accepted attempts, so the point estimate is the mean over draws of the fraction of shots accepted with an error, over the mean of the fraction accepted. With checks="kept", the rate with one check set kept for every attempt, averaged over check sets: the mean of the per-draw rates. Each draw counts equally, whatever its number of shots.

The draws are independent clusters of correlated shots, so the interval is the Korn-Graubard interval for a proportion from a clustered sample (Korn and Graubard, Survey Methodology 24, 193 (1998)), as the NCHS data presentation standards for proportions specify it. The variance of the point estimate is estimated over the draws by the delta method, so it counts the spread between draws as well as shot noise. Dividing the binomial variance at the point estimate by it gives an effective number of shots, scaled by the ratio of the Student t quantiles at the shots’ and the draws’ degrees of freedom, and capped at the shots accepted. The interval is the Clopper-Pearson interval at that effective number. When the variance carries no information, at a point estimate of 0 or 1 or with draws that do not differ, the effective number is the shots accepted.

Parameters:
estimateslist of Estimate

Draws for one setting: the same gate counts, checks per chunk, n and options. With checks="kept" each must have accepted a shot; with "fresh", at least one.

confidencefloat, optional

Confidence level, strictly between 0 and 1.

checks{“fresh”, “kept”}, optional

Whether the checks are redrawn for every attempt or kept.

Returns:
tuple of (float, float, float)

With a single draw the bounds are nan.

Raises:
ValueError

If estimates is empty, holds an estimate with given checks, or its entries disagree in gate counts, checks per chunk, n or options; if they accepted too few shots, as above; if confidence is not strictly between 0 and 1; or if checks is neither "fresh" nor "kept".

clinr.estimators.gate_overhead_over_draws(estimates: list[Estimate], confidence: float = 0.95, *, checks: Literal['fresh', 'kept'] = 'fresh') → tuple[float, float, float]

Return (point, lo, hi) for the gate overhead over draws.

With checks="fresh", the overhead of the protocol of arXiv:2407.06583, Sec. III, which draws new checks for every attempt: its attempts are then independent and identically distributed, so by Wald’s identity each chunk costs its teleportation plus the mean over draws of its protected region’s operations, divided by the mean over draws of its acceptance. With checks="kept", the mean over draws of gate_overhead(), each draw’s checks kept for every attempt. Each draw counts equally, whatever its number of shots. The interval is as in logical_error_rate(), without the clamp.

Parameters:
estimateslist of Estimate

Draws as in logical_error_rate(), of CliNR or CZNR rather than the direct implementation. With checks="kept" every chunk of each must have accepted a shot; with "fresh", every chunk of at least one.

confidencefloat, optional

Confidence level, strictly between 0 and 1.

checks{“fresh”, “kept”}, optional

Whether the checks are redrawn for every attempt or kept.

Returns:
tuple of (float, float, float)

With a single draw the bounds are nan.

Raises:
ValueError

On the conditions of logical_error_rate() other than those on accepted shots, if an estimate has no chunks, or if the chunks accepted too few shots, as above.

clinr.estimators.design_effect(estimates: list[Estimate]) → float

Return the between-draw variance over the mean within-draw variance.

The within-draw variance of a draw is the binomial p (1 - p) / a at its rate p and accepted count a. A value near 1 means the draws vary no more than independent shots would, so a Wilson interval on the pooled shots is honest; above 1, an interval over draws is wider than the pooled one by about the square root of the value.

Parameters:
estimateslist of Estimate

At least two draws, as in logical_error_rate() with checks="kept".

Returns:
float
Raises:
ValueError

If estimates fails the conditions of logical_error_rate() with checks="kept", if fewer than two are given, or if every draw’s rate is 0 or 1, which makes the within-draw variance zero.

Notes

When errors are rare, few draws see any, and the ratio is noisy.

clinr.first_order

First-order analysis of the circuits clinr.protocol builds.

A fault here is one outcome of one noise channel at one location: one of the three Paulis of a DEPOLARIZE1, one of the fifteen of a DEPOLARIZE2, the flip of an X_ERROR or Z_ERROR, or the flipped outcome of a noisy measurement. faults() lists every fault of a built circuit that flips some detector or some observable, with its probability, the region its channel is tagged with, and its effect, as Stim’s explanation of the circuit’s detector error model reports them. Faults that flip nothing are harmless and left out.

To first order in the error rates, at most one fault occurs per shot, so the logical error rate is the total probability of the faults that flip an observable and no detector (logical_error_rate()), and the rejection rate that of the faults that flip a detector. The estimators of clinr.estimators measure the same quantities to all orders by sampling; the first-order values are exact for one draw of the checks, attribute every contribution to a region, and cost one pass over the circuit.

class clinr.first_order.Fault(tag: str, instruction: int, probability: float, logical: bool, detected: bool)

One fault of a circuit with an effect on its detectors or observables.

Parameters:
tagstr

The tag of the noise channel, which names its region (see clinr.protocol.build_clinr_tr()).

instructionint

Index of the channel’s instruction in the circuit, so faults sort in time order.

probabilityfloat

Probability of this fault.

logicalbool

Whether it flips some observable.

detectedbool

Whether it flips some detector.

tag: str

Alias for field number 0

instruction: int

Alias for field number 1

probability: float

Alias for field number 2

logical: bool

Alias for field number 3

detected: bool

Alias for field number 4

clinr.first_order.faults(circuit: Circuit) → list[Fault]

Return every fault of circuit that flips a detector or observable.

Parameters:
circuitstim.Circuit

A circuit built by clinr.protocol, or any circuit without REPEAT blocks whose noise channels are DEPOLARIZE1, DEPOLARIZE2, X_ERROR, Z_ERROR or noisy M, and whose detectors and observables are deterministic without noise.

Returns:
list of Fault

One entry per fault with an effect, ordered by instruction.

Raises:
ValueError

If circuit has a REPEAT block or another noise channel.

clinr.first_order.logical_error_rate(found: list[Fault]) → float

Return the first-order logical error rate of a list of faults.

Parameters:
foundlist of Fault

Faults, as faults() returns them, or any subset of them, such as those of one region.

Returns:
float

The total probability of the faults that flip an observable and no detector: the logical error rate to first order in the error rates, accepted or not, since the two differ only at second order.

clinr.circuits

Random Clifford circuits to protect.

random_gate_sequence() draws gates uniformly from {H, S, CX}, the construction of [1], App. D, and is reproducible from a NumPy generator. random_clifford() samples a uniformly random Clifford [2] and synthesizes it over {H, S, CX}, the construction of [1], Sec. V; Stim’s sampler takes no seed, so these circuits are not reproducible, and save_circuits() and load_circuits() keep a generated set.

References

[1] (1,2)

N. Delfosse and E. Tham, “Low-cost noise reduction for Clifford circuits”, arXiv:2407.06583 (2024).

[2]

S. Bravyi and D. Maslov, “Hadamard-free circuits expose the structure of the Clifford group”, arXiv:2003.09412 (2020).

clinr.circuits.random_gate_sequence(n: int, size: int, rng: Generator) → Circuit

Return size gates drawn uniformly from {H, S, CX}.

Each gate is H, S or CX with equal probability (H or S when n = 1); a single-qubit gate acts on a uniformly random qubit, and a CX on a uniformly random ordered pair of distinct qubits. This is the construction of arXiv:2407.06583, App. D.

Parameters:
nint

Number of qubits. Must be at least 1.

sizeint

Number of gates. Must be non-negative.

rngnumpy.random.Generator

Source of randomness.

Returns:
stim.Circuit

The gates in order. Qubits no gate touches are left implicit, so num_qubits may be less than n.

Raises:
TypeError

If rng is not a numpy.random.Generator, or n or size is not an integer.

ValueError

If n < 1 or size < 0.

Notes

The same generator state gives the same circuit within one NumPy version; NumPy does not promise identical streams across versions.

clinr.circuits.random_clifford(n: int) → Circuit

Return a uniformly random n-qubit Clifford over {H, S, CX}.

The Clifford is sampled by Stim’s implementation of Bravyi and Maslov’s algorithm, as in arXiv:2407.06583, Sec. V, and synthesized by Gaussian elimination into O(n^2) gates.

Parameters:
nint

Number of qubits. Must be at least 1.

Returns:
stim.Circuit
Raises:
TypeError

If n is not an integer.

ValueError

If n < 1.

Notes

Not reproducible: Stim’s sampler takes no seed, and Stim documents its synthesis as unstable across versions and possibly randomized. Keep a generated set with save_circuits() for anything that must be rerun.

clinr.circuits.random_cliffords(n: int, count: int) → list[Circuit]

Return count independent random_clifford() circuits.

Parameters:
nint

Number of qubits. Must be at least 1.

countint

Number of circuits. Must be at least 1.

Returns:
list of stim.Circuit
Raises:
TypeError

If n or count is not an integer.

ValueError

If n < 1 or count < 1.

clinr.circuits.save_circuits(circuits: list[Circuit], path: str | Path) → None

Write circuits to path, replacing any existing file.

The file is a JSON list of Stim circuit texts, in order, encoded as UTF-8.

Parameters:
circuitslist of stim.Circuit

Must not be empty.

pathstr or pathlib.Path
Raises:
TypeError

If an element of circuits is not a stim.Circuit.

ValueError

If circuits is empty.

clinr.circuits.load_circuits(path: str | Path) → list[Circuit]

Return the circuits written to path by save_circuits().

Parameters:
pathstr or pathlib.Path
Returns:
list of stim.Circuit

In the order they were saved.

clinr.noise_models

Circuit-level noise models.

A NoiseModel holds the four error rates that clinr.protocol builds noisy circuits with and clinr.bounds prices fault locations against. uniform_noise() and asymmetric_noise() give the two regimes of [1]: one rate for every operation, and two-qubit gates noisier than the rest.

References

[1]

N. Delfosse and E. Tham, “Low-cost noise reduction for Clifford circuits”, arXiv:2407.06583 (2024).

class clinr.noise_models.NoiseModel(p1: float, p2: float, p_m: float, p_prep: float)

Four circuit-level error rates.

Idle qubits are noiseless: the model has no idle rate.

Parameters:
p1float

Depolarizing rate after each single-qubit gate, in [0, 1].

p2float

Depolarizing rate after each two-qubit gate, in [0, 1].

p_mfloat

Probability that a measurement outcome is flipped, in [0, 1].

p_prepfloat

Probability that a preparation lands in the orthogonal state, in [0, 1].

Raises:
TypeError

If a rate is not a number.

ValueError

If any rate lies outside [0, 1].

clinr.noise_models.uniform_noise(p: float) → NoiseModel

Return the model with every rate equal to p.

This is the single-rate model of arXiv:2407.06583, Sec. II, under which Theorem 1 is stated.

Parameters:
pfloat

Error rate of every operation, in [0, 1].

Returns:
NoiseModel
Raises:
TypeError

If p is not a number.

ValueError

If p lies outside [0, 1].

clinr.noise_models.asymmetric_noise(p2: float, ratio: float = 10.0) → NoiseModel

Return the model with two-qubit gates ratio times noisier.

Every operation other than a two-qubit gate gets rate p2 / ratio. The default ratio=10 is the regime of the numerics in arXiv:2407.06583, Sec. V, which also puts noise on idle qubits; this model has none.

Parameters:
p2float

Depolarizing rate after each two-qubit gate, in [0, 1].

ratiofloat, optional

How many times noisier two-qubit gates are than every other operation. Must be positive, and at least p2.

Returns:
NoiseModel
Raises:
TypeError

If p2 or ratio is not a number.

ValueError

If p2 lies outside [0, 1], if ratio is not positive, or if p2 / ratio exceeds 1.