mimiqcircuits.lossmodel¶
Loss model definitions and qubit-loss sampling.
This module provides the rule system used by lower_losses() (and hence
resolve_losses()) when a circuit instruction touches both lost and
surviving qubits. A LossModel lets users decide whether such an
instruction should be dropped, replaced, decorated, or handled by custom logic.
Examples
>>> from mimiqcircuits import *
>>> # qubit 1 is lost before a CX that also acts on qubit 0
>>> circuit = Circuit()
>>> _ = circuit.push(Loss(), 1)
>>> _ = circuit.push(GateCX(), 0, 1)
>>> # replace the broken CX by depolarizing noise on the surviving qubit
>>> model = LossModel().add_replace(GateCX(), Depolarizing1(0.2))
>>> resolve_losses(circuit, lossmodel=model)
2-qubit circuit with 2 instructions:
├── Lost @ q[1]
└── Depolarizing(0.2) @ q[0]
Functions
|
Rewrite one partially lost instruction according to a loss model. |
|
Lower a circuit with loss operations into one using only primitives. |
|
Fully resolve loss into a runnable, loss-free circuit. |
|
Build a deterministic "what-if" loss scenario from a circuit. |
|
Resolve the random qubit-loss events in a circuit. |
Classes
|
User-defined loss rule. |
|
Keep a matched instruction and add a decoration before or after it. |
|
Drop matched instructions that touch lost qubits. |
|
Ordered collection of loss rules. |
|
Replace a matched instruction with new instructions. |
- class AbstractCircuitRule[source]¶
Bases:
objectBase class for the rules of a
NoiseModelor aLossModel.A rule looks at one instruction at a time.
matches()says whether it applies, andapply_rule()builds what it produces. The model keeps its rules sorted bypriority()and uses the first one that produces something for an instruction.before()andreplaces()say where a noise rule’s output goes relative to the matched instruction.Subclasses must implement
matches()andapply_rule(). Two rules are equal when they have the same type and the same attributes.- priority()[source]¶
Return the priority of the rule. Lower values are tried first.
The default is
100.
- before()[source]¶
Return
Trueif the rule’s output goes before the matched instruction.The default is
False: the output goes after it.
- replaces()[source]¶
Return
Trueif the rule’s output replaces the matched instruction.The default is
False: the matched instruction is kept.
- matches(inst)[source]¶
Return
Trueif the rule applies to the instructioninst.- Raises:
NotImplementedError – Unless a subclass implements it.
- apply_rule(inst)[source]¶
Return what the rule produces for
inst, orNoneif it does not apply.- Raises:
NotImplementedError – Unless a subclass implements it.
- class DropRule(operation=None)[source]¶
Bases:
AbstractCircuitRuleDrop matched instructions that touch lost qubits.
A
DropRuleremoves a partially affected operation without putting anything in its place. Dropping is also what happens when no rule matches; aDropRuleis useful to stop a later rule from matching. Drop rules have priority 0, so aLossModeltries them before any other rule.An operation pattern matches instructions whose operation has the same type and is equal to it. A gate, measurement or reset pattern with symbolic parameters (for example
GateRX(theta)) matches every operation of that type.- Parameters:
operation (Optional[Operation]) – Operation pattern to drop: a gate, measurement, reset,
Block,RepeatorIfStatement. If omitted, the rule matches every instruction.- Raises:
ValueError – If
operationis not one of the supported kinds.
Examples
>>> from mimiqcircuits import * >>> # drop every CX that touches a lost qubit >>> model = LossModel().add_drop(GateCX()) >>> model LossModel (unnamed, 1 rules) └── DropRule(CX)
>>> circuit = Circuit() >>> _ = circuit.push(Loss(), 1) >>> _ = circuit.push(GateCX(), 0, 1) >>> circuit.resolve_losses(lossmodel=model) 2-qubit circuit with 1 instruction: └── Lost @ q[1]
- priority()[source]¶
Return the priority of the rule. Lower values are tried first.
The default is
100.
- matches(inst)[source]¶
Return
Trueif the rule applies to the instructioninst.- Raises:
NotImplementedError – Unless a subclass implements it.
- replaces()[source]¶
Return
Trueif the rule’s output replaces the matched instruction.The default is
False: the matched instruction is kept.
- apply_rule(inst)[source]¶
Return what the rule produces for
inst, orNoneif it does not apply.- Raises:
NotImplementedError – Unless a subclass implements it.
- class DecorateRule(operation, decoration=None, *, before=False)[source]¶
Bases:
AbstractCircuitRuleKeep a matched instruction and add a decoration before or after it.
When the loss model rewrites an instruction, every resulting instruction that still touches a lost qubit is removed, and that includes the matched instruction itself. What remains is the decoration on the surviving qubits, which models a side effect of an operation attempted with a qubit missing.
The decoration is either an operation or a sequence of instructions (a list,
CircuitorBlock). An operation with as many qubits asoperationis applied to the same targets; a one-qubit operation is applied to each target. Instructions use the local qubit indices0toN-1of the matched operation.- Parameters:
operation – Operation pattern to match (see
DropRule). The pair(operation, decoration)may also be passed as a single tuple.decoration – Operation or instruction sequence to add.
before (bool) – Keyword-only. If
True, add the decoration before the matched instruction, otherwise after it (default).
- Raises:
TypeError – If
decorationis missing andoperationis not a pair, or the decoration is not an operation or instructions.ValueError – If
operationis not a supported pattern, the decoration targets classical bits or z-variables, or its qubit count or indices do not fitoperation.
Examples
>>> from mimiqcircuits import * >>> # a CZ attempted with a lost partner depolarizes the survivor >>> model = LossModel().add_decorate(GateCZ(), Depolarizing1(0.01), before=True) >>> model LossModel (unnamed, 1 rules) └── DecorateRule(CZ, Depolarizing(0.01), before)
>>> circuit = Circuit() >>> _ = circuit.push(Loss(), 1) >>> _ = circuit.push(GateCZ(), 0, 1) >>> circuit.resolve_losses(lossmodel=model) 2-qubit circuit with 2 instructions: ├── Lost @ q[1] └── Depolarizing(0.01) @ q[0]
- before()[source]¶
Return
Trueif the rule’s output goes before the matched instruction.The default is
False: the output goes after it.
- matches(inst)[source]¶
Return
Trueif the rule applies to the instructioninst.- Raises:
NotImplementedError – Unless a subclass implements it.
- apply_rule(inst)[source]¶
Return what the rule produces for
inst, orNoneif it does not apply.- Raises:
NotImplementedError – Unless a subclass implements it.
- class ReplaceRule(operation, replacement=None)[source]¶
Bases:
AbstractCircuitRuleReplace a matched instruction with new instructions.
Use
ReplaceRulewhen a partially affected operation should be removed and replaced by something acting on the surviving qubits. The replacement follows the same conventions as the decoration ofDecorateRule: an operation with as many qubits asoperationis applied to the same targets, a one-qubit operation is applied to each target, and instructions use local qubit indices0toN-1. Resulting instructions on lost qubits are removed.If
operationhas symbolic parameters, a symbolic replacement can reuse them: the values of the matched operation are substituted in.- Parameters:
operation – Operation pattern to match (see
DropRule). The pair(operation, replacement)may also be passed as a single tuple.replacement – Replacement operation or instruction sequence.
- Raises:
TypeError – If
replacementis missing andoperationis not a pair, or the replacement is not an operation or instructions.ValueError – If
operationis not a supported pattern, the replacement targets classical bits or z-variables, or its qubit count or indices do not fitoperation.
Examples
>>> from mimiqcircuits import * >>> # a CX with a lost qubit becomes depolarizing noise on the survivor >>> model = LossModel().add_replace(GateCX(), Depolarizing1(0.2)) >>> model LossModel (unnamed, 1 rules) └── ReplaceRule(CX => Depolarizing(0.2))
>>> circuit = Circuit() >>> _ = circuit.push(Loss(), 1) >>> _ = circuit.push(GateCX(), 0, 1) >>> circuit.resolve_losses(lossmodel=model) 2-qubit circuit with 2 instructions: ├── Lost @ q[1] └── Depolarizing(0.2) @ q[0]
- matches(inst)[source]¶
Return
Trueif the rule applies to the instructioninst.- Raises:
NotImplementedError – Unless a subclass implements it.
- replaces()[source]¶
Return
Trueif the rule’s output replaces the matched instruction.The default is
False: the matched instruction is kept.
- apply_rule(inst)[source]¶
Return what the rule produces for
inst, orNoneif it does not apply.- Raises:
NotImplementedError – Unless a subclass implements it.
- class CustomRule(matcher, generator)[source]¶
Bases:
AbstractCircuitRuleUser-defined loss rule.
CustomRuleis the escape hatch for loss policies that cannot be expressed withDropRule,ReplaceRule, orDecorateRule. The matcher decides whether the rule applies. The generator returnsNoneto drop the instruction, oneInstruction, or a sequence of instructions.The generator may accept
(inst),(inst, lost), or(inst, lost, rng). It may also acceptrngas a keyword argument.lostmaps qubit indices toTruewhen the qubit is lost. A qubit that was never lost is not in the map and a reloaded one maps toFalse, so read it withlost.get(q, False).rngis the random number generator given tolower_losses(). Returned instructions use the circuit’s qubit indices, and any that touch a lost qubit are removed.- Parameters:
matcher – Callable that receives an instruction and returns
Trueif the rule should apply.generator – Callable that returns the instructions to emit instead of the matched one.
Examples
Define a custom fallback for a partially lost
CX. If the control qubit survives, replace the failedCXbyXon the control. If the control is lost, returnNoneto drop the instruction.>>> from mimiqcircuits import * >>> def cx_control_fallback(inst, lost): ... control = inst.get_qubits()[0] ... if lost.get(control, False): ... return None ... return Instruction(GateX(), (control,)) ... >>> model = LossModel([ ... CustomRule( ... lambda inst: isinstance(inst.get_operation(), GateCX), ... cx_control_fallback, ... ) ... ]) >>> model LossModel (unnamed, 1 rules) └── CustomRule(<callable>)
>>> circuit = Circuit() >>> _ = circuit.push(Loss(), 1) >>> _ = circuit.push(GateCX(), 0, 1) >>> circuit.resolve_losses(lossmodel=model) 2-qubit circuit with 2 instructions: ├── Lost @ q[1] └── X @ q[0]
Another custom rule can generate one instruction for each surviving qubit. Here a partially lost
CXbecomesZon every qubit that is still present:>>> model = LossModel([ ... CustomRule( ... lambda inst: isinstance(inst.get_operation(), GateCX), ... lambda inst, lost: [ ... Instruction(GateZ(), (q,)) ... for q in inst.get_qubits() ... if not lost.get(q, False) ... ], ... ) ... ]) >>> circuit.resolve_losses(lossmodel=model) 2-qubit circuit with 2 instructions: ├── Lost @ q[1] └── Z @ q[0]
- matches(inst)[source]¶
Return
Trueif the rule applies to the instructioninst.- Raises:
NotImplementedError – Unless a subclass implements it.
- replaces()[source]¶
Return
Trueif the rule’s output replaces the matched instruction.The default is
False: the matched instruction is kept.
- apply_rule(inst)[source]¶
Return what the rule produces for
inst, orNoneif it does not apply.- Raises:
NotImplementedError – Unless a subclass implements it.
- class LossModel(rules=None, name='')[source]¶
Bases:
objectOrdered collection of loss rules.
A
LossModeltellslower_losses()(and soresolve_losses()) what to do with an instruction that touches both lost and surviving qubits. Instructions that touch only lost qubits are always dropped, and those that touch none are always kept.For each such instruction the rules are tried in order and the first one that matches decides. Rules are ordered by priority, then by insertion order:
DropRulehas priority 0 and all other rules 100, so drop rules come first. When no rule matches, the instruction is dropped, which is also what an empty model does.- Parameters:
rules (Optional[Iterable[AbstractCircuitRule]]) – Rules to start with, each an
AbstractCircuitRule.name (str) – Name shown when the model is printed.
- Raises:
TypeError – If a rule is not an
AbstractCircuitRule.
Examples
>>> from mimiqcircuits import * >>> model = LossModel(name="My Loss Model") >>> model LossModel (My Loss Model, 0 rules)
>>> # the add_* methods return the model, so they can be chained >>> model.add_replace(GateCX(), Depolarizing1(0.2)) LossModel (My Loss Model, 1 rules) └── ReplaceRule(CX => Depolarizing(0.2))
>>> # pass the model when resolving the losses of a circuit >>> circuit = Circuit() >>> _ = circuit.push(Loss(), 1) >>> _ = circuit.push(GateCX(), 0, 1) >>> circuit.resolve_losses(lossmodel=model) 2-qubit circuit with 2 instructions: ├── Lost @ q[1] └── Depolarizing(0.2) @ q[0]
- 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 (AbstractCircuitRule) – Any
AbstractCircuitRule.- Returns:
This model, changed in place.
- Return type:
- Raises:
TypeError – If
ruleis not anAbstractCircuitRule.
- add_replace(operation, replacement=None)[source]¶
Add a
ReplaceRuleand return the model.- Parameters:
operation – Operation pattern to match.
replacement – Operation or instructions to emit instead.
- Returns:
This model, changed in place.
- Return type:
- add_decorate(operation, decoration=None, *, before=False)[source]¶
Add a
DecorateRuleand return the model.
- lower_losses(circuit, rng=None)[source]¶
Run
lower_losses()oncircuitwith this model.
- resolve_losses(circuit, rng=None)[source]¶
Run
resolve_losses()oncircuitwith this model.
- describe()[source]¶
Print a readable summary of the rules, in the order they are tried.
Examples
>>> from mimiqcircuits import * >>> LossModel(name="demo").add_drop(GateCX()).describe() LossModel: demo ================================================== Rule 1: DropRule -> Drop CX when touching lost qubits
- saveproto(file)[source]¶
Save the model to a protobuf file.
- Parameters:
file – Path or writable binary file object.
- Raises:
TypeError – If the model has a
CustomRule, which cannot be saved.
- static loadproto(file)[source]¶
Load a model saved with
saveproto().- Parameters:
file – Path or readable binary file object.
- Returns:
The loaded model.
- Return type:
- sample_losses(circuit, rng=None)[source]¶
Resolve the random qubit-loss events in a circuit.
Each
Loss(p)is drawn: with probabilitypit becomes a certain lossLoss(1.0), otherwise it is removed. Every other operation, includingReload,CheckandMeasureCheck, is kept unchanged. The result is deterministic but still contains loss operations;lower_losses()turns it into a runnable, loss-free circuit, andresolve_losses()does both steps.- Parameters:
circuit (Circuit) – Circuit to sample. It is not changed.
rng – Random number generator with a
random()method, such asrandom.Random(seed). Defaults to a newrandom.Random().
- Returns:
A new circuit with only certain losses left.
- Return type:
- Raises:
TypeError – If
rnghas norandom()method.ValueError – If a loss probability is still symbolic.
Examples
>>> from mimiqcircuits import * >>> import random >>> c = Circuit() >>> _ = c.push(Loss(0.0), 0) # never fires: removed >>> _ = c.push(Loss(1.0), 1) # always fires: kept >>> sample_losses(c, rng=random.Random(1)) 2-qubit circuit with 1 instruction: └── Loss(1.0) @ q[1]
- lower_losses(circuit, rng=None, lossmodel=None)[source]¶
Lower a circuit with loss operations into one using only primitives.
This is the deterministic half of loss resolution. It expects the random
Loss(p)events to be resolved already (seesample_losses()) and treats any remainingLossas a certain loss. Going through the circuit in order and tracking which qubits are lost, it rewrites:Lossinto aLostmarker (nothing if the qubit is already lost);ReloadintoResetand aReloadedmarker;CheckintoSetBit1(present) orSetBit0(lost);MeasureCheckintoMeasureandSetBit1when present, twoSetBit0when lost;a one-qubit measurement of a lost qubit into
SetBit0.
Other instructions are kept if they touch no lost qubit, dropped if they touch only lost qubits, and passed to
lossmodelotherwise.- Parameters:
circuit (Circuit) – Circuit to lower. It is not changed.
rng – Random number generator passed to
CustomRulegenerators. Defaults to a newrandom.Random(). ALossModelpassed in this position is used aslossmodel.lossmodel (LossModel | None) – Rules for instructions touching both lost and present qubits. Defaults to an empty model, which drops them.
- Returns:
A new circuit with no loss operations.
- Return type:
- Raises:
TypeError – If
rnghas norandom()method, or a loss model is given both positionally and aslossmodel.
Examples
>>> from mimiqcircuits import * >>> c = Circuit() >>> _ = c.push(Loss(), 0) >>> _ = c.push(MeasureCheck(), 0, 0, 1) # lost: both bits set to 0 >>> _ = c.push(Reload(), 0) # back to |0>, present again >>> _ = c.push(Check(), 0, 2) # present: bit set to 1 >>> lower_losses(c) 1-qubit, 3-bit circuit with 6 instructions: ├── Lost @ q[0] ├── c[0] = 0 ├── c[1] = 0 ├── Reset @ q[0] ├── Reloaded @ q[0] └── c[2] = 1
- resolve_losses(circuit, rng=None, lossmodel=None)[source]¶
Fully resolve loss into a runnable, loss-free circuit.
It runs
sample_losses()to draw the randomLoss(p)events, thenlower_losses()to rewrite the result into primitives. Each call draws a new loss pattern, so resolve once per shot to sample loss statistics.- Parameters:
circuit (Circuit) – Circuit to resolve. It is not changed.
rng – Random number generator with a
random()method, used for both steps. Defaults to a newrandom.Random(). ALossModelpassed in this position is used aslossmodel.lossmodel (LossModel | None) – Rules for instructions touching both lost and present qubits. Defaults to an empty model, which drops them.
- Returns:
A new circuit with no loss operations.
- Return type:
- Raises:
TypeError – If
rnghas norandom()method, or a loss model is given both positionally and aslossmodel.ValueError – If a loss probability is still symbolic.
Examples
>>> from mimiqcircuits import * >>> # qubit 1 is lost for sure, so the CX touching it is dropped >>> c = Circuit() >>> _ = c.push(Loss(), 1) >>> _ = c.push(GateCX(), 0, 1) >>> resolve_losses(c) 2-qubit circuit with 1 instruction: └── Lost @ q[1]
- sample_loss_scenario(circuit, loss_indices, *, p=1.0, rng=None, lossmodel=None)[source]¶
Build a deterministic “what-if” loss scenario from a circuit.
The selected
mimiqcircuits.Lossinstructions, counted in circuit order (1-based), are forced toLoss(p)while every otherLossis forced toLoss(0.0). The result is then resolved withresolve_losses(), so the returned circuit shows the effect of losing exactly those sites.- Parameters:
circuit (Circuit) – Circuit containing
Lossinstructions. It is not changed.loss_indices – A 1-based index or iterable of indices selecting which
Lossinstructions to force.p (float) – Keyword-only. Probability assigned to the selected sites (default 1.0, a certain loss).
rng – Keyword-only. Random number generator, used when
p < 1and byCustomRulegenerators.lossmodel (LossModel | None) – Keyword-only. Rules for instructions touching both lost and present qubits.
- Returns:
A loss-free circuit for the chosen scenario.
- Return type:
- Raises:
ValueError – If an index is below 1 or beyond the number of
Lossinstructions,pis outside \([0, 1]\), or the circuit has noLossinstruction.
Examples
>>> from mimiqcircuits import * >>> # two possible loss sites; force the second one only >>> circuit = Circuit() >>> _ = circuit.push(Loss(0.2), 0) >>> _ = circuit.push(GateCX(), 0, 1) >>> _ = circuit.push(Loss(0.4), 1) >>> sample_loss_scenario(circuit, 2) 2-qubit circuit with 2 instructions: ├── CX @ q[0], q[1] └── Lost @ q[1]