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¶
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:
By default
|+>is a reset followed by a Hadamard, two fault locations where the paper charges one;native_plus=Trueprepares it with oneRX, as the paper does.A preparation error is a flip with probability
p_prep, where the paper’s depolarizing error flips a fresh preparation with probability2p/3.The Pauli correction
Qof Eq. (1) is never applied: it is tracked as a Pauli frame and folded into the observables, so the circuit implementsCup to that frame andQis not a fault location, where the paper applies and charges it after every chunk.
References¶
- clinr.protocol.gate_list(circuit: Circuit) list[tuple[str, list[int]]]¶
Return the gates of
circuit, one(name, targets)per gate.REPEATblocks 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
circuitis not astim.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 isnBell pairs joiningbare[i]toimage[i], with the CliffordCoftableauapplied toimage. Its stabilizer group is generated byX_{bare[i]} (C X_i C^dag)_{image}andZ_{bare[i]} (C Z_i C^dag)_{image}foriinrange(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 ofchunk_circuit()are).- barelist of int
The
nindices of the halfCdoes not act on.- imagelist of int
The
nindices of the half carryingC.- totalint
Length of the returned Pauli strings. Every index in
bareandimagemust lie in[0, total), and no index may repeat.
- Returns:
- list of stim.PauliString
2nindependent, pairwise commuting generators, orderedX-type thenZ-type for each pair in turn, each with the sign under which it stabilizes the resource.
- Raises:
- TypeError
If
totalis not an integer.- ValueError
If
tableauacts on no qubits, ifbareorimagedoes not holdlen(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
circuitintotcontiguous chunks.The gates of
gate_list()are cut in order intotpieces, the firsts mod tof sizeceil(s/t)and the rest of sizefloor(s/t), as in arXiv:2407.06583, Sec. III. Whentexceeds the gate countsthe surplus chunks are empty.- Parameters:
- circuitstim.Circuit
The Clifford circuit
C, as accepted bygate_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
tchunks whose gates, concatenated, aregate_list()ofcircuit. Each begins with an identity on allnqubits, so its tableau isnwide.
- Raises:
- TypeError
If
circuitis not astim.Circuitornortis not an integer.- ValueError
If
n < 1,t < 1, orcircuitacts on a qubit index ofnor 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()witht = len(checks). The teleportation byproduct is tracked as a Pauli frame and folded into the observables, so the circuit needs no feedback.t = 1is the circuit of Lemma 1 of arXiv:2407.06583.- Parameters:
- circuitstim.Circuit
The Clifford circuit
C, as accepted bygate_list(), on qubits[0, n).- nint
Number of data qubits. Must be at least 1.
- checkslist of list of stim.PauliString
One list of
rchecks per chunk, the samerfor every chunk, laid out asclinr.checks.draw_checks()returns them: length2n, 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 oneRX, as in arXiv:2407.06583, Sec. II, so that a weight-wcheck costsw + 3locations rather thanw + 4. If False,|+>isRthenH.
- Returns:
- stim.Circuit
On
4n + 1qubits, or4nwithout checks, with one detector per check in chunk order and2nobservables, the Choi stabilizers ofC; exact at zero noise. Every noise channel is tagged with the region it belongs to in chunkk, counted from 0, asclinr.accountingdivides it:prep/kfor the preparation of the resource,gates/kfor the chunk’s gates,check/k/jfor itsj-th check, andteleport/kfor the teleportation.
- Raises:
- TypeError
If
circuitis not astim.Circuit,nis not an integer,noiseis not aclinr.noise_models.NoiseModel, orchecksis not a list of lists ofstim.PauliString.- ValueError
If
n < 1, ifchecksholds no chunks, ifcircuitis not asgate_list()accepts or acts on a qubit index ofnor more, if the chunks have different numbers of checks, or if a check does not have length2nor 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
Cwith the Choi harness.Cis applied tob1with circuit-level noise, with no resource state, teleportation or checks.- Parameters:
- circuitstim.Circuit
The Clifford circuit
C, as accepted bygate_list(), on qubits[0, n).- nint
Number of data qubits. Must be at least 1.
- noiseNoiseModel
- Returns:
- stim.Circuit
On
4nqubits,b1andref, with no detectors and2nobservables, the Choi stabilizers ofC; exact at zero noise. Every noise channel is taggedgates/0.
- Raises:
- TypeError
If
circuitis not astim.Circuit,nis not an integer, ornoiseis not aclinr.noise_models.NoiseModel.- ValueError
If
n < 1, ifcircuitis not asgate_list()accepts, or if it acts on a qubit index ofnor more.
- clinr.protocol.require_cz_only(circuit: Circuit) None¶
Raise unless every gate of
circuitis aCZ, as CZNR requires.- Parameters:
- circuitstim.Circuit
- Raises:
- ValueError
If
circuithas a gate other thanCZ, 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_Gof a circuit ofCZgates, the graph stateU_G |+>^nis stabilized byU_G X_i U_G^dag = X_i prod_j Z_j, the product over the neighborsjofiin the graphGwhose edges are theCZgates taken with odd multiplicity.- Parameters:
- tableaustim.Tableau
Tableau of
U_G, on at least one qubit, padded to its full width as forstabilizer_gens().
- Returns:
- list of stim.PauliString
The
ngenerators, in qubit order, onnqubits, each with the sign under which it stabilizes the graph state.
- Raises:
- ValueError
If
tableauacts on no qubits, or is not the tableau of a circuit ofCZgates: one that fixes everyZ_iand takes eachX_itoX_itimes a product ofZ_jwithj != 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.
Cmust consist ofCZgates. Each chunkC_kis applied by one-bit teleportation through its graph state:nresource qubits are prepared in|+>and the chunk’s gates applied to them; the checks are measured; then each data qubititakes aCXfrom resource qubitiand is measured, which leaves the chunk’s output on the resource qubits up to the PauliU_{G_k} X_i U_{G_k}^dagfor each nontrivial outcome. As inbuild_clinr_tr(), that correction is tracked as a Pauli frame and folded into the observables, allrchecks of an attempt are measured, and the Choi harness is noiseless.Register layout,
3n + 1qubits, or3nwithout checks: the first chunk’s data on[0, n), its resource on[n, 2n), the Choi reference on[2n, 3n)and the check ancilla at3n. After each chunk the data and resource blocks exchange roles by relabeling.- Parameters:
- circuitstim.Circuit
The circuit
C, ofCZgates only, as accepted bychunk_circuit(), on qubits[0, n).- nint
Number of data qubits. Must be at least 1.
- checkslist of list of stim.PauliString
One list of
rchecks per chunk, the samerfor every chunk, asclinr.checks.draw_cznr_checks()returns them: lengthn, 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 + 1qubits, or3nwithout checks, with one detector per check in chunk order and2nobservables, the Choi stabilizers ofC; exact at zero noise. Every noise channel is tagged with its region in chunkk:prep/kfor the|+>of the resource,gates/kfor the chunk’s gates,check/k/jfor itsj-th check, andteleport/kfor the teleportation.
- Raises:
- TypeError
As in
build_clinr_tr().- ValueError
If
n < 1, ifchecksholds no chunks, ifcircuithas a gate other thanCZor acts on a qubit of indexnor more, if the chunks have different numbers of checks, or if a check does not have lengthnor 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¶
- 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 stabilizersXX,ZZandYYof each pair underI ⊗ 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
- Returns:
- list of stim.PauliString
3nstabilizers of the resource state, none the identity, each of weight 1 onbareand at mostnonimage.
- clinr.checks.draw_checks(circuit: Circuit, n: int, t: int, r: int, rng: Generator, *, restricted_checks: bool = False) list[list[PauliString]]¶
Draw
rchecks for each of thetchunks ofcircuit.The
rchecks 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 byclinr.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 ofclinr.protocol.stabilizer_gens()enters the product with probability 1/2.
- Returns:
- list of list of stim.PauliString
tlists ofrchecks, in chunk order, asclinr.protocol.build_clinr_tr()takes them: length2n, the bare half on[0, n)and the half carrying the chunk on[n, 2n).
- Raises:
- TypeError
If
rngis not anumpy.random.Generator,circuitis not astim.Circuit, orn,torris not an integer.- ValueError
If
ris negative, or asclinr.protocol.chunk_circuit()raises forcircuit,nandt.
- clinr.checks.draw_cznr_checks(circuit: Circuit, n: int, t: int, r: int, rng: Generator) list[list[PauliString]]¶
Draw
rchecks for each of thetchunks of aCZcircuit.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, ofCZgates only, on qubits[0, n).- n, t, r, rng
As in
draw_checks().
- Returns:
- list of list of stim.PauliString
tlists ofrchecks, in chunk order, of lengthn, asclinr.protocol.build_cznr_tr()takes them.
- Raises:
- TypeError
As in
draw_checks().- ValueError
If
ris negative, ifcircuithas a gate other thanCZ, or asclinr.protocol.chunk_circuit()raises forcircuit,nandt.
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¶
- 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.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, orZEROif none.
- clinr.accounting.prep_region(n: int, native_plus: bool) Region¶
Return the region of one resource preparation of
nBell pairs.The region has
2npreparations andnCXeither way, plusnHadamards unlessnative_plusis true, in which case|+>is oneRXrather thanRthenH.- Parameters:
- nint
Number of Bell pairs. Must be at least 1.
- native_plusbool
- Returns:
- Region
- Raises:
- TypeError
If
nis not an integer.- ValueError
If
n < 1.
- clinr.accounting.check_region(count: int, weight: int, native_plus: bool) Region¶
Return the region of
countchecks of total weightweight.A weight-
wcheck is one preparation, two Hadamards (one undernative_plus),wcontrolled Paulis and one measurement:w + 4operations, orw + 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
countorweightis not an integer.- ValueError
If
countorweightis negative.
- clinr.accounting.teleport_region(n: int) Region¶
Return the region of the teleportation after a chunk’s last check.
nCX,nHadamards and2nmeasurements: the4nof the paper’s5nthat 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
nis 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.npreparations, plusnHadamards unlessnative_plus. The graph state’sCZgates 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
nis 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
nqubits.nCXandnmeasurements: the2nof the paper’s3n(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
nis 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.
- clinr.accounting.clinr_scheme(n: int, native_plus: bool) Scheme¶
Return CliNR’s regions on
ndata qubits.The regions are those of
prep_region()andteleport_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
ndata qubits.The regions are those of
cznr_prep_region()andcznr_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()orcznr_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
s1ors2is not an integer.- ValueError
If
s1ors2is 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
kruns all of its checks, so it costs them_koperations of itsprotected_region(), and the number of attempts is geometric with mean1 / q_k. Each chunk also pays its teleportation once. This is Eq. (B4) of arXiv:2407.06583 with the acceptanceq_kin place of1 - p_resand the scheme’s teleportation,4nfor CliNR, in place of5n. 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()orcznr_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.infif anyq_kis zero.
- Raises:
- TypeError
If a gate count is not an integer.
- ValueError
If
counts,check_regionsandacceptancediffer 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;
4noperations to finish a teleportation, where the paper’s5nincludes applying the Pauli correction, which is tracked here instead (2nfor CZNR, where the paper has3n);the probability that
rchecks 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 familyclinr.checks.draw_checks()draws from, where the paper has2^-rand2for 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¶
- 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, withmiss = q**randescapes = 1 + q + ... + q**(r - 1)forqthe 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
qthat one check misses a damaging fault:1/2for uniform checks,1 - 2/(3n)for restricted ones.
- 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
circuitfaults, the paper’sg_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 byclinr.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
circuitis not astim.Circuitornoiseis not aclinr.noise_models.NoiseModel.- ValueError
If
circuitis not asclinr.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 tocircuit.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 byclinr.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_checksinclinr.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 inclinr.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 checksclinr.checks.draw_checks()draws. Not clipped to [0, 1], and infinite when some chunk with checks can never be accepted. Withr == 0it is the probability that some operation outside the checks faults, since no attempt is rejected.
- Raises:
- TypeError
If
circuitis not astim.Circuit,n,torris not an integer, ornoiseis not aclinr.noise_models.NoiseModel.- ValueError
If
n < 1,r < 0,t < 1, orcircuitis not asclinr.protocol.gate_list()accepts or acts on a qubit index ofnor 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
circuitis not astim.Circuit,n,torris not an integer, ornoiseis not aclinr.noise_models.NoiseModel.- ValueError
If
n < 1,r < 1,t < 1, orcircuitis not asclinr.protocol.gate_list()accepts or acts on a qubit index ofnor 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 tocircuit.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. Withr == 0no attempt is rejected, so the acceptance is 1 and the value is exact.- Parameters:
- circuitstim.Circuit
The Clifford circuit
C, as accepted byclinr.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
circuitis not astim.Circuit,n,torris not an integer, ornoiseis not aclinr.noise_models.NoiseModel.- ValueError
If
n < 1,r < 0,t < 1, ifcircuitis not asclinr.protocol.gate_list()accepts or acts on a qubit index ofnor 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
circuitfaults and whose overhead is 1, and everyCliNR_{t,r}with1 <= t <= t_maxand0 <= r <= r_maxwhose overhead bound is at mostmax_overhead. Ties go to the direct implementation, then to the smallert, then to the smallerr.- Parameters:
- circuitstim.Circuit
The Clifford circuit
C, as accepted byclinr.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), orNonewhen the direct implementation’s bound is the least. A result withr == r_maxmay mean the cap binds.
- Raises:
- TypeError
If
circuitis not astim.Circuit,n,r_maxort_maxis not an integer,max_overheadis not a number, ornoiseis not aclinr.noise_models.NoiseModel.- ValueError
If
n < 1,r_max < 0,t_max < 1,max_overheadis less than 1, orcircuithas no gates, is not asclinr.protocol.gate_list()accepts, or acts on a qubit index ofnor 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 tocircuit.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 asplog_bound()’s from Theorem 1. A check drawn uniformly from the graph state’s stabilizer group misses a damaging fault with probability1/2and weighs at mostn.- Parameters:
- circuitstim.Circuit
The circuit
C, ofCZgates 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 checksclinr.checks.draw_cznr_checks()draws, as forplog_bound().
- Raises:
- TypeError
If
circuitis not astim.Circuit,n,torris not an integer, ornoiseis not aclinr.noise_models.NoiseModel.- ValueError
If
n < 1,r < 0,t < 1, orcircuithas a gate other thanCZor acts on a qubit index ofnor 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 tocircuit.overhead_bound()with CZNR’s regions and the checks ofcznr_plog_bound().- Parameters:
- circuitstim.Circuit
The circuit
C, ofCZgates 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
circuitis not astim.Circuit,n,torris not an integer, ornoiseis not aclinr.noise_models.NoiseModel.- ValueError
If
n < 1,r < 0,t < 1, ifcircuithas a gate other thanCZor acts on a qubit index ofnor 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¶
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 / trialsand the interval’s bounds, which lie in [0, 1]. With no trials the point estimate isnanand the interval is(0, 1).
- Raises:
- TypeError
If
errorsortrialsis not an integer.- ValueError
If
trialsorerrorsis negative, iferrorsexceedstrials, or ifconfidenceis 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
acceptedandshots. 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,
nifcznr,n + 1ifrestricted_checksand2notherwise, and at least its number of checks ifrestricted_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, sorestricted_checksis 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, sorestricted_checksis 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.
- interval(confidence: float = 0.95) tuple[float, float, float]¶
Return
wilson_interval()oferrorsinaccepted.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 tocircuitunder fresh checks.The checks are drawn by
clinr.checks.draw_checks()and the circuit built byclinr.protocol.build_clinr_tr().rngsupplies 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
- restricted_checksbool, optional
As in
clinr.checks.draw_checks().
- Returns:
- Estimate
With one entry per chunk in each per-chunk tuple.
- Raises:
- TypeError
If
rngis not anumpy.random.Generator,shotsis not an integer, ornoiseis not aclinr.noise_models.NoiseModel; or as the functions it calls raise for the other arguments.- ValueError
If
shotsis 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 tocircuitwith the given checks.The circuit is built by
clinr.protocol.build_clinr_tr()fromchecks, witht = len(checks);rngseeds Stim’s sampler.- Parameters:
- circuit, n, checks
- noiseNoiseModel
- shotsint
Shots to sample. Must be positive.
- rngnumpy.random.Generator
Source of randomness.
- noisy_checks, native_plusbool, optional
- Returns:
- Estimate
With
given_checksset and one entry per chunk in each per-chunk tuple.
- Raises:
- TypeError
If
rngis not anumpy.random.Generator,shotsis not an integer, ornoiseis not aclinr.noise_models.NoiseModel; or as the functions it calls raise for the other arguments.- ValueError
If
shotsis 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 aCZcircuit under fresh checks.estimate_clinr()for CZNR: the checks are drawn byclinr.checks.draw_cznr_checks()and the circuit built byclinr.protocol.build_cznr_tr().- Parameters:
- circuitstim.Circuit
The circuit
C, ofCZgates only, on qubits[0, n).- n, t, r, noise, shots, rng
As in
estimate_clinr().- noisy_checks, native_plusbool, optional
- Returns:
- Estimate
With
cznrset, and one entry per chunk in each per-chunk tuple.
- Raises:
- TypeError
If
rngis not anumpy.random.Generator,shotsis not an integer, ornoiseis not aclinr.noise_models.NoiseModel; or as the functions it calls raise for the other arguments.- ValueError
If
shotsis 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 tocircuitwith the given checks.The circuit is built by
clinr.protocol.build_cznr_tr()fromchecks, witht = len(checks);rngseeds Stim’s sampler.- Parameters:
- circuit, n, checks
- noiseNoiseModel
- shotsint
Shots to sample. Must be positive.
- rngnumpy.random.Generator
Source of randomness.
- noisy_checks, native_plusbool, optional
- Returns:
- Estimate
With
cznrandgiven_checksset and one entry per chunk in each per-chunk tuple.
- Raises:
- TypeError
If
rngis not anumpy.random.Generator,shotsis not an integer, ornoiseis not aclinr.noise_models.NoiseModel; or as the functions it calls raise for the other arguments.- ValueError
If
shotsis 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();rngseeds Stim’s sampler.- Parameters:
- circuit, n
- 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
rngis not anumpy.random.Generator,shotsis not an integer, ornoiseis not aclinr.noise_models.NoiseModel; or as the functions it calls raise for the other arguments.- ValueError
If
shotsis 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 ofcircuits, 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
circuitsis empty.
- clinr.estimators.sweep_direct(circuits: list[Circuit], n: int, noise: NoiseModel, shots: int, rng: Generator) list[Estimate]¶
Return
estimate_direct()of each ofcircuits, 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
circuitsis empty.
- clinr.estimators.gate_overhead(estimate: Estimate) float¶
Return the gate overhead measured by
estimate.clinr.accounting.expected_overhead(), as inclinr.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 fromestimate.- Parameters:
- estimateEstimate
From
estimate_clinr(),estimate_cznr()or their_givenforms, with at least one gate and every chunk accepting at least one shot.
- Returns:
- float
- Raises:
- ValueError
If
estimatehas 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. Withchecks="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,
nand options. Withchecks="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
estimatesis empty, holds an estimate with given checks, or its entries disagree in gate counts, checks per chunk,nor options; if they accepted too few shots, as above; ifconfidenceis not strictly between 0 and 1; or ifchecksis 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. Withchecks="kept", the mean over draws ofgate_overhead(), each draw’s checks kept for every attempt. Each draw counts equally, whatever its number of shots. The interval is as inlogical_error_rate(), without the clamp.- Parameters:
- estimateslist of Estimate
Draws as in
logical_error_rate(), of CliNR or CZNR rather than the direct implementation. Withchecks="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) / aat its ratepand accepted counta. 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()withchecks="kept".
- Returns:
- float
- Raises:
- ValueError
If
estimatesfails the conditions oflogical_error_rate()withchecks="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.
- clinr.first_order.faults(circuit: Circuit) list[Fault]¶
Return every fault of
circuitthat flips a detector or observable.- Parameters:
- circuitstim.Circuit
A circuit built by
clinr.protocol, or any circuit withoutREPEATblocks whose noise channels areDEPOLARIZE1,DEPOLARIZE2,X_ERROR,Z_ERRORor noisyM, 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
circuithas aREPEATblock 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¶
- clinr.circuits.random_gate_sequence(n: int, size: int, rng: Generator) Circuit¶
Return
sizegates drawn uniformly from{H, S, CX}.Each gate is
H,SorCXwith equal probability (HorSwhenn = 1); a single-qubit gate acts on a uniformly random qubit, and aCXon 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_qubitsmay be less thann.
- Raises:
- TypeError
If
rngis not anumpy.random.Generator, ornorsizeis not an integer.- ValueError
If
n < 1orsize < 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
nis 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
countindependentrandom_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
norcountis not an integer.- ValueError
If
n < 1orcount < 1.
- clinr.circuits.save_circuits(circuits: list[Circuit], path: str | Path) None¶
Write
circuitstopath, 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
circuitsis not astim.Circuit.- ValueError
If
circuitsis empty.
- clinr.circuits.load_circuits(path: str | Path) list[Circuit]¶
Return the circuits written to
pathbysave_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¶
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
pis not a number.- ValueError
If
plies outside [0, 1].
- clinr.noise_models.asymmetric_noise(p2: float, ratio: float = 10.0) NoiseModel¶
Return the model with two-qubit gates
ratiotimes noisier.Every operation other than a two-qubit gate gets rate
p2 / ratio. The defaultratio=10is 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
p2orratiois not a number.- ValueError
If
p2lies outside [0, 1], ifratiois not positive, or ifp2 / ratioexceeds 1.