Noise¶
Stochastic Pauli noise, including correlated multi-qubit terms, coherent Pauli-rotation errors, and general channels such as amplitude damping and thermal relaxation on the HSMPO surrogate; after gates, on the spectators of a gate (crosstalk), on idle qubits, at preparation and at readout.
Describe the noise with a NoiseModel, adding errors
rule by rule as in qibo, then call noisy_expectation():
add()puts an error after every matching gate, or on the initial state and the measured bits forStatePreparationErrorandReadoutError;add_crosstalk()puts it on the qubits coupled to a gate but not acted on by it;add_idle()puts it on the qubits left idle in each moment, or on coupled pairs of them, as an always-onZZdoes.
apply() returns the same noisy circuit as a
qibo density-matrix circuit, for exact reference values on small systems.
A Pauli fault pulled into the Clifford frame leaves the tableau unchanged: it only negates the angle of every later dressed rotation it anticommutes with, and the sign of the dressed observable if it anticommutes with that too. A noisy expectation value is then an average of noiseless HSMPO expectation values over sign patterns of the rotation chain: the patterns with zero and one fault are summed exactly, those with two or more are sampled. Coherent errors are dressed like magic gates and join the chain.
A general channel, written in the Pauli basis as
sum_{A, B} chi[A, B] A rho B, splits into its diagonal, a Pauli channel
handled as above, and its off-diagonal coherences, which make it non-unital.
A coherence acts on the ket with A and on the bra with B: it flips
the two chains’ signs differently and contributes the transition amplitude
between them, weighted by the complex chi[A, B]. The one-location terms
stay exact; with several locations the sampled weights become a
quasi-probability, whose total exceeds 1 by about the summed |chi| of the
coherences.
Readout noise flips a measured 0 with probability p0 and a 1 with
probability p1: every non-identity factor of a Pauli term on that qubit
becomes (1 - p0 - p1) P + (p1 - p0) I.
Usage Example:
from qibo import gates
from mpstab import (
HSMPO,
CoherentError,
DepolarizingError,
NoiseModel,
PauliError,
ReadoutError,
StatePreparationError,
ThermalRelaxationError,
)
from mpstab.models.ansatze import KickedIsing
ansatz = KickedIsing(nqubits=4, n_steps=1, theta_h=0.7, theta_z=0.3)
surrogate = HSMPO(ansatz)
noise = NoiseModel()
noise.add(PauliError({"X": 1e-3, "Y": 1e-3, "Z": 1e-3})) # every gate, every qubit
noise.add(DepolarizingError(0.01), gates.CNOT) # two-qubit depolarizing
noise.add(PauliError({"ZZ": 0.005}), gates.CNOT) # correlated dephasing
noise.add(CoherentError("ZZ", 0.02), gates.CNOT) # residual coupling
noise.add(ThermalRelaxationError(t1=100.0, t2=80.0, time=0.05), gates.CNOT)
chain = [(0, 1), (1, 2), (2, 3)]
noise.add_crosstalk(CoherentError("ZZ", 0.01), chain, gates.CNOT)
noise.add_idle(ThermalRelaxationError(t1=100.0, t2=80.0, time=0.02))
noise.add_idle(CoherentError("ZZ", 0.005).twirled(), coupling=chain)
noise.add(StatePreparationError(0.005)) # |0> prepared as |1>
noise.add(ReadoutError(0.01, 0.03)) # 1 -> 0 likelier
result = surrogate.noisy_expectation("ZIIZ", noise, n_samples=500, seed=0)
print(f"noiseless {surrogate.expectation('ZIIZ'):+.4f}")
print(f"noisy {result.mean:+.4f} +- {result.stderr:.4f}")
# Noise-strength sweeps, e.g. for zero-noise extrapolation:
stronger = noise.scaled(2.0)
A gate-attached noise model, built with NoiseModel.add() as in qibo.
- class mpstab.models.noise.model.AmplitudeDampingError(gamma: float)[source]¶
Amplitude damping
|1> -> |0>with probabilitygammaon each qubit of the gate: energy relaxation (T1), which is not unital.- Variables:
gamma (float) – damping probability, in
[0, 1].
Example:
from mpstab import AmplitudeDampingError t1 = AmplitudeDampingError(0.01)
- class mpstab.models.noise.model.CoherentError(generator: str, angle: float)[source]¶
Coherent error
exp(-i angle/2 P), such as an over-rotation or a residual ZZ coupling.A single-qubit
generatoracts on each qubit of the gate; one as wide as the gate acts jointly on its qubits, in the gate’s qubit order. Each one joins the rotation chain like a magic gate, so many of them cost bond dimension:twirled()is the stochastic Pauli error the same rotation becomes under randomized compiling, which costs none.- Variables:
generator (str) – Pauli label of the rotation, one qubit or as wide as the gate.
angle (float) – rotation angle.
Example:
from mpstab import CoherentError residual_zz = CoherentError("ZZ", 0.02) over_rotation = CoherentError("X", 0.01) print(residual_zz.twirled())
- twirled() PauliError[source]¶
The Pauli twirl of the rotation,
rho -> cos^2 rho + sin^2 P rho Pwithsin^2 = sin(angle/2)**2.
- property width: int¶
1 per qubit of the gate, or the whole gate.
- Type:
Qubits the generator acts on
- class mpstab.models.noise.model.DepolarizingError(lam: float)[source]¶
Depolarizing channel
(1 - lam) rho + lam I / 2**kon thekqubits of the gate, with qibo’s convention: probabilitylam / 4**kon each of the4**k - 1non-identity Paulis.For independent single-qubit depolarizing on every qubit of a multi-qubit gate, use
PauliError({"X": p / 3, "Y": p / 3, "Z": p / 3}). On idle qubits and spectators (NoiseModel.add_idle(),NoiseModel.add_crosstalk()) it acts on each qubit alone.- Variables:
lam (float) – depolarizing strength, in
[0, 4/3].
Example:
from mpstab import DepolarizingError error = DepolarizingError(0.01)
- width = None¶
Always acts on the whole gate.
- class mpstab.models.noise.model.KrausError(operators: Sequence[ndarray])[source]¶
Any channel, given by its Kraus operators:
rho -> sum_k K_k rho K_k^dag.Operators on one qubit act on each qubit of the gate; operators as wide as the gate act jointly on its qubits, the first of them the most significant factor, as in qibo. The channel is split into its Pauli twirl, sampled as Pauli faults, and the off-diagonal part of its process matrix, evaluated as transition amplitudes (
KrausChannel).- Variables:
operators (Sequence[numpy.ndarray]) – the Kraus operators, each
2**k x 2**k.
Example:
# A phase-damping channel. import numpy as np from mpstab import KrausError lam = 0.05 phase_damping = KrausError([ np.diag([1, np.sqrt(1 - lam)]), np.diag([0, np.sqrt(lam)]), ])
- class mpstab.models.noise.model.NoiseModel(rules: list[_Rule] = <factory>)[source]¶
Noise attached to a circuit, built rule by rule as in qibo.
add()puts an error right after each matching gate, or, forReadoutErrorandStatePreparationError, on the measured bits and on the initial state.add_crosstalk()puts it on the spectators of each matching gate: the qubits coupled to the gate but not acted on by it.add_idle()puts it on the qubits left idle in each moment of the circuit.
Pass the model to
noisy_expectation();apply()gives the same noisy circuit as a qibo density-matrix circuit, for exact reference values.- Variables:
rules (list[mpstab.models.noise.model._Rule]) – the rules added so far, in order.
Example:
from qibo import gates from mpstab import ( HSMPO, AmplitudeDampingError, CoherentError, DepolarizingError, NoiseModel, PauliError, ) from mpstab.models.ansatze import KickedIsing chain = [(0, 1), (1, 2), (2, 3)] noise = NoiseModel() noise.add(DepolarizingError(1e-3)) # after every gate noise.add(PauliError({"ZZ": 5e-4}), gates.CNOT) # correlated, on CNOTs noise.add(CoherentError("ZZ", 0.02), gates.CNOT) # residual coupling noise.add(PauliError({"Z": 1e-3}), gates.RX, qubits=[0, 1]) noise.add_crosstalk(PauliError({"ZZ": 1e-3}), chain, gates.CNOT) noise.add_idle(AmplitudeDampingError(1e-3)) # T1 while idle hsmpo = HSMPO(KickedIsing(nqubits=4, n_steps=1, theta_h=0.7)) ideal = hsmpo.expectation("ZIIZ") noisy = hsmpo.noisy_expectation("ZIIZ", noise, n_samples=500, seed=0) print(f"{ideal:+.4f} -> {noisy.mean:+.4f} +- {noisy.stderr:.4f}")
- add(error: PauliError | DepolarizingError | CoherentError | KrausError | AmplitudeDampingError | ThermalRelaxationError | ReadoutError | StatePreparationError, gate: type | Sequence[type] | None = None, qubits: int | Sequence[int] | None = None) NoiseModel[source]¶
Put
errorafter every gate of typegate(all gates ifNone).- Parameters:
error – the error to insert. Readout and preparation errors take no gate.
gate – qibo gate class, or sequence of them; only gates of these types get the error. Measurements never do.
qubits – restrict the error to these qubits. A single-qubit error acts only on the gate’s qubits in this set; an error spanning the whole gate applies only to gates entirely inside it.
- Returns:
self, so calls can be chained.- Raises:
TypeError – if
erroris not an mpstab error.ValueError – if a
ReadoutErroror aStatePreparationErroris given agate.
- add_crosstalk(error: PauliError | DepolarizingError | CoherentError | KrausError | AmplitudeDampingError | ThermalRelaxationError, coupling: Iterable[tuple[int, int]], gate: type | Sequence[type] | None = None) NoiseModel[source]¶
Put
erroron the spectators of every gate of typegate.A spectator is a qubit coupled to one of the gate’s qubits without being acted on by the gate. A single-qubit error acts on each spectator; a two-qubit one acts on each
(gate qubit, spectator)edge, in that order, asZZcrosstalk from a driven qubit does.- Parameters:
error – the error, on one qubit or on two.
coupling – the coupling graph, as qubit pairs.
gate – qibo gate class, or sequence of them; only gates of these types cause the crosstalk.
- Returns:
self, so calls can be chained.
- add_idle(error: PauliError | DepolarizingError | CoherentError | KrausError | AmplitudeDampingError | ThermalRelaxationError, qubits: int | Sequence[int] | None = None, coupling: Iterable[tuple[int, int]] | None = None) NoiseModel[source]¶
Put
erroron the qubits left idle in each moment of the circuit.Moments are an in-order layering of the gate queue: a gate lands one moment after the last gate on any of its qubits, and never before the gate queued ahead of it, so a circuit queued layer by layer gets its layers as moments. A single-qubit error acts on every idle qubit of every moment, before its first gate and after its last one included. A two-qubit error, such as an always-on
ZZcoupling, acts on eachcouplingedge whose two qubits are both idle.- Parameters:
error – the error, on one qubit or on two.
qubits – restrict the error to these qubits.
coupling – the coupling graph, needed by two-qubit errors.
- Returns:
self, so calls can be chained.
- apply(circuit: Circuit) Circuit[source]¶
circuitwith the noise inserted, as a qibo density-matrix circuit: Pauli errors asPauliNoiseChannel, coherent ones as unitaries and the others asKrausChannel.Readout errors act on the measured bits, not on the state, so they are not part of this circuit: apply them to the observable with
readout_observable().
- events(circuit: Circuit) list[NoiseEvent][source]¶
The model resolved on
circuit: one event per inserted error.
- readout_attenuation(nqubits: int) ndarray[source]¶
The
scaleofreadout_maps(): the product of1 - p0 - p1over the readout errors on each qubit, shape(nqubits,).
- readout_maps(nqubits: int) tuple[ndarray, ndarray][source]¶
The readout errors of each qubit as
(scale, offset), each of shape(nqubits,): a measured Pauli factorPon qubitqreads asscale[q] P + offset[q] I. Ones and zeros where there is no readout noise.
- readout_observable(observable, nqubits: int) tuple[float, dict][source]¶
observableas(constant, {pauli: coefficient}), aspauli_terms()returns it, with the readout errors folded in (readout_maps()).A symmetric error only rescales the terms. An asymmetric one expands a term with
wnon-identity factors on asymmetric qubits into its2**wsubterms, the empty one adding to the constant.
- scaled(factor: float) NoiseModel[source]¶
A copy with every error’s strength multiplied by
factor: its probabilities, coherent angles, damping rates or relaxation times, for noise-strength sweeps such as zero-noise extrapolation.
- class mpstab.models.noise.model.PauliError(probs: dict[str, float])[source]¶
Stochastic Pauli error:
probs[P]is the probability thatPacts.Single-qubit labels (
{"X": 0.01, "Z": 0.02}) act independently on each qubit of the gate. Labels as wide as the gate ({"ZZ": 0.01}after a two-qubit gate) act jointly on its qubits, in the gate’s qubit order, which is how correlated noise is written.- Variables:
probs (dict[str, float]) – probability of each non-identity Pauli label.
Example:
from mpstab import PauliError dephasing = PauliError({"Z": 0.01}) correlated = PauliError({"ZZ": 0.005, "XX": 0.001})
- property width: int¶
1 per qubit of the gate, or the whole gate.
- Type:
Qubits each label acts on
- class mpstab.models.noise.model.ReadoutError(p0: float, p1: float | None = None)[source]¶
Readout bit flips: a measured
0is reported as1with probabilityp0, and a1as0with probabilityp1(p0if not given).A Pauli expectation value is estimated from the bits read out in the term’s eigenbasis, so every non-identity factor
Pof a term on a noisy qubit becomes(1 - p0 - p1) P + (p1 - p0) I. A symmetric error only attenuates the term; an asymmetric one also mixes in its lower-weight subterms. Add it with no gate, optionally restricted to some qubits; errors on the same qubit compose.- Variables:
p0 (float) – probability of reading a
0as1, in[0, 1].p1 (float | None) – probability of reading a
1as0, in[0, 1];p0if not given.
Example:
from mpstab import NoiseModel, ReadoutError noise = NoiseModel() noise.add(ReadoutError(0.02)) # every qubit noise.add(ReadoutError(0.01, 0.05), qubits=[0]) # 1 -> 0 is likelier
- class mpstab.models.noise.model.StatePreparationError(p: float)[source]¶
Preparation error: each qubit starts flipped by
Xwith probabilityp, so|0>is prepared as|1>. Add it with no gate, optionally restricted to some qubits; it acts on the initial state, before any gate.- Variables:
p (float) – flip probability of each qubit, in
[0, 1].
Example:
from mpstab import NoiseModel, StatePreparationError noise = NoiseModel().add(StatePreparationError(0.01))
- class mpstab.models.noise.model.ThermalRelaxationError(t1: float, t2: float, time: float, excited_population: float = 0.0)[source]¶
Thermal relaxation for a duration
timeon each qubit of the gate: the excited population relaxes toexcited_populationwith time constantt1, and coherences decay asexp(-time / t2).It is generalized amplitude damping with
gamma = 1 - exp(-time / t1)followed by the pure dephasing that brings the coherence decay fromexp(-time / (2 t1))down toexp(-time / t2), sot2 <= 2 t1.scaled()scalestime.- Variables:
t1 (float) – energy relaxation time.
t2 (float) – dephasing time, at most
2 * t1.time (float) – duration of the error, in the units of
t1andt2.excited_population (float) – equilibrium population of
|1>, in[0, 1].
Example:
from mpstab import ThermalRelaxationError idle = ThermalRelaxationError(t1=100e-6, t2=80e-6, time=50e-9)
- class mpstab.models.noise.NoisyExpectation(mean: float, stderr: float, n_patterns: int, fidelities: ndarray, stratum_weights: tuple[float, float, float], n_samples: int, n_transitions: int = 0)[source]¶
Result of
noisy_expectation().- Variables:
mean (float) – the noisy expectation value.
stderr (float) – its standard error, from the sampled
k >= 2stratum only: the lower strata are exact. Zero when nothing was sampled.n_patterns (int) – distinct rotation sign patterns evaluated on the MPS as expectation values.
fidelities (numpy.ndarray) – truncation fidelity of the MPS of each of those patterns, shape
(n_patterns,);nanfor an engine that does not expose a norm.stratum_weights (tuple[float, float, float]) – total weight of the configurations with
k = 0,k = 1andk >= 2locations doing something, counting only the faults and coherences that can affect the observable. For Pauli noise these are probabilities summing to 1; coherences count with|chi|.n_samples (int) – configurations sampled for the
k >= 2stratum.n_transitions (int) – transition amplitudes evaluated for coherences, exact and sampled.
Low-level interface¶
noisy_expectation() resolves the model into noise events
placed by gate index, compiles them into the Clifford frame and runs the
fault-pattern estimator. The three steps are available on their own.
Noise events: what happens, and after which gate of the circuit.
Every event is anchored to a position in ansatz.circuit.queue: it acts right
after the gate at index after_gate, or on the initial state when
after_gate is -1. Events sharing an anchor act in the order they are
listed.
- class mpstab.models.noise.events.CoherentRotation(after_gate: int, generator: str, angle: float)[source]¶
Bases:
NoiseEventA coherent error
exp(-i angle/2 generator), such as ZZ crosstalk or an over-rotation.- Variables:
after_gate (int) – index of the gate the rotation follows, or
-1for the initial state.generator (str) – full-width Pauli string, one label per qubit of the circuit.
angle (float) – rotation angle.
Example
ZZ crosstalk between qubits 1 and 2 of a 4-qubit circuit, after gate 3:
from mpstab.models.noise.events import CoherentRotation crosstalk = CoherentRotation(after_gate=3, generator="IZZI", angle=0.02)
- class mpstab.models.noise.events.KrausChannel(after_gate: int, qubits: tuple[int, ...], kraus: tuple[ndarray, ...])[source]¶
Bases:
NoiseEventA general channel
rho -> sum_k K_k rho K_k^dagon a few qubits, such as amplitude damping or thermal relaxation.In the Pauli basis the channel is
sum_{A, B} chi[A, B] A rho B(chi). The diagonal ofchiis a Pauli channel, its Pauli twirl; the off-diagonal entries are what makes it non-unital or otherwise non-Pauli, and the estimator evaluates them as transition amplitudes between two sign patterns of the rotation chain.- Variables:
after_gate (int) – index of the gate the channel follows, or
-1for the initial state.qubits (tuple[int, ...]) – the qubits the channel acts on.
qubits[0]is the most significant factor of the Kraus matrices, as in qibo.kraus (tuple[numpy.ndarray, ...]) – Kraus operators, each
2**k x 2**kfork = len(qubits). They must satisfysum_k K_k^dag K_k = I.
Example:
# Amplitude damping of qubit 0 after the first gate. import numpy as np from mpstab.models.noise.events import KrausChannel gamma = 0.05 damping = KrausChannel( after_gate=0, qubits=(0,), kraus=( np.array([[1, 0], [0, np.sqrt(1 - gamma)]]), np.array([[0, np.sqrt(gamma)], [0, 0]]), ), ) print(damping.chi[("I", "Z")]) # gamma / 4
- property chi: dict[tuple[str, str], complex]¶
The process matrix in the Pauli basis,
{(A, B): chi[A, B]}, withAandBlabels onqubits; entries below1e-15in magnitude are left out. It is Hermitian, and its diagonal sums to 1.
- class mpstab.models.noise.events.NoiseEvent(after_gate: int)[source]¶
Bases:
objectBase class of every noise event.
compile_noise()dispatches on the concrete type and rejects any it does not know: a new kind of event is added as a subclass plus a branch there.- Variables:
after_gate (int) – index in
ansatz.circuit.queueof the gate the event follows, or-1for the initial state.
- class mpstab.models.noise.events.PauliChannel(after_gate: int, qubits: tuple[int, ...], probs: dict[str, float] = <factory>)[source]¶
Bases:
NoiseEventA stochastic Pauli channel, possibly correlated over several qubits.
With probability
probs[P]the Pauli stringPacts onqubits, and with the remaining probability nothing happens.- Variables:
after_gate (int) – index of the gate the channel follows, or
-1for the initial state.qubits (tuple[int, ...]) – the qubits the channel acts on, in the order the Pauli labels use.
probs (dict[str, float]) – probability of each non-identity Pauli string on
qubits, one label per qubit. They must sum to at most 1.
Example
A correlated two-qubit channel after the first gate:
from mpstab.models.noise.events import PauliChannel channel = PauliChannel(after_gate=0, qubits=(0, 1), probs={"ZZ": 0.01, "XI": 0.002}) print(channel.no_fault_probability)
- full_width_terms(nqubits: int) list[tuple[str, float]][source]¶
The channel’s terms as
(pauli, probability), padded tonqubits.- Parameters:
nqubits – width of the circuit.
- Returns:
One
(pauli, probability)entry per term, inprobsorder.- Raises:
ValueError – if the channel acts on a qubit outside the circuit.
- property no_fault_probability: float¶
Probability that the channel does nothing.
Pull noise events into the Clifford frame of an HSMPO surrogate.
A Pauli fault E after Clifford prefix C is the dressed fault
E' = C^dag E C at the same point of the dressed-rotation chain. Moving it
through every later dressed rotation and the Clifford remainder to the
observable leaves the tableau untouched: it only flips the sign of the angle
of each later rotation whose generator anticommutes with E', and the sign
of the dressed observable if that anticommutes too. A coherent rotation is
dressed exactly like a magic gate and joins the chain.
A general channel sum_{A, B} chi[A, B] A rho B splits into its diagonal,
a Pauli channel compiled as above, and pairs (A, B) of its off-diagonal
entries, the coherences. A coherence acts on the ket with A' and on the
bra with B', so it flips the ket’s and the bra’s rotation signs
differently and contributes a transition amplitude between the two.
- class mpstab.models.noise.compile.CompiledNoise(hsmpo: HSMPO, generators: list[str], angles: np.ndarray, fault_paulis: list[str], fault_probs: np.ndarray, fault_location: np.ndarray, location_probs: np.ndarray, flips: np.ndarray, coherence_ket: list[str] = <factory>, coherence_bra: list[str] = <factory>, coherence_weights: np.ndarray = <factory>, coherence_location: np.ndarray = <factory>, ket_flips: np.ndarray | None = None, bra_flips: np.ndarray | None = None, location_position: np.ndarray | None = None)[source]¶
A noisy circuit in the Clifford frame of an HSMPO surrogate.
Build it with
compile_noise(). Each location is onePauliChannelorKrausChannel. Each fault is a non-identity Pauli of a location with nonzero probability: a term of the Pauli channel, or a diagonal entry of the Kraus channel’s process matrix. Each coherence is a pair of distinct Paulis with a nonzero off-diagonal entry, stored once for the pair. Both are stored in location order.- Variables:
hsmpo (HSMPO) – the surrogate supplying the engines and the initial MPS. It is only read from, never modified.
generators (list[str]) – dressed generators of the rotation chain: the magic gates and the coherent rotations, in circuit order.
angles (np.ndarray) – signed angle of each rotation, shape
(R,).fault_paulis (list[str]) – dressed Pauli of each fault, unsigned, length
F.fault_probs (np.ndarray) – probability of each fault, shape
(F,).fault_location (np.ndarray) – location index of each fault, shape
(F,), nondecreasing.location_probs (np.ndarray) – probability that each location faults at all, shape
(L,).flips (np.ndarray) – boolean
(F, R)matrix,Truewhere a fault flips the sign of a rotation’s angle.coherence_ket (list[str]) – dressed Pauli
A'of each coherence, unsigned, lengthC; the identity string whereAis the identity.coherence_bra (list[str]) – dressed Pauli
B'of each coherence, likewise.coherence_weights (np.ndarray) – complex
chi[A, B]of each coherence, times the dressing signs ofA'andB', shape(C,). The pair(B, A)has the conjugate weight.coherence_location (np.ndarray) – location index of each coherence, shape
(C,), nondecreasing.ket_flips (np.ndarray | None) – boolean
(C, R)matrix: the rotationsA'flips.bra_flips (np.ndarray | None) – boolean
(C, R)matrix: the rotationsB'flips.location_position (np.ndarray | None) – rotations applied before each location, shape
(L,), nondecreasing.
- property coherence_mass: ndarray¶
Total
|chi|of the coherences of each location, both orientations counted, shape(L,).
- dress_observable(pauli: str)[source]¶
Dress a Pauli observable with the full Clifford circuit.
- Parameters:
pauli – full-width Pauli string.
- Returns:
The dressed string and its sign, as
backpropagate()returns them.
- dress_observables(paulis: Sequence[str]) list[source]¶
dress_observable()for many terms, sharing the engine’s work.
- property nqubits: int¶
Width of the circuit.
- observable_flips(dressed_paulis: Sequence[str]) ndarray[source]¶
Which faults flip the sign of each dressed observable term.
- Parameters:
dressed_paulis – dressed observable terms, from
dress_observable().- Returns:
Boolean
(F, len(dressed_paulis))matrix.
- restricted_to(dressed_paulis: Sequence[str]) CompiledNoise[source]¶
The same noisy circuit, reduced to what can affect an observable.
Rotations outside the observable’s light cone (
pauli_light_cone()) are dropped. A fault that then flips no remaining rotation and commutes with the observable terms leaves every expectation value unchanged, so it is folded into its location’s no-fault probability, and locations left with nothing are dropped.A location with coherences is dropped whole when all its Paulis pass the same test: the channel then commutes through to the observable, where trace preservation makes it the identity. Otherwise its Paulis spread the observable, so they join the light cone, which may keep more rotations and locations; this is repeated until nothing changes. Every step is exact for this observable.
- Parameters:
dressed_paulis – dressed observable terms, from
dress_observable().- Returns:
A new
CompiledNoise; this one is left untouched.
- mpstab.models.noise.compile.compile_noise(hsmpo: HSMPO, events: Sequence[NoiseEvent]) CompiledNoise[source]¶
Dress the noise events of a circuit with its Clifford frame.
The stabilizers engine dresses every magic gate, coherent rotation and Pauli fault with the Clifford gates before its own position, in one call (
backpropagate_at()), and the flip matrix then follows from the symplectic form in one matrix product.- Parameters:
hsmpo – surrogate of the noiseless circuit. Its
ansatz.circuit.queueis whatafter_gateindexes. It may be built withrotations_only().events – the noise, as
PauliChannel,CoherentRotationandKrausChannelevents.
- Returns:
The
CompiledNoise.- Raises:
NotImplementedError – on an event type this function does not know.
ValueError – on an
after_gateoutside the circuit, or an ansatz whose own partitioning does not follow its circuit queue (FloquetAnsatz).
Example:
from qibo import Circuit, gates from mpstab import HSMPO from mpstab.models.noise.compile import compile_noise from mpstab.models.noise.events import PauliChannel circuit = Circuit(2) circuit.add(gates.H(0)) circuit.add(gates.RZ(0, theta=0.3)) circuit.add(gates.CNOT(0, 1)) # A bit flip between the H and the RZ anticommutes with the RZ. events = [PauliChannel(after_gate=0, qubits=(0,), probs={"X": 0.01})] compiled = compile_noise(HSMPO(circuit), events) print(compiled.generators, compiled.flips) # ['XI'] [[ True]]
Noisy expectation values as averages over sign patterns of the rotation chain.
Every set of faults maps to a sign pattern over the dressed rotations and the
observable terms (mpstab.models.noise.compile), so the noisy expectation value
of Pauli noise is a probability-weighted average of noiseless HSMPO
expectation values with some angles negated. A coherence (A, B) of a
non-Pauli channel flips the ket’s and the bra’s angles differently, and
contributes the transition amplitude <phi_B| B' O A' |phi_A> between the
two patterns with the complex weight chi[A, B].
The sum over configurations is stratified by the number k of locations
that do something, each configuration weighted by the product of its entries:
the no-fault probability, a fault’s probability or a coherence’s complex
weight.
k = 0andk = 1are summed exactly;k >= 2is sampled from its conditional distribution, with coherences drawn by|chi|and their phases carried as a weight, and its mean is multiplied by the total weight of that stratum.
For Pauli noise the weights are probabilities. Coherences make them a
quasi-probability, whose total exceeds 1 by about their summed |chi|.
Before any of this, the circuit is restricted to the light cone of the
observable and the coherences
(restricted_to()): rotations that cannot
affect them are dropped, and so are faults that then do nothing. Patterns are
deduplicated, then evaluated in lexicographic order, each one restarting from
the MPS checkpoint before its first rotation that differs from the previous
pattern; the bra of a transition branches off the ket’s checkpoint at their
first difference.
- mpstab.models.noise.mc_noise_estimator.noisy_expectation(compiled: CompiledNoise, observable: str | list | dict | SymbolicHamiltonian, n_samples: int = 1000, seed: int | None = None, light_cone: bool = True, n_workers: int = 1) NoisyExpectation[source]¶
Expectation value of
observableon the noisy circuit.- Parameters:
compiled – the noisy circuit, from
compile_noise().observable – a Pauli string or any other format
pauli_terms()accepts.n_samples – configurations to sample for the
k >= 2stratum. With0that stratum is dropped, which biases the mean by at moststratum_weights[2]times the sum of the absolute coefficients.seed – seed of the sampler.
light_cone – restrict the circuit to the observable’s light cone first. This is exact, and it leaves fewer rotations per pattern and fewer faults, so a smaller
k >= 2weight and a smaller standard error. Turn it off only to compare against the unrestricted computation.n_workers – processes evaluating the sign patterns of Pauli faults. The distinct patterns are split into contiguous blocks, so the result is identical for any value; each extra process costs a start-up of about a second, so it pays off only when there are many patterns or the MPS is large. Transition amplitudes are evaluated in this process.
- Returns:
The
NoisyExpectation.
Example:
from qibo import Circuit, gates from mpstab import HSMPO from mpstab.models.noise.compile import compile_noise from mpstab.models.noise.mc_noise_estimator import noisy_expectation from mpstab.models.noise.events import PauliChannel circuit = Circuit(2) circuit.add(gates.RY(0, theta=0.4)) circuit.add(gates.CNOT(0, 1)) events = [ PauliChannel(after_gate=g, qubits=(0, 1), probs={"XX": 0.02, "ZI": 0.01}) for g in range(2) ] compiled = compile_noise(HSMPO(circuit), events) result = noisy_expectation(compiled, "ZZ", n_samples=200, seed=0) print(f"{result.mean:.4f} +- {result.stderr:.4f}")
The Pauli noise simulation tutorial compares these values against an exact density-matrix simulation.