qldpc.circuits.noise_model
Implementation of noise models for stim circuits (and stim-wrapping circuits such as tsim’s).
The main components of this module are:
PauliChannel: A sparse multi-qubit Pauli channel used to specify multi-qubit noise.
NoiseRule: Defines how to add noise to individual operations.
NoiseModel: Defines how noise is added to circuits.
Built-in noise models: DepolarizingNoiseModel and the superconducting-inspired SI1000NoiseModel.
Examples of basic usage with a predefined noise model:
import stim
from qldpc.circuits.noise_model import DepolarizingNoiseModel, NoiseModel, SI1000NoiseModel
# Create a simple circuit
circuit = stim.Circuit("H 0
CX 0 1")
# Apply simple depolarizing noise
noise_model = DepolarizingNoiseModel(0.001)
noisy_circuit = noise_model.noisy_circuit(circuit)
# Apply superconducting-inspired noise
noise_model = SI1000NoiseModel(0.001)
noisy_circuit = noise_model.noisy_circuit(circuit)
# Create a custom noise model
custom_model = NoiseModel(
clifford_1q_error=3e-5,
clifford_2q_error=1e-3,
readout_error=1e-3,
reset_error=1e-3,
idle_error=2e-4,
)
noisy_circuit = custom_model.noisy_circuit(circuit)
Noise on multi-qubit Clifford gates (SPP / MPP):
from qldpc.circuits.noise_model import NoiseModel, NoiseRule, PauliChannel
# `clifford_nq_error` maps a qubit count ``k`` to the noise applied after each ``k``-qubit
# unitary Clifford gate (namely, the Pauli-product Cliffords SPP and SPP_DAG, which are stim's
# multi-qubit unitary Clifford primitives). Values may be a float (uniform ``k``-qubit
# depolarizing channel), a Mapping[str, float] (auto-wrapped as PauliChannel), a PauliChannel,
# or a full NoiseRule.
noise_model = NoiseModel(
clifford_nq_error={
1: 1e-4, # DEPOLARIZE1(1e-4) after each 1-qubit gate
2: 1e-3, # DEPOLARIZE2(1e-3) after each 2-qubit gate
3: PauliChannel.depolarizing(3, 5e-3), # 3-qubit depolarizing channel, emitted as
# a chain of CORRELATED_ERROR /
# ELSE_CORRELATED_ERROR instructions
4: {"XXXX": 1e-4, "ZZZZ": 2e-4}, # sparse 4-qubit channel (raw dict)
}
)
# Multi-qubit MPP / SPP gates receive ordinary readout_error / clifford_nq_error. To assign
# per-basis rules, use "M<paulis>" for MPP (e.g. "MXYZ" for `MPP X*Y*Z`, "MXX" for `MPP X*X`)
# and "S<paulis>" / "S<paulis>_DAG" for SPP / SPP_DAG (e.g. "SXYZ" for `SPP X*Y*Z`, "SXY_DAG"
# for `SPP_DAG X*Y`).
noise_model = NoiseModel(
readout_error=1e-3, # default readout flip probability
rules={
"MXYZ": NoiseRule(readout_error=5e-3), # override for MPP X*Y*Z specifically
"SXYZ": NoiseRule(after=PauliChannel.depolarizing(3, 1e-2)), # SPP X*Y*Z override
},
)
Multi-qubit Pauli channels with arity three or greater are emitted as correlated E /
ELSE_CORRELATED_ERROR chains. Stim’s exact detector-error-model conversion rejects these chains
unless approximate_disjoint_errors=True is passed. qLDPC’s DEM consumers use that explicit
approximation; callers extracting DEMs directly must make the same modeling choice.
Per-gate-application noise via a callback (rule_func):
from qldpc.circuits.noise_model import NoiseModel, NoiseRule
# `rule_func` takes top priority over every other rule in a `NoiseModel`. Broadcast gates such
# as `H 0 1 2` and `CX 0 1 2 3` are decomposed into individual gates before being passed to
# `rule_func`, so the `op` argument is always a stim.CircuitInstruction holding exactly one gate
# application's worth of targets (e.g. two targets for a two-qubit gate, one Pauli product for
# an SPP/MPP). Returning `None` falls back to the ordinary `NoiseModel` rules.
def bad_qubit_noise(op: stim.CircuitInstruction) -> NoiseRule | None:
# Give any gate touching qubit 7 a heavier depolarizing kick; leave everything else alone.
targets = [t for t in op.targets_copy() if not t.is_combiner]
if any(t.qubit_value == 7 for t in targets):
return NoiseRule(after=PauliChannel.depolarizing(len(targets), 1e-2))
return None
noise_model = NoiseModel(
clifford_1q_error=1e-4,
clifford_2q_error=1e-3,
rule_func=bad_qubit_noise,
)
noisy_circuit = noise_model.noisy_circuit(circuit)
Important note:
This file was originally taken and modified from:
https://github.com/tqec/tqec/blob/main/src/tqec/utils/noise_model.py
which itself was taken from:
https://zenodo.org/records/7487893
and licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/legalcode).
The original code was written for the paper at “Inplace Access to the Surface Code Y Basis”, at:
https://quantum-journal.org/papers/q-2024-04-08-1310.
Portions copyright the original authors, licensed under CC BY 4.0 — see above.
Attributes
Classes
Base class for sparse Pauli channels. |
|
Creates a near-standard circuit depolarizing noise model. |
|
A model that defines how to add noise to quantum circuits. |
|
Describes how to add noise to an operation. |
|
A sparse multi-qubit Pauli channel. |
|
A sequence of independent Pauli-string error mechanisms. |
|
A superconducting-inspired noise model defined in "A Fault-Tolerant Honeycomb Memory". |
Functions
|
Wrap a circuit in a one-repetition block tagged immune to |
|
Return the qLDPC op-type category for a gate name (canonical or alias). |
Module Contents
- class qldpc.circuits.noise_model.AbstractPauliChannel(probabilities: collections.abc.Mapping[str, float], *, num_qubits: int | None = None)[source]
Bases:
abc.ABCBase class for sparse Pauli channels.
Every
AbstractPauliChannelmaps non-identity Pauli strings (over the alphabet{I, X, Y, Z}) to their probabilities. The interpretation of those probabilities generally depends on theAbstractPauliChannelsubclass.Subclasses of
AbstractPauliChannelare required to define a.to_circuitmethod.- to_circuit(*, append_to: None = None, qubits: collections.abc.Iterable[int] | None = None, tag: str = '') stim.Circuit[source]
- to_circuit(*, append_to: qldpc.circuits.common.StimCircuitLike, qubits: collections.abc.Iterable[int] | None = None, tag: str = '') qldpc.circuits.common.StimCircuitLike
Convert this channel into a circuit.
- property num_qubits: int
Number of qubits the channel acts on.
- property probabilities: collections.abc.Mapping[str, float]
Non-identity Pauli-string → probability mapping.
- class qldpc.circuits.noise_model.DepolarizingNoiseModel(p: float, *, include_idling_error: bool = False, max_gate_size: int = 2)[source]
Bases:
NoiseModelCreates a near-standard circuit depolarizing noise model.
All operations have the same error parameter p:
One-qubit Clifford gates get one-qubit depolarization.
Two-qubit Clifford gates get two-qubit depolarization.
Measurements have their outcomes probabilistically flipped.
Reset gates probabilistically reset qubits to the wrong (orthogonal) state.
If applicable, every idling qubit in a given moment gets depolarized.
Multi-qubit Cliffords can also be depolarized by increasing the max_gate_size.
Explicit
IandIIinstructions are treated as idle markers: they are preserved, do not receive gate noise, and their target qubits receive the configured idle noise. Multi-qubit measurement and Pauli-product rules are configured explicitly throughrules(for example,"MXX"or"SXYZ"); arity-based Clifford defaults apply only to unitary Clifford gates.- include_idling_error = False
- p
- class qldpc.circuits.noise_model.NoiseModel(clifford_1q_error: ErrorSpec | None = None, clifford_2q_error: ErrorSpec | None = None, readout_error: float | None = None, reset_error: float | None = None, *, clifford_nq_error: collections.abc.Mapping[int, ErrorSpec] | None = None, idle_error: ErrorSpec | None = None, additional_error_waiting_for_m_or_r: ErrorSpec | None = None, rules: collections.abc.Mapping[str, NoiseRule] | None = None, rule_func: collections.abc.Callable[[stim.CircuitInstruction], NoiseRule | None] | None = None)[source]
A model that defines how to add noise to quantum circuits.
This class provides a framework for adding various types of noise to quantum circuits, including gate errors, readout errors, reset errors, and idling errors. Classically controlled operations are assumed to NOT occur, so the corresponding qubits pick up idling errors, if applicable. Explicit
IandIImarkers are likewise treated as idle time, not as Clifford gates.- get_noise_rule(op: stim.CircuitInstruction) NoiseRule | None[source]
Determines the noise rule to apply to a specific operation.
Noise rules are consulted in the following order of precedence: 1.
rule_func(stim.CircuitInstruction -> NoiseRule factory). 2.rules(name-based NoiseRules). 3.clifford_nq_error(arity-based NoiseRules for unitary Cliffords). 4.readout_errorand/orreset_error(per-gate defaults for measurement/reset ops).Explicit idle markers (
IandII) receive idling noise rather than gate noise, sorule_funcis not consulted for them and they cannot be keys inrules.Note: MPP / SPP / SPP_DAG instructions passed to this method must contain exactly one Pauli product (e.g.
MPP X0*Y1*Z2, notMPP X0*Y1 Z2*X3). Multi-product instructions are decomposed upstream by_split_targets_ppbefore this method is invoked; hand-calling with an unsplit multi-product op raisesValueErrorfrom_get_gate_aliases.- Parameters:
op – The circuit instruction to find a noise rule for.
- Returns:
The NoiseRule to apply for the given operation, or None for no noise.
- noisy_circuit(circuit: qldpc.circuits.common.StimCircuitLike, *, system_qubits: collections.abc.Iterable[int] | None = None, immune_qubits: collections.abc.Iterable[int] = (), immune_op_tag: str | None = DEFAULT_IMMUNE_OP_TAG, immune_qubit_tag: str | None = DEFAULT_IMMUNE_QUBIT_TAG, immunize_gates: bool = True, insert_ticks: bool = True) qldpc.circuits.common.StimCircuitLike[source]
Construct a noisy version of the given circuit.
This method first uses TICKs to split the input circuit into moments of operations that can be applied in parallel, thereby preventing qubit reuse conflicts. Noise is then applied to each operation according to the rules of this NoiseModel.
- Parameters:
circuit – The circuit to apply noise to.
system_qubits – All qubits that are used by the circuit or are otherwise allowed to accumulate idling errors. Defaults to set(range(circuit.num_qubits)).
immune_qubits – Qubits that are declared to be immune to noise. Defaults to none.
immune_op_tag – If an operation contains this string in its tag, that operation is noiseless. Set to None to disable tagged operation immunity. Default: “{DEFAULT_IMMUNE_OP_TAG}”.
immune_qubit_tag – If a QUBIT_COORDS annotation contains this string in its tag, its target qubits are immune to noise. Set to None to disable annotated immunity. Default: “{DEFAULT_IMMUNE_QUBIT_TAG}”.
immunize_gates – If True (the default), a gate that touches an immune qubit is treated as noiseless. Otherwise, its Pauli noise is conditioned on the absence of errors on noise-immune qubits, keeping only strings that act as
Ion every immune qubit. An immune-tagged operation is still a real operation for moment accounting; it does not suppress idle noise on unrelated qubits in the same moment.insert_ticks – If True, automatically inserts TICK operations to prevent qubit reuse conflicts. If False, assumes that this preprocessing is not necessary.
- Returns:
The input circuit with added noise.
- additional_error_waiting_for_m_or_r
- property clifford_1q_error: NoiseRule | None
clifford_nq_error[1]if set, else None.- Type:
Convenience view
- property clifford_2q_error: NoiseRule | None
clifford_nq_error[2]if set, else None.- Type:
Convenience view
- clifford_nq_error
- idle_error
- readout_error = 0
- reset_error = 0
- rule_func = None
- rules = None
- class qldpc.circuits.noise_model.NoiseRule(*, after: AbstractPauliChannel | collections.abc.Mapping[str, float] | stim.Circuit | None = None, readout_error: float | None = None, reset_error: float | None = None)[source]
Describes how to add noise to an operation.
This class encapsulates the noise channels and measurement error probabilities that should be applied to a particular type of quantum operation.
- emit_after(circuit: qldpc.circuits.common.StimCircuitLike, qubit_targets: list[int], *, context: str = 'operation') None[source]
Append this rule’s
afternoise in-place to the provided circuit.If the operation packages multiple independent gates (e.g.,
H 0 1 2— threeHgates in one instruction), the noise is applied per gate. For broadcast forms (PauliChannelof arity 1 or 2), this is achieved by a single emission on all targets, since stim’sPAULI_CHANNEL_1/PAULI_CHANNEL_2broadcast natively. For higher-arityPauliChanneland for thestim.Circuitform, the fragment is emitted once per gate.- Parameters:
circuit – The circuit to append the noise instructions to.
qubit_targets – The qubits the noise applies to (in the operation’s target order).
context – A short description of the operation, used only in error messages.
- Raises:
ValueError – If
len(qubit_targets)is not a multiple of theafterrule’s arity (i.e. the operation cannot be split into an integer number of individual gates matching the rule).
- noisy_operation(op: stim.CircuitInstruction) tuple[stim.CircuitInstruction, stim.Circuit][source]
Apply this noise rule to the given operation.
- Parameters:
op – The operation to add noise to.
- Returns:
The given operation possibly modified to account for noise. stim.Circuit: Noise operations that should follow the given operation.
- Return type:
stim.CircuitInstruction
- after: AbstractPauliChannel | stim.Circuit | None
- readout_error = None
- reset_error = None
- class qldpc.circuits.noise_model.PauliChannel(probabilities: collections.abc.Mapping[str, float], *, num_qubits: int | None = None)[source]
Bases:
AbstractPauliChannelA sparse multi-qubit Pauli channel.
Maps non-identity Pauli strings (over the alphabet
{I, X, Y, Z}) to their probabilities. The strings name mutually-exclusive outcomes: exactly one Pauli (possibly the identity) is applied. The all-identity string is implicit; its probability is1 - sum(others), so the listed probabilities must sum to at most 1.- conditioned_on(immune_qubits: collections.abc.Iterable[int]) PauliChannel[source]
Return the sub-channel of error mechanisms that act as identity on the given qubits.
Keeps only Pauli strings whose positions in
immune_qubitsare allI, with their original probabilities. The returned channel has the samenum_qubitsasself— surviving strings retain their length; the immune positions are still present, always asI. Total probability is in general reduced (the dropped weight represents error events that would have acted nontrivially on an immune qubit, which are assumed to not occur).- Parameters:
immune_qubits – Positions in
[0, num_qubits)to constrain to identity. Repeats are ignored.- Returns:
A
PauliChannelon the same qubits asself. If no strings survive, the returned channel is empty but still reportsnum_qubits == self.num_qubits.- Raises:
ValueError – If any index is outside
[0, num_qubits).
- static depolarizing(num_qubits: int, probability: float) PauliChannel[source]
Uniform
num_qubits-qubit depolarizing channel with total errorprobability.Each of the
4**num_qubits - 1non-identity Pauli strings is assigned probabilityprobability / (4**num_qubits - 1). Strings are inserted in lexicographic order.
- to_circuit(*, append_to: None = None, qubits: collections.abc.Iterable[int] | None = None, simplify: bool = True, tag: str = '') stim.Circuit[source]
- to_circuit(*, append_to: qldpc.circuits.common.StimCircuitLike, qubits: collections.abc.Iterable[int] | None = None, simplify: bool = True, tag: str = '') qldpc.circuits.common.StimCircuitLike
Convert this PauliChannel into a circuit.
If provided a circuit, append to that circuit in-place and return it.
By default (with
simplify=True), the channel is emitted in the simplest form its probabilities permit: channels that address only one or two qubits nontrivially becomePAULI_CHANNEL_[12]/DEPOLARIZE[12]/[XYZ]_ERROR.With
simplify=Falsethe channel is always emitted as aCORRELATED_ERRORfollowed by oneELSE_CORRELATED_ERRORper remaining Pauli string, with conditional probabilities renormalized so each string’s unconditional firing probability matches this channel. For channels with three or more active qubits, this correlated chain requiresapproximate_disjoint_errors=Truewhen converting a containing Stim circuit to a detector error model.- Parameters:
append_to – The circuit to append to; if
None(default), create a new circuit.qubits – The qubit targets, one per position of the channel; if
None(default), set torange(self.num_qubits).simplify – If True (the default), emit the channel in the simplest equivalent form. If False, always emit a
CORRELATED_ERROR/ELSE_CORRELATED_ERRORchain.tag – An optional tag applied to every emitted instruction.
- Returns:
The circuit that the noise instructions were appended to.
- Raises:
ValueError – If the number of
qubitsdoes not match the arity of the channel.
- class qldpc.circuits.noise_model.PauliChannelSequence(probabilities: collections.abc.Mapping[str, float], *, num_qubits: int | None = None)[source]
Bases:
AbstractPauliChannelA sequence of independent Pauli-string error mechanisms.
Like
PauliChannel, this maps non-identity Pauli strings to probabilities, but the entries are independent events rather than mutually-exclusive outcomes: each fires (or not) on its own, and several may fire together.- to_circuit(*, append_to: None = None, qubits: collections.abc.Iterable[int] | None = None, tag: str = '') stim.Circuit[source]
- to_circuit(*, append_to: qldpc.circuits.common.StimCircuitLike, qubits: collections.abc.Iterable[int] | None = None, tag: str = '') qldpc.circuits.common.StimCircuitLike
Emit each entry of this channel as an independent
CORRELATED_ERROR.If provided a circuit, append to that circuit in-place and return it.
- Parameters:
append_to – The circuit to append to; if
None(default), create a new circuit.qubits – The qubit targets, one per position of the channel; if
None(default), set torange(self.num_qubits).tag – An optional tag applied to every emitted instruction.
- Returns:
The circuit that the noise instructions were appended to.
- Raises:
ValueError – If the number of
qubitsdoes not match the arity of the channel.
- class qldpc.circuits.noise_model.SI1000NoiseModel(p: float)[source]
Bases:
NoiseModelA superconducting-inspired noise model defined in “A Fault-Tolerant Honeycomb Memory”.
This noise model is defined by a two-qubit gate infidelity that determines all error rates.
See https://arxiv.org/abs/2108.10457. A qubit waiting while another qubit is measured or reset receives both the ordinary idling rate
p/10and the additional waiting rate2*p; this matches the cited reference implementation.- p
- qldpc.circuits.noise_model.as_noiseless_circuit(circuit: qldpc.circuits.common.StimCircuitLike) qldpc.circuits.common.StimCircuitLike[source]
Wrap a circuit in a one-repetition block tagged immune to
NoiseModel.
- qldpc.circuits.noise_model.op_type(op_name: str) str[source]
Return the qLDPC op-type category for a gate name (canonical or alias).
- qldpc.circuits.noise_model.ALL_STIM_GATE_NAMES
- qldpc.circuits.noise_model.ANNOTATION = 'info'
- qldpc.circuits.noise_model.CLIFFORD_1Q = 'C1'
- qldpc.circuits.noise_model.CLIFFORD_2Q = 'C2'
- qldpc.circuits.noise_model.CLIFFORD_PP = 'CPP'
- qldpc.circuits.noise_model.COLLAPSING_OPS
- qldpc.circuits.noise_model.DEFAULT_IMMUNE_OP_TAG = '__IMMUNE_TO_NOISE__'
- qldpc.circuits.noise_model.DEFAULT_IMMUNE_QUBIT_TAG = '__IMMUNE_QUBIT_TO_NOISE__'
- type qldpc.circuits.noise_model.ErrorSpec = float | Mapping[str, float] | AbstractPauliChannel | NoiseRule
- qldpc.circuits.noise_model.GATE_OP_TYPES
- qldpc.circuits.noise_model.IDLE_OPS
- qldpc.circuits.noise_model.JUST_MEASURE_1Q = 'M1'
- qldpc.circuits.noise_model.JUST_MEASURE_2Q = 'M2'
- qldpc.circuits.noise_model.JUST_MEASURE_OPS
- qldpc.circuits.noise_model.JUST_MEASURE_PP = 'MPP'
- qldpc.circuits.noise_model.JUST_RESET_1Q = 'R1'
- qldpc.circuits.noise_model.JUST_RESET_OPS
- qldpc.circuits.noise_model.MEASURE_AND_RESET_OPS
- qldpc.circuits.noise_model.MEASURE_RESET_1Q = 'MR1'
- qldpc.circuits.noise_model.NOISE = '!?'
- qldpc.circuits.noise_model.UNSUPPORTED = 'unsupported'