Noisy simulations on MIMIQ¶
This page provides detailed information on simulating noise in quantum circuits using MIMIQ.
Summary of noise functionality¶
Custom noise channels:
KrausMixedUnitary
Specialized noise channels:
DepolarizingDepolarizing1Depolarizing2PauliNoisePauliXPauliYPauliZAmplitudeDampingGeneralizedAmplitudeDampingPhaseAmplitudeDampingThermalNoiseProjectiveNoise
Note that the Reset type operations can also be thought of as noisy operations.
Coherent noise can be added by using any of the supported gates (e.g., Gate).
Noise channels come with the following methods:
krausmatrices()andkrausoperators()unitarymatrices()andunitarygates()(only for mixed-unitary)probabilities()(only for mixed-unitary)ismixedunitary()
To add noise channels to a circuit, you can use:
push()(like gates)add_noise()(to add noise to every instance of a gate)
To generate one sample of a circuit with mixed unitaries, use:
sample_mixedunitaries()
See below for further information. You can also run help(Circuit().sample_mixedunitaries).
Mathematical background¶
Kraus operators¶
Noise in a quantum circuit refers to any kind of unwanted interaction of the qubits with the environment (or with itself). Mathematically, this puts us in the framework of open systems and the state of the qubits now needs to be described in terms of a density matrix \(\rho\), which fulfills \(\rho = \rho^\dagger\) and \(\mathrm{Tr} (\rho) = 1\).
A quantum operation such as noise can then be described using the Kraus operator representation as:
We consider only completely positive and trace-preserving (CPTP) operations. In this case, the Kraus operators \(E_k\) can be any matrix as long as they fulfill the completeness relation:
Note that unitary gates \(U\) just correspond to a single Kraus operator, \(E_1 = U\).
When all Kraus operators are proportional to a unitary matrix, \(E_k = \alpha_k U_k\), this is called a mixed-unitary quantum operation and can be written as:
where \(p_k = |\alpha_k|^2\).
Such operations are easier to implement as we’ll see below.
Remarks:
Unitary gates \(U\) correspond to a single Kraus operator, \(E_1 = U\).
The number of Kraus operators depends on the noise considered.
For a given quantum operation \(\mathcal{E}\), the Kraus operator representation is not unique. One can change the basis of Kraus operators using a unitary matrix \(U\) as \(\tilde{E}_i = \sum_j U_{ij} E_j\).
We define a noise channel (or Kraus channel) as a quantum operation \(\mathcal{E}\) described by a set of Kraus operators as given above. A common way of modeling noisy quantum computers is by considering each operation \(O\) in the circuit as a noisy quantum operation \(\mathcal{E}_O\).
Evolution with noise¶
There are two common ways to evolve the state of the system when acting with Kraus channels:
Density matrix: If we use a density matrix to describe the qubits, then a Kraus channel can simply be applied by directly performing the matrix multiplications as:
\[\mathcal{E}(\rho) = \sum_k E_k \rho E_k^\dagger.\]The advantage of this approach is that the density matrix contains the full information of the system and we only need to run the circuit once. The disadvantage is that \(\rho\) requires more memory to be stored (\(2^{2N}\) as opposed to \(2^N\) for a state vector), so we can simulate fewer qubits.
Quantum trajectories: This method consists in simulating the evolution of the state vector \(|\psi_\alpha \rangle\) for a set of iterations \(\alpha = 1, \ldots, n\). In each iteration, a noise channel is applied by randomly selecting one of the Kraus operators according to some probabilities (see below) and applying that Kraus operator to the state vector. The advantage of this approach is that we need less memory since we work with a state vector. The disadvantage is that we need to run the circuit many times to collect samples (one sample per run).
Currently, MIMIQ only implements the quantum trajectories method.
The basis for quantum trajectories is that a Kraus channel can be rewritten as:
where \(p_k = \mathrm{Tr}(E_k \rho E_k^\dagger)\) and \(\tilde{E}_k = E_k / \sqrt{p_k}\).
The parameters \(p_k\) can be interpreted as probabilities since they fulfill \(0 \leq p_k \leq 1\) and \(\sum_k p_k = 1\). In this way, the Kraus channel can be viewed as a linear combination of operations with different Kraus operators weighted by the probabilities \(p_k\).
Note that the probabilities \(p_k\) generally depend on the state, so they need to be computed at runtime. The exception is mixed-unitary channels, for which the probabilities are fixed (state-independent).
Building noise channels¶
You can create noise channels using one of the many functions available. Most noise channels take one or more parameters, and custom channels require passing the Kraus matrices and/or probabilities. Here are some examples of how to build noise channels:
>>> p = 0.1 # probability
>>> PauliX(p)
PauliX(0.1)
>>> p, gamma = 0.1, 0.2 # parameters
>>> GeneralizedAmplitudeDamping(p, gamma)
GeneralizedAmplitudeDamping((0.1, 0.2))
>>> ps = [0.8, 0.1, 0.1] # probabilities
>>> paulis = ["II", "XX", "YY"] # Pauli strings
>>> PauliNoise(ps, paulis)
PauliNoise((0.8, pauli"II"), (0.1, pauli"XX"), (0.1, pauli"YY"))
>>> from symengine import *
>>> ps = [0.9, 0.1] # probabilities
>>> unitaries = [Matrix([[1, 0], [0, 1]]), Matrix([[1, 0], [0, -1]])] # unitary matrices
>>> MixedUnitary(ps, unitaries)
MixedUnitary((0.9, "Custom([1 0; 0 1])"), (0.1, "Custom([1 0; 0 -1])"))
>>> kmatrices = [Matrix([[1, 0], [0, (0.9)**0.5]]), Matrix([[0, (0.1)**0.5], [0, 0]])] # Kraus matrices
>>> Kraus(kmatrices)
Kraus(Operator([[1, 0], [0, 0.948683298050514]]), Operator([[0, 0.316227766016838], [0, 0]]))
Custom Kraus channels
also support
LossyOperator
branches, which makes them loss-aware Kraus channels. For more information, see
Loss-Aware Kraus Channels.
Check the documentation for each noise channel to understand the conditions that each parameter needs to fulfill for the noise channel to be valid.
In MIMIQ, the most important distinction between noise channels is whether they are mixed-unitary or general Kraus channels. You can use ismixedunitary() to check if a channel is mixed unitary:
>>> PauliX(0.1).ismixedunitary()
True
>>> AmplitudeDamping(0.1).ismixedunitary()
False
You can retrieve the Kraus matrices/operators used to define a given channel using krausmatrices() or krausoperators(). For example:
>>> ProjectiveNoise("Z").krausmatrices()
[[1.0, 0]
[0, 0]
, [0, 0]
[0, 1.0]
]
For mixed unitary channels, you can obtain the list of probabilities and the list of unitary gates/matrices separately using probabilities(), unitarymatrices(), or unitarygates(), respectively:
>>> PauliZ(0.1).unitarymatrices()
[[1.0, 0]
[0, 1.0]
, [1.0, 0]
[0, -1.0]
]
>>> Depolarizing1(0.1).unitarygates()
[I, X, Y, Z]
>>> PauliNoise([0.1, 0.9], ["II", "ZZ"]).probabilities()
[0.1, 0.9]
In MIMIQ, noise channels can be added at any point in a circuit to make any operation noisy. For noisy gates, one would normally add a noise channel after an ideal gate. To model measurement, preparation, and reset errors, noise channels can be added before and/or after the corresponding operation. More information can be found in the next section.
How to add noise¶
Adding noise one by one¶
The simplest and most flexible way to add noise to a circuit is by using the push() method, similar to how gates are added. Here’s an example of how to create a noisy 5-qubit GHZ circuit:
>>> c = Circuit()
>>> c.push(PauliX(0.1), [1, 2, 3, 4, 5]) # preparation/reset error since all qubits start in 0
6-qubit circuit with 5 instructions:
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
└── PauliX(0.1) @ q[5]
>>> c.push(GateH(), 1)
6-qubit circuit with 6 instructions:
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
├── PauliX(0.1) @ q[5]
└── H @ q[1]
>>> c.push(AmplitudeDamping(0.1), 1) # 1-qubit noise for GateH
6-qubit circuit with 7 instructions:
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
├── PauliX(0.1) @ q[5]
├── H @ q[1]
└── AmplitudeDamping(0.1) @ q[1]
>>> c.push(GateCX(), 1, [2, 3, 4, 5])
6-qubit circuit with 11 instructions:
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
├── PauliX(0.1) @ q[5]
├── H @ q[1]
├── AmplitudeDamping(0.1) @ q[1]
├── CX @ q[1], q[2]
├── CX @ q[1], q[3]
├── CX @ q[1], q[4]
└── CX @ q[1], q[5]
>>> c.push(Depolarizing2(0.1), 1, [2, 3, 4, 5]) # 2-qubit noise for GateCX
6-qubit circuit with 15 instructions:
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
├── PauliX(0.1) @ q[5]
├── H @ q[1]
├── AmplitudeDamping(0.1) @ q[1]
├── CX @ q[1], q[2]
├── CX @ q[1], q[3]
├── CX @ q[1], q[4]
├── CX @ q[1], q[5]
├── Depolarizing(0.1) @ q[1:2]
├── Depolarizing(0.1) @ q[1,3]
├── Depolarizing(0.1) @ q[1,4]
└── Depolarizing(0.1) @ q[1,5]
>>> c.push(PauliX(0.1), [1, 2, 3, 4, 5]) # measurement error. Note it's added before the measurement
6-qubit circuit with 20 instructions:
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
├── PauliX(0.1) @ q[5]
├── H @ q[1]
├── AmplitudeDamping(0.1) @ q[1]
├── CX @ q[1], q[2]
├── CX @ q[1], q[3]
├── CX @ q[1], q[4]
├── CX @ q[1], q[5]
├── Depolarizing(0.1) @ q[1:2]
├── Depolarizing(0.1) @ q[1,3]
├── Depolarizing(0.1) @ q[1,4]
├── Depolarizing(0.1) @ q[1,5]
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
└── PauliX(0.1) @ q[5]
>>> c=c.push(Measure(), [1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
>>> print(c)
6-qubit, 6-bit circuit with 25 instructions:
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
├── PauliX(0.1) @ q[5]
├── H @ q[1]
├── AmplitudeDamping(0.1) @ q[1]
├── CX @ q[1], q[2]
├── CX @ q[1], q[3]
├── CX @ q[1], q[4]
├── CX @ q[1], q[5]
├── Depolarizing(0.1) @ q[1:2]
├── Depolarizing(0.1) @ q[1,3]
├── Depolarizing(0.1) @ q[1,4]
├── Depolarizing(0.1) @ q[1,5]
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
├── PauliX(0.1) @ q[5]
├── M @ q[1], c[1]
├── M @ q[2], c[2]
├── M @ q[3], c[3]
├── M @ q[4], c[4]
└── M @ q[5], c[5]
Note how bit-flip error (PauliX) is added at the beginning for state preparation/reset errors and right before measuring for measurement errors.
Adding noise to all gates of the same type¶
Usually, when adding noise to a circuit, the same type of noise is added to each instance of a given gate. Instead of adding noise channels one by one, you can use add_noise(). It takes several parameters:
Circuit().add_noise(gate, kraus, before=False, parallel=False)
This function adds the noise channel specified by kraus to every instance of the gate g in the circuit circuit. The optional parameter before determines whether to add the noise before or after the operation, and parallel determines whether to add the noise in parallel after/before a block of transversal gates.
Here’s the same noisy GHZ circuit, using add_noise():
>>> cnoise = c.add_noise(Reset(), PauliX(0.1), parallel=True)
>>> cnoise.add_noise(GateH(), AmplitudeDamping(0.1))
6-qubit, 6-bit circuit with 21 instructions:
├── Reset @ q[1]
├── Reset @ q[2]
├── Reset @ q[3]
├── Reset @ q[4]
├── Reset @ q[5]
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
├── PauliX(0.1) @ q[5]
├── H @ q[1]
├── AmplitudeDamping(0.1) @ q[1]
├── CX @ q[1], q[2]
├── CX @ q[1], q[3]
├── CX @ q[1], q[4]
├── CX @ q[1], q[5]
├── M @ q[1], c[1]
├── M @ q[2], c[2]
├── M @ q[3], c[3]
⋮ ⋮
└── M @ q[5], c[5]
>>> cnoise.add_noise(GateCX(), Depolarizing2(0.1), parallel=True)
6-qubit, 6-bit circuit with 25 instructions:
├── Reset @ q[1]
├── Reset @ q[2]
├── Reset @ q[3]
├── Reset @ q[4]
├── Reset @ q[5]
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
├── PauliX(0.1) @ q[5]
├── H @ q[1]
├── AmplitudeDamping(0.1) @ q[1]
├── CX @ q[1], q[2]
├── Depolarizing(0.1) @ q[1:2]
├── CX @ q[1], q[3]
├── Depolarizing(0.1) @ q[1,3]
├── CX @ q[1], q[4]
├── Depolarizing(0.1) @ q[1,4]
├── CX @ q[1], q[5]
⋮ ⋮
└── M @ q[5], c[5]
>>> cnoise.add_noise(Measure(), PauliX(0.1), before=True, parallel=True)
6-qubit, 6-bit circuit with 30 instructions:
├── Reset @ q[1]
├── Reset @ q[2]
├── Reset @ q[3]
├── Reset @ q[4]
├── Reset @ q[5]
├── PauliX(0.1) @ q[1]
├── PauliX(0.1) @ q[2]
├── PauliX(0.1) @ q[3]
├── PauliX(0.1) @ q[4]
├── PauliX(0.1) @ q[5]
├── H @ q[1]
├── AmplitudeDamping(0.1) @ q[1]
├── CX @ q[1], q[2]
├── Depolarizing(0.1) @ q[1:2]
├── CX @ q[1], q[3]
├── Depolarizing(0.1) @ q[1,3]
├── CX @ q[1], q[4]
├── Depolarizing(0.1) @ q[1,4]
├── CX @ q[1], q[5]
⋮ ⋮
└── M @ q[5], c[5]
Running a noisy circuit¶
Circuits with noise can be run using the submit() function,
just as with circuits without noise. Currently, noisy simulations are run using the quantum trajectories
method. In this case, when running a circuit with noise for n samples, the circuit will internally be
run once for each sample, with a different set of random Kraus operators selected based on the
corresponding probabilities.
When the noise channel is a mixed-unitary channel, the unitary operators to be applied can be selected
before applying the operations on the state. Use the sample_mixedunitaries()
function to generate samples of a circuit with mixed-unitary noise:
>>> from mimiqcircuits import *
>>> import random
>>> rng = random.Random(42)
>>> c = Circuit()
>>> c.push(Depolarizing1(0.5), [1, 2, 3, 4, 5])
6-qubit circuit with 5 instructions:
├── Depolarizing(0.5) @ q[1]
├── Depolarizing(0.5) @ q[2]
├── Depolarizing(0.5) @ q[3]
├── Depolarizing(0.5) @ q[4]
└── Depolarizing(0.5) @ q[5]
# Produce a circuit with either I, X, Y, or Z in place of each depolarizing channel
>>> c.sample_mixedunitaries(rng=rng, ids=True)
6-qubit circuit with 5 instructions:
├── X @ q[1]
├── I @ q[2]
├── I @ q[3]
├── I @ q[4]
└── Y @ q[5]
This function is called internally when executing a circuit, but it can also be used separately.
Noise Models¶
In addition to adding noise directly to the circuit, MIMIQ provides a Noise Model framework. A NoiseModel is a collection of “noise rules” that define how noise should be applied to a circuit. This allows you to define a noise profile once and apply it to multiple circuits.
Building a Noise Model¶
A noise model is essentially a container for rules. You can create an empty noise model and add rules to it.
model = NoiseModel(name="My Noise Model")
The recommended way to add rules is using the helper methods:
add_operation_noise()add_readout_noise()add_idle_noise()
Operation Noise¶
Use add_operation_noise to add noise to specific operations (gates, measurements, resets, etc.). You can specify the operation type (or a symbolic pattern for gates), the noise channel, and optionally specific qubits.
# Add noise to all Hadamard gates
model.add_operation_noise(GateH(), Depolarizing1(0.001))
# Add noise to CX gates only on qubits [1, 2]
model.add_operation_noise(GateCX(), Depolarizing2(0.01), qubits=[1, 2], exact=True)
# Add noise to any CX gate involving qubits in set {1, 2, 3}
model.add_operation_noise(GateCX(), Depolarizing2(0.005), qubits=[1, 2, 3], exact=False)
# Add noise before measurements
model.add_operation_noise(Measure(), PauliX(0.02), before=True)
# Add noise after resets
model.add_operation_noise(Reset(), Depolarizing1(0.01))
# Replace an operation with noise (e.g., replace a gate with a noise channel)
model.add_operation_noise(GateH(), AmplitudeDamping(0.001), replace=True)
Readout Noise¶
Use add_readout_noise to add noise to measurements.
# Global readout error
model.add_readout_noise(ReadoutErr(0.01, 0.02))
# Readout error only on qubit 1
model.add_readout_noise(ReadoutErr(0.05, 0.05), qubits=[1])
Idle Noise¶
Use add_idle_noise to add noise to idle qubits (during Delay operations).
# Constant idle noise
model.add_idle_noise(AmplitudeDamping(0.0001))
# Time-dependent idle noise (using symbolic variable t)
from symengine import Symbol
t = Symbol("t")
model.add_idle_noise(t, AmplitudeDamping(t / 1000.0))
Applying a Noise Model¶
Once you have defined a noise model, you can apply it to a circuit using apply_noise_model(). This will return a new circuit with the noise instructions inserted.
noisy_circuit = apply_noise_model(circuit, model)
Adding Rules Directly¶
While helper functions are convenient, you can also add rules directly to the model using add_rule(). This gives you full control over the rule parameters.
model.add_rule(GlobalReadoutNoise(ReadoutErr(0.01, 0.01)))
Available Rules¶
Here is a list of the available noise rules. Each rule matches a specific condition in the circuit.
Readout Noise
GlobalReadoutNoise: Applies noise to all measurements.SetQubitReadoutNoise: Applies noise to measurements on any qubit in a given set.ExactQubitReadoutNoise: Applies noise to measurements on a specific sequence of qubits (sensitive to order).
Operation Noise
OperationInstanceNoise: Applies noise to all instances of a specific operation type (e.g., allCXgates, all measurements, all resets).SetOperationInstanceQubitNoise: Applies noise to operations acting on qubits within a given set.ExactOperationInstanceQubitNoise: Applies noise to operations acting on a specific sequence of qubits.
Idle Noise
IdleNoise: Applies noise to idle qubits duringDelayinstructions.SetIdleQubitNoise: Applies idle noise only to specific qubits.
Custom Rules
CustomNoiseRule: User-defined rule with custom matching and noise generation logic. Has the highest priority by default.
# Custom rule with user-defined matching and generation functions
rule = CustomNoiseRule(
matcher=lambda inst: isinstance(inst.get_operation(), GateH),
generator=lambda inst: Instruction(AmplitudeDamping(0.01), tuple(inst.get_qubits())),
priority_val=0, # highest priority (default)
)
model.add_rule(rule)
Saving and Loading¶
Noise models can be saved to and loaded from disk using the protobuf format. This allows sharing models between Python and Julia.
# Save to a file
model.saveproto("noise_model.pb")
# Load from a file
loaded_model = NoiseModel.loadproto("noise_model.pb")
Reference¶
- class NoiseModel(rules=<factory>, name='')[source]
Bases:
objectCollection of noise rules applied to circuits.
apply_noise_model()goes through a circuit and gives each instruction to the rules in order; the first rule that matches adds its noise (after the instruction, before it, or in its place) and the others are skipped. Instructions that no rule matches are kept as they are.Rules are kept sorted by
priority(), lower first, and rules of equal priority keep the order they were added in. The built-in rules make specific rules win over general ones:Rule
Priority
CustomNoiseRule(default)0
ExactOperationInstanceQubitNoise40
ExactQubitReadoutNoise50
SetOperationInstanceQubitNoise60
SetQubitReadoutNoise70
OperationInstanceNoise80
GlobalReadoutNoise90
SetIdleQubitNoise190
IdleNoise200
The
add_*methods build these rules for you and return the model, so calls can be chained.- Parameters:
rules (List[AbstractNoiseRule]) – Initial rules. The list is sorted in place.
name (str) – Name shown by
describe().
Examples
>>> from mimiqcircuits import * >>> from symengine import symbols, pi >>> theta = symbols("theta") >>> model = NoiseModel(name="demo") >>> # RX(theta) is followed by depolarizing noise of strength theta/pi >>> _ = model.add_operation_noise(GateRX(theta), Depolarizing1(theta / pi)) >>> # every CX is followed by two-qubit depolarizing noise >>> _ = model.add_operation_noise(GateCX(), Depolarizing2(0.01)) >>> # every measured bit gets a readout error >>> _ = model.add_readout_noise(ReadoutErr(0.01, 0.02)) >>> # every Delay becomes amplitude damping >>> _ = model.add_idle_noise(AmplitudeDamping(0.001)) >>> c = Circuit() >>> _ = c.push(GateRX(0.4), 0) >>> _ = c.push(GateCX(), 0, 1) >>> _ = c.push(Delay(5), 1) >>> _ = c.push(Measure(), 0, 0) >>> model.apply_noise_model(c) 2-qubit, 1-bit circuit with 7 instructions: ├── RX(0.4) @ q[0] ├── Depolarizing(0.4/pi) @ q[0] ├── CX @ q[0], q[1] ├── Depolarizing(0.01) @ q[0:1] ├── AmplitudeDamping(0.001) @ q[1] ├── M @ q[0], c[0] └── RErr(0.01, 0.02) @ c[0]
>>> # rules can also be given directly >>> model = NoiseModel( ... [ ... ExactOperationInstanceQubitNoise(GateCX(), [0, 1], Depolarizing(2, 0.01)), ... GlobalReadoutNoise(ReadoutErr(0.01, 0.02)), ... ], ... name="explicit", ... )
- add_rule(rule)[source]
Add a rule and return the model.
The rule is placed after the existing rules of the same priority.
- Parameters:
rule (AbstractNoiseRule) – Any
AbstractNoiseRule.- Returns:
This model, changed in place.
- Return type:
- add_readout_noise(noise, *, qubits=None, exact=False)[source]
Add a rule that puts a readout error after measurements.
Without
qubitsthe rule is aGlobalReadoutNoise. Withqubitsit is aSetQubitReadoutNoise, or anExactQubitReadoutNoisewhenexactisTrue.- Parameters:
noise (ReadoutErr) – Readout error to add.
qubits – Keyword-only. Restrict the rule to measurements on these qubits.
exact – Keyword-only. Require the measured qubits to equal
qubits, in order, instead of being a subset of them.
- Returns:
This model, changed in place.
- Return type:
- Raises:
ValueError – If
qubitsis empty or has repetitions.
Examples
>>> from mimiqcircuits import * >>> model = NoiseModel() >>> # all measurements >>> model.add_readout_noise(ReadoutErr(0.01, 0.02)) NoiseModel(rules=[GlobalReadoutNoise(noise=RErr(0.01,0.02))], name='') >>> # measurements on qubits 0 and 2 only; tried before the global rule >>> model.add_readout_noise(ReadoutErr(0.03, 0.04), qubits=[0, 2]) NoiseModel(rules=[SetQubitReadoutNoise(qubits=(0, 2), noise=RErr(0.03,0.04)), GlobalReadoutNoise(noise=RErr(0.01,0.02))], name='') >>> # a measurement of exactly (q2, q0); tried first >>> model.add_readout_noise(ReadoutErr(0.05, 0.06), qubits=[2, 0], exact=True) NoiseModel(rules=[ExactQubitReadoutNoise(qubits=(2, 0), noise=RErr(0.05,0.06)), SetQubitReadoutNoise(qubits=(0, 2), noise=RErr(0.03,0.04)), GlobalReadoutNoise(noise=RErr(0.01,0.02))], name='')
- add_operation_noise(operation, noise, *, qubits=None, exact=False, before=False, replace=False)[source]
Add a rule that puts noise next to an operation.
Without
qubitsthe rule is anOperationInstanceNoise. Withqubitsit is aSetOperationInstanceQubitNoise, or anExactOperationInstanceQubitNoisewhenexactisTrue.A concrete
operationmatches only equal operations. One with symbolic parameters matches any operation of the same type, and its symbols are replaced innoiseby the values of the matched operation.- Parameters:
operation – Operation pattern: a gate, measurement, reset,
Block,Repeat,IfStatementorWhileStatement.noise – Kraus channel or gate to add, on as many qubits as
operation.qubits – Keyword-only. Restrict the rule to instructions on these qubits.
exact – Keyword-only. Require the instruction’s qubits to equal
qubits, in order, instead of being a subset of them.before – Keyword-only. Add the noise before the operation.
replace – Keyword-only. Replace the operation with the noise.
- Returns:
This model, changed in place.
- Return type:
- Raises:
ValueError – If
operationis not a supported kind,noiseacts on a different number of qubits,qubitsis invalid, or bothbeforeandreplaceare set.
Examples
>>> from mimiqcircuits import * >>> from symengine import symbols, pi >>> theta, alpha, beta = symbols("theta alpha beta") >>> model = NoiseModel() >>> # only RX(pi/2) matches >>> _ = model.add_operation_noise(GateRX(pi / 2), AmplitudeDamping(0.001)) >>> # any RX matches; theta in the noise takes the gate's angle >>> _ = model.add_operation_noise(GateRX(theta), Depolarizing(1, theta / pi)) >>> # several parameters at once >>> _ = model.add_operation_noise( ... GateU(alpha, beta, 0), ... Depolarizing(1, (alpha**2 + beta**2) / (2 * pi**2)), ... ) >>> # restricted to RX on qubits 0, 1 or 2 >>> _ = model.add_operation_noise( ... GateRX(theta), ... Depolarizing(1, theta / pi), ... qubits=[0, 1, 2], ... ) >>> # restricted to RX on exactly qubit 0 >>> _ = model.add_operation_noise( ... GateRX(theta), ... Depolarizing(1, theta / pi), ... qubits=[0], ... exact=True, ... ) >>> # a bit flip just before every measurement >>> _ = model.add_operation_noise(Measure(), PauliX(0.02), before=True) >>> _ = model.add_operation_noise(Reset(), Depolarizing(1, 0.01)) >>> # H is removed and only the noise is left >>> _ = model.add_operation_noise(GateH(), AmplitudeDamping(0.001), replace=True)
- add_idle_noise(noise, qubits=None)[source]
Add a rule that replaces
Delayinstructions with noise.Without
qubitsthe rule is anIdleNoise, otherwise aSetIdleQubitNoise. Only explicitDelayinstructions are affected; qubits that are simply not acted upon get no noise.- Parameters:
noise – A noise operation, or a tuple
(t, noise(t))wheretis a symbol replaced by the duration of eachDelay.qubits – Restrict the rule to delays on these qubits.
- Returns:
This model, changed in place.
- Return type:
- Raises:
ValueError – If
noiseis neither an operation nor a(symbol, operation)tuple, orqubitsis empty.
Examples
>>> from mimiqcircuits import * >>> from symengine import symbols >>> t = symbols("t") >>> model = NoiseModel() >>> # the same noise for every delay >>> model.add_idle_noise(AmplitudeDamping(1e-4)) NoiseModel(rules=[IdleNoise(relation=AmplitudeDamping(0.0001))], name='') >>> # noise depending on the delay duration, on qubits 0 to 2 >>> model.add_idle_noise((t, AmplitudeDamping(t / 1000)), qubits=[0, 1, 2]) NoiseModel(rules=[SetIdleQubitNoise(relation=(t, AmplitudeDamping((1/1000)*t)), qubits=frozenset({0, 1, 2})), IdleNoise(relation=AmplitudeDamping(0.0001))], name='')
- apply_noise_model(circuit)[source]
Return a noisy copy of
circuit; seeapply_noise_model().
- describe()[source]
Print a readable summary of the rules, in the order they are tried.
Examples
>>> from mimiqcircuits import * >>> NoiseModel(name="demo").add_idle_noise(AmplitudeDamping(0.001)).describe() NoiseModel: demo ================================================================================ Rule 1 (priority 200): IdleNoise -> Applies AmplitudeDamping(0.001) to all idle qubits (REPLACES the matched operation) --------------------------------------------------------------------------------
- saveproto(file)[source]
Save the model to a protobuf file.
- Parameters:
file – Path or writable binary file object.
- Raises:
ValueError – If the model contains a
CustomNoiseRule, which cannot be serialized.
- static loadproto(file)[source]
Load a model saved with
saveproto().- Parameters:
file – Path or readable binary file object.
- Returns:
The loaded model.
- Return type:
- apply_noise_model(circuit, model)[source]
Return a copy of
circuitwith the noise ofmodeladded.Each instruction is given to the rules of
modelin priority order, and only the first rule that matches is applied: its noise goes after the instruction, before it, or in its place.circuitis not changed.When no rule matches a wrapper operation, the rules are applied to the operations inside it:
Block,IfStatement,WhileStatement,Parallel,Repeat,GateCallandBlockCall. A wrapper whose content gets noise is turned into aBlock(or keeps its condition, forIfStatementandWhileStatement); one whose content gets none is kept as it is.- Parameters:
circuit (Circuit) – Circuit to make noisy.
model (NoiseModel) – Noise model to apply.
- Returns:
A new circuit with the noise added.
- Return type:
Examples
>>> from mimiqcircuits import * >>> from symengine import symbols, pi >>> theta = symbols("theta") >>> c = Circuit() >>> _ = c.push(GateRX(0.4), 0) >>> _ = c.push(GateRX(0.8), 1) >>> _ = c.push(Measure(), 0, 0) >>> _ = c.push(Measure(), 1, 1) >>> # noise after each RX that depends on its angle, and readout errors >>> model = NoiseModel([ ... OperationInstanceNoise(GateRX(theta), Depolarizing(1, theta / pi)), ... GlobalReadoutNoise(ReadoutErr(0.01, 0.02)), ... ]) >>> apply_noise_model(c, model) 2-qubit, 2-bit circuit with 8 instructions: ├── RX(0.4) @ q[0] ├── Depolarizing(0.4/pi) @ q[0] ├── RX(0.8) @ q[1] ├── Depolarizing(0.8/pi) @ q[1] ├── M @ q[0], c[0] ├── RErr(0.01, 0.02) @ c[0] ├── M @ q[1], c[1] └── RErr(0.01, 0.02) @ c[1]
Noise also reaches operations inside wrappers. Here every
Hgets amplitude damping;decompose_stepopens the wrapper to show it.>>> model = NoiseModel([OperationInstanceNoise(GateH(), AmplitudeDamping(0.01))]) >>> inner = Circuit().push(GateH(), 0) >>> # inside a Block >>> c_block = Circuit().push(Block(inner), 0) >>> apply_noise_model(c_block, model).decompose_step() 1-qubit circuit with 2 instructions: ├── H @ q[0] └── AmplitudeDamping(0.01) @ q[0] >>> # inside a gate declaration call >>> decl = GateDecl("local_h", (), inner) >>> c_call = Circuit().push(GateCall(decl, ()), 0) >>> apply_noise_model(c_call, model).decompose_step() 1-qubit circuit with 2 instructions: ├── H @ q[0] └── AmplitudeDamping(0.01) @ q[0] >>> # each copy of a Parallel gets its own noise >>> c_parallel = Circuit().push(Parallel(2, GateH()), 0, 1) >>> apply_noise_model(c_parallel, model).decompose_step() 2-qubit circuit with 4 instructions: ├── H @ q[0] ├── AmplitudeDamping(0.01) @ q[0] ├── H @ q[1] └── AmplitudeDamping(0.01) @ q[1] >>> # so does each repetition of a Repeat >>> c_repeat = Circuit().push(Repeat(2, GateH()), 0) >>> apply_noise_model(c_repeat, model).decompose_step() 1-qubit circuit with 4 instructions: ├── H @ q[0] ├── AmplitudeDamping(0.01) @ q[0] ├── H @ q[0] └── AmplitudeDamping(0.01) @ q[0] >>> # a conditional gate keeps its condition, and so does its noise >>> c_if = Circuit().push(IfStatement(GateH(), BitString("1")), 0, 0) >>> apply_noise_model(c_if, model).decompose_step() 1-qubit, 1-bit circuit with 2 instructions: ├── IF(c==1) H @ q[0], condition[0] └── IF(c==1) AmplitudeDamping(0.01) @ q[0], condition[0] >>> # nested gate calls are opened at every level >>> decl_inner = GateDecl("inner_h", (), inner) >>> middle = Circuit().push(GateCall(decl_inner, ()), 0) >>> decl_outer = GateDecl("outer_call", (), middle) >>> c_nested = Circuit().push(GateCall(decl_outer, ()), 0).push(GateCall(decl_outer, ()), 1) >>> apply_noise_model(c_nested, model).decompose_step().decompose_step() 2-qubit circuit with 4 instructions: ├── H @ q[0] ├── AmplitudeDamping(0.01) @ q[0] ├── H @ q[1] └── AmplitudeDamping(0.01) @ q[1]
- class Depolarizing1(p)[source]
Bases:
krauschannelSingle-qubit depolarizing channel, shorthand for
Depolarizing(1, p).Calling
Depolarizing1(p)returns aDepolarizinginstance, not aDepolarizing1one.- Parameters:
p (float) – Probability of error, in \([0, 1]\).
Examples
>>> from mimiqcircuits import * >>> # 10% chance of applying X, Y or Z, each with probability 0.1/3 >>> Depolarizing1(0.1) == Depolarizing(1, 0.1) True
- class Depolarizing2(p)[source]
Bases:
krauschannelTwo-qubit depolarizing channel, shorthand for
Depolarizing(2, p).Calling
Depolarizing2(p)returns aDepolarizinginstance, not aDepolarizing2one.- Parameters:
p (float) – Probability of error, in \([0, 1]\).
Examples
>>> from mimiqcircuits import * >>> # 10% chance of one of the 15 non-identity two-qubit Pauli strings >>> Depolarizing2(0.1) == Depolarizing(2, 0.1) True
- class AmplitudeDamping(gamma)[source]
Bases:
krauschannelOne-qubit amplitude damping noise channel.
Models energy relaxation: the excited state \(|1\rangle\) decays to \(|0\rangle\) with probability \(\gamma\). The Kraus operators are
\[\begin{split}E_1 = \begin{pmatrix} 1 & 0 \\ 0 & \sqrt{1-\gamma} \end{pmatrix} ,\quad E_2 = \begin{pmatrix} 0 & \sqrt{\gamma} \\ 0 & 0 \end{pmatrix}.\end{split}\]- Parameters:
gamma (float) – Damping probability, in \([0, 1]\); may be symbolic.
- Raises:
ValueError – If a numeric
gammais outside \([0, 1]\).
See also
GeneralizedAmplitudeDamping,PhaseAmplitudeDampingExamples
>>> from mimiqcircuits import * >>> # |1> decays to |0> with probability 0.1 >>> c = Circuit() >>> c.push(AmplitudeDamping(0.1), 0) 1-qubit circuit with 1 instruction: └── AmplitudeDamping(0.1) @ q[0]
- evaluate(d={})[source]
Return a copy with symbols in
gammasubstituted by values.- Parameters:
d (dict) – Map from symbols to the values to substitute.
- Returns:
A new channel;
gammabecomes a float when it is fully numeric.- Return type:
- Raises:
ValueError – If the substituted
gammais outside \([0, 1]\).
- krausoperators()[source]
Return the Kraus operators \(E_k\) of the channel as operator objects.
Every concrete channel implements this method; the base class raises.
- Returns:
One operator (for example
Operator,DiagonalOporRescaledGate) per Kraus operator.- Return type:
- Raises:
NotImplementedError – When called on a class that does not define it.
Examples
>>> from mimiqcircuits import * >>> # projective noise in Z: project on |0> or on |1> >>> ProjectiveNoise("Z").krausoperators() [P₀(1), P₁(1)]
- krausmatrices()[source]
Return the matrices of the Kraus operators \(E_k\) of the channel.
These are the matrices of
krausoperators(), in the same order. For a parametric channel the entries are symbolic expressions.- Returns:
One symengine matrix per Kraus operator.
- Return type:
Examples
>>> from mimiqcircuits import * >>> AmplitudeDamping(0.36).krausmatrices() [[1.0, 0] [0, 0.8] , [0, 0.6] [0, 0] ]
- iswrapper()[source]
Whether the operation wraps another operation.
Truefor composite operations such asControl,Power,Inverse,ParallelorIfStatement,Falseotherwise.- Returns:
bool
- property parnames
Names of the operation’s parameters, as a tuple of strings.
Read-only: assigning to it raises
ValueError.
- class PauliNoise(p, paulistr)[source]
Bases:
krauschannelN-qubit Pauli noise channel given by probabilities and Pauli strings.
A Pauli channel is defined by
\[\mathcal{E}(\rho) = \sum_k p_k P_k \rho P_k,\]where \(0 \leq p_k \leq 1\) and \(P_k\) are Pauli string operators, defined as tensor products of one-qubit Pauli operators. The probabilities must fulfill \(\sum_k p_k = 1\).
This channel is a mixed unitary channel (see
ismixedunitary()).Depolarizing,PauliX,PauliYandPauliZare special cases of it.- Parameters:
p (List[float | int]) – Probabilities, one per Pauli string. Numeric values must lie in \([0, 1]\) and add up to 1; the checks are skipped when any value is symbolic.
paulistr (List[str]) – Pauli strings, all of the same length \(N\), made of the characters
"I","X","Y"and"Z". \(N\) is the number of qubits of the channel.
- Raises:
ValueError – If
paulistris empty, the two lists have different lengths, the strings have different lengths or are not valid Pauli strings, or the numeric probabilities are out of range or do not add up to 1.
See also
Depolarizing,PauliX,PauliY,PauliZ,PauliStringExamples
>>> from mimiqcircuits import * >>> # one qubit: identity with probability 0.8, X or Y with 0.1 each >>> c = Circuit() >>> c.push(PauliNoise([0.8, 0.1, 0.1], ["I", "X", "Y"]), 1) 2-qubit circuit with 1 instruction: └── PauliNoise((0.8, pauli"I"), (0.1, pauli"X"), (0.1, pauli"Y")) @ q[1]
>>> # two qubits: XY with probability 0.9, nothing with 0.1 >>> c.push(PauliNoise([0.9, 0.1], ["XY", "II"]), 1, 2) 3-qubit circuit with 2 instructions: ├── PauliNoise((0.8, pauli"I"), (0.1, pauli"X"), (0.1, pauli"Y")) @ q[1] └── PauliNoise((0.9, pauli"XY"), (0.1, pauli"II")) @ q[1]
>>> # any number of qubits and of Pauli strings >>> c.push(PauliNoise([0.5, 0.2, 0.2, 0.1], ["IXIX", "XYXY", "ZZZZ", "IXYZ"]), 1, 2, 3, 4) 5-qubit circuit with 3 instructions: ├── PauliNoise((0.8, pauli"I"), (0.1, pauli"X"), (0.1, pauli"Y")) @ q[1] ├── PauliNoise((0.9, pauli"XY"), (0.1, pauli"II")) @ q[1] └── PauliNoise((0.5, pauli"IXIX"), (0.2, pauli"XYXY"), (0.2, pauli"ZZZZ"), (0.1, pauli"IXYZ")) @ q[1]
- property num_qubits
Number of qubits the operation acts on.
Read-only: assigning to it raises
ValueError.
- property parnames
Names of the operation’s parameters, as a tuple of strings.
Read-only: assigning to it raises
ValueError.
- evaluate(d={})[source]
Return a copy with symbols in the probabilities substituted by values.
- Parameters:
d (dict) – Map from symbols to the values to substitute.
- Returns:
A new channel with the same Pauli strings.
- Return type:
- Raises:
ValueError – If a substituted probability is outside \([0, 1]\) or the probabilities are all numeric and do not add up to 1.
- krausmatrices()[source]
Return the matrices of the Kraus operators \(E_k\) of the channel.
These are the matrices of
krausoperators(), in the same order. For a parametric channel the entries are symbolic expressions.- Returns:
One symengine matrix per Kraus operator.
- Return type:
Examples
>>> from mimiqcircuits import * >>> AmplitudeDamping(0.36).krausmatrices() [[1.0, 0] [0, 0.8] , [0, 0.6] [0, 0] ]
- krausoperators()[source]
Return the Kraus operators \(E_k\) of the channel as operator objects.
Every concrete channel implements this method; the base class raises.
- Returns:
One operator (for example
Operator,DiagonalOporRescaledGate) per Kraus operator.- Return type:
- Raises:
NotImplementedError – When called on a class that does not define it.
Examples
>>> from mimiqcircuits import * >>> # projective noise in Z: project on |0> or on |1> >>> ProjectiveNoise("Z").krausoperators() [P₀(1), P₁(1)]
- probabilities()[source]
Return the probabilities \(p_k\) of a mixed unitary channel.
For \(\mathcal{E}(\rho) = \sum_k p_k U_k \rho U_k^\dagger\) this is the list of \(p_k\), in the same order as
unitarygates().- Returns:
One probability per unitary.
- Return type:
- Raises:
ValueError – If the channel is not mixed unitary.
Examples
>>> from mimiqcircuits import * >>> # identity with probability 0.9, X with probability 0.1 >>> PauliX(0.1).probabilities() [0.9, 0.1]
- unitarymatrices()[source]
Return the matrices of the unitaries \(U_k\) of a mixed unitary channel.
For \(\mathcal{E}(\rho) = \sum_k p_k U_k \rho U_k^\dagger\) these are the matrices of
unitarygates(), in the same order asprobabilities(). For a parametric channel the entries are symbolic expressions.- Returns:
One symengine matrix per unitary.
- Return type:
- Raises:
ValueError – If the channel is not mixed unitary.
See also
ismixedunitary(),probabilities(),krausmatrices()Examples
>>> from mimiqcircuits import * >>> # identity and Pauli X >>> PauliX(0.2).unitarymatrices() [[1.0, 0] [0, 1.0] , [0, 1.0] [1.0, 0] ]
- unitarygates()[source]
Return the unitaries \(U_k\) of a mixed unitary channel as gates.
For \(\mathcal{E}(\rho) = \sum_k p_k U_k \rho U_k^\dagger\) these are the \(U_k\), in the same order as
probabilities().- Returns:
One gate per unitary.
- Return type:
- Raises:
ValueError – If the channel is not mixed unitary.
Examples
>>> from mimiqcircuits import * >>> PauliX(0.1).unitarygates() [ID, X]
- classmethod ismixedunitary()[source]
Whether the channel is a mixed unitary channel.
A channel is mixed unitary when every Kraus operator \(E_k\) is proportional to a unitary matrix \(U_k\), so that
\[\mathcal{E}(\rho) = \sum_k p_k U_k \rho U_k^\dagger,\]with probabilities \(0 \leq p_k \leq 1\) that add up to 1. The answer depends only on the channel type, not on its parameters, so this is a class method. Only mixed unitary channels support
probabilities(),cumprobabilities(),unitarygates()andunitarymatrices().- Returns:
Truefor mixed unitary channel types,Falseotherwise.- Return type:
Examples
>>> from mimiqcircuits import * >>> # PauliX applies X with probability p: mixed unitary >>> PauliX(0.1).ismixedunitary() True
>>> # amplitude damping has a non-unitary Kraus operator >>> AmplitudeDamping(0.1).ismixedunitary() False
- iswrapper()[source]
Whether the operation wraps another operation.
Truefor composite operations such asControl,Power,Inverse,ParallelorIfStatement,Falseotherwise.- Returns:
bool
- unwrappedkrausmatrices()[source]
Return the Kraus matrices of a channel whose parameters all have values.
Returns the same matrices as
krausmatrices(), after checking that every parameter evaluates to a constant.- Returns:
One symengine matrix per Kraus operator.
- Return type:
- Raises:
ValueError – If a parameter is still a free symbol.
See also
krausmatrices()Examples
>>> from mimiqcircuits import * >>> # PauliX(p) has Kraus operators sqrt(1-p) I and sqrt(p) X >>> op = PauliX(0.2) >>> op.unwrappedkrausmatrices() [[0.894427190999916, 0] [0, 0.894427190999916] , [0, 0.447213595499958] [0.447213595499958, 0] ]
- class ReadoutErr(p0, p1=None)[source]
Bases:
OperationClassical readout error on one bit, applied after a measurement.
The operation flips the recorded bit at random: a 0 is reported as 1 with probability \(p_0\) and a 1 is reported as 0 with probability \(p_1\). This is the confusion matrix
\[\begin{split}\begin{pmatrix} P(0 | 0) & P(1 | 0) \\ P(0 | 1) & P(1 | 1) \end{pmatrix} = \begin{pmatrix} 1 - p_0 & p_0 \\ p_1 & 1 - p_1 \end{pmatrix},\end{split}\]where \(P(r | t)\) is the probability of reporting \(r\) when the true outcome is \(t\). The operation targets one classical bit and no qubits.
- Parameters:
p0 – Probability of reporting 1 when the outcome is 0, in \([0, 1]\). It may also be a 2×2 confusion matrix (numpy, sympy or symengine) as above, with
p1omitted; its entries must be numeric, in \([0, 1]\), with rows adding up to 1.p1 – Probability of reporting 0 when the outcome is 1, in \([0, 1]\).
A symbolic
p0orp1is not range checked.- Raises:
TypeError – If
p1is omitted andp0is not a matrix, or the matrix has symbolic entries.ValueError – If the matrix is not 2×2, has entries outside \([0, 1]\) or rows not adding up to 1, or if
p0orp1is outside \([0, 1]\).
Examples
>>> from mimiqcircuits import * >>> # 2% chance to read 1 instead of 0, 3% to read 0 instead of 1 >>> ReadoutErr(0.02, 0.03) RErr(0.02,0.03)
>>> # the same error from its confusion matrix >>> import numpy as np >>> ReadoutErr(np.array([[0.98, 0.02], ... [0.03, 0.97]])) RErr(0.02,0.03)
>>> # apply it to bit 0, where a measurement result is stored >>> c = Circuit() >>> c.push(Measure(), 0, 0) 1-qubit, 1-bit circuit with 1 instruction: └── M @ q[0], c[0] >>> c.push(ReadoutErr(0.01, 0.02), 0) 1-qubit, 1-bit circuit with 2 instructions: ├── M @ q[0], c[0] └── RErr(0.01, 0.02) @ c[0]
See also
NoiseModel.add_readout_noise(), which adds readout errors after measurements.- evaluate(d={})[source]
Return a copy with symbols in
p0andp1substituted by values.- Parameters:
d (dict) – Map from symbols to the values to substitute.
- Returns:
A new operation; a probability becomes a float once no symbol is left in it.
- Return type:
- Raises:
ValueError – If a substituted probability is outside \([0, 1]\).
- matrix()[source]
Return the confusion matrix
[[1 - p0, p0], [p1, 1 - p1]].- Returns:
The 2×2 confusion matrix.
- Return type:
symengine.Matrix
Examples
>>> from mimiqcircuits import * >>> ReadoutErr(0.25, 0.5).matrix() [0.75, 0.25] [0.5, 0.5]
- property parnames
Names of the operation’s parameters, as a tuple of strings.
Read-only: assigning to it raises
ValueError.
- iswrapper()[source]
Whether the operation wraps another operation.
Truefor composite operations such asControl,Power,Inverse,ParallelorIfStatement,Falseotherwise.- Returns:
bool