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

lossmodel_rewrite(inst, lost, model[, rng])

Rewrite one partially lost instruction according to a loss model.

lower_losses(circuit[, rng, lossmodel])

Lower a circuit with loss operations into one using only primitives.

resolve_losses(circuit[, rng, lossmodel])

Fully resolve loss into a runnable, loss-free circuit.

sample_loss_scenario(circuit, loss_indices, *)

Build a deterministic "what-if" loss scenario from a circuit.

sample_losses(circuit[, rng])

Resolve the random qubit-loss events in a circuit.

Classes

CustomRule(matcher, generator)

User-defined loss rule.

DecorateRule(operation[, decoration, before])

Keep a matched instruction and add a decoration before or after it.

DropRule([operation])

Drop matched instructions that touch lost qubits.

LossModel([rules, name])

Ordered collection of loss rules.

ReplaceRule(operation[, replacement])

Replace a matched instruction with new instructions.

class AbstractCircuitRule[source]

Bases: object

Base class for the rules of a NoiseModel or a LossModel.

A rule looks at one instruction at a time. matches() says whether it applies, and apply_rule() builds what it produces. The model keeps its rules sorted by priority() and uses the first one that produces something for an instruction. before() and replaces() say where a noise rule’s output goes relative to the matched instruction.

Subclasses must implement matches() and apply_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 True if the rule’s output goes before the matched instruction.

The default is False: the output goes after it.

replaces()[source]

Return True if the rule’s output replaces the matched instruction.

The default is False: the matched instruction is kept.

matches(inst)[source]

Return True if the rule applies to the instruction inst.

Raises:

NotImplementedError – Unless a subclass implements it.

apply_rule(inst)[source]

Return what the rule produces for inst, or None if it does not apply.

Raises:

NotImplementedError – Unless a subclass implements it.

class DropRule(operation=None)[source]

Bases: AbstractCircuitRule

Drop matched instructions that touch lost qubits.

A DropRule removes a partially affected operation without putting anything in its place. Dropping is also what happens when no rule matches; a DropRule is useful to stop a later rule from matching. Drop rules have priority 0, so a LossModel tries 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, Repeat or IfStatement. If omitted, the rule matches every instruction.

Raises:

ValueError – If operation is 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 True if the rule applies to the instruction inst.

Raises:

NotImplementedError – Unless a subclass implements it.

replaces()[source]

Return True if 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, or None if it does not apply.

Raises:

NotImplementedError – Unless a subclass implements it.

class DecorateRule(operation, decoration=None, *, before=False)[source]

Bases: AbstractCircuitRule

Keep 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, Circuit or Block). An operation with as many qubits as operation is applied to the same targets; a one-qubit operation is applied to each target. Instructions use the local qubit indices 0 to N-1 of 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 decoration is missing and operation is not a pair, or the decoration is not an operation or instructions.

  • ValueError – If operation is not a supported pattern, the decoration targets classical bits or z-variables, or its qubit count or indices do not fit operation.

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 True if the rule’s output goes before the matched instruction.

The default is False: the output goes after it.

matches(inst)[source]

Return True if the rule applies to the instruction inst.

Raises:

NotImplementedError – Unless a subclass implements it.

apply_rule(inst)[source]

Return what the rule produces for inst, or None if it does not apply.

Raises:

NotImplementedError – Unless a subclass implements it.

class ReplaceRule(operation, replacement=None)[source]

Bases: AbstractCircuitRule

Replace a matched instruction with new instructions.

Use ReplaceRule when 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 of DecorateRule: an operation with as many qubits as operation is applied to the same targets, a one-qubit operation is applied to each target, and instructions use local qubit indices 0 to N-1. Resulting instructions on lost qubits are removed.

If operation has 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 replacement is missing and operation is not a pair, or the replacement is not an operation or instructions.

  • ValueError – If operation is not a supported pattern, the replacement targets classical bits or z-variables, or its qubit count or indices do not fit operation.

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 True if the rule applies to the instruction inst.

Raises:

NotImplementedError – Unless a subclass implements it.

replaces()[source]

Return True if 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, or None if it does not apply.

Raises:

NotImplementedError – Unless a subclass implements it.

class CustomRule(matcher, generator)[source]

Bases: AbstractCircuitRule

User-defined loss rule.

CustomRule is the escape hatch for loss policies that cannot be expressed with DropRule, ReplaceRule, or DecorateRule. The matcher decides whether the rule applies. The generator returns None to drop the instruction, one Instruction, or a sequence of instructions.

The generator may accept (inst), (inst, lost), or (inst, lost, rng). It may also accept rng as a keyword argument. lost maps qubit indices to True when the qubit is lost. A qubit that was never lost is not in the map and a reloaded one maps to False, so read it with lost.get(q, False). rng is the random number generator given to lower_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 True if 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 failed CX by X on the control. If the control is lost, return None to 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 CX becomes Z on 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 True if the rule applies to the instruction inst.

Raises:

NotImplementedError – Unless a subclass implements it.

replaces()[source]

Return True if 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, or None if it does not apply.

Raises:

NotImplementedError – Unless a subclass implements it.

class LossModel(rules=None, name='')[source]

Bases: object

Ordered collection of loss rules.

A LossModel tells lower_losses() (and so resolve_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: DropRule has 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:
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:

LossModel

Raises:

TypeError – If rule is not an AbstractCircuitRule.

add_drop(operation=None)[source]

Add a DropRule and return the model.

Parameters:

operation (Operation | None) – Operation pattern to drop. If omitted, every partially lost instruction is dropped.

Returns:

This model, changed in place.

Return type:

LossModel

add_replace(operation, replacement=None)[source]

Add a ReplaceRule and return the model.

Parameters:
  • operation – Operation pattern to match.

  • replacement – Operation or instructions to emit instead.

Returns:

This model, changed in place.

Return type:

LossModel

add_decorate(operation, decoration=None, *, before=False)[source]

Add a DecorateRule and return the model.

Parameters:
  • operation – Operation pattern to match.

  • decoration – Operation or instructions to add.

  • before (bool) – Add the decoration before the instruction instead of after it.

Returns:

This model, changed in place.

Return type:

LossModel

lower_losses(circuit, rng=None)[source]

Run lower_losses() on circuit with this model.

resolve_losses(circuit, rng=None)[source]

Run resolve_losses() on circuit with 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:

LossModel

sample_losses(circuit, rng=None)[source]

Resolve the random qubit-loss events in a circuit.

Each Loss (p) is drawn: with probability p it becomes a certain loss Loss(1.0), otherwise it is removed. Every other operation, including Reload, Check and MeasureCheck, is kept unchanged. The result is deterministic but still contains loss operations; lower_losses() turns it into a runnable, loss-free circuit, and resolve_losses() does both steps.

Parameters:
  • circuit (Circuit) – Circuit to sample. It is not changed.

  • rng – Random number generator with a random() method, such as random.Random(seed). Defaults to a new random.Random().

Returns:

A new circuit with only certain losses left.

Return type:

Circuit

Raises:
  • TypeError – If rng has no random() 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 (see sample_losses()) and treats any remaining Loss as a certain loss. Going through the circuit in order and tracking which qubits are lost, it rewrites:

  • Loss into a Lost marker (nothing if the qubit is already lost);

  • Reload into Reset and a Reloaded marker;

  • Check into SetBit1 (present) or SetBit0 (lost);

  • MeasureCheck into Measure and SetBit1 when present, two SetBit0 when 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 lossmodel otherwise.

Parameters:
  • circuit (Circuit) – Circuit to lower. It is not changed.

  • rng – Random number generator passed to CustomRule generators. Defaults to a new random.Random(). A LossModel passed in this position is used as lossmodel.

  • 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:

Circuit

Raises:

TypeError – If rng has no random() method, or a loss model is given both positionally and as lossmodel.

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 random Loss(p) events, then lower_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 new random.Random(). A LossModel passed in this position is used as lossmodel.

  • 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:

Circuit

Raises:
  • TypeError – If rng has no random() method, or a loss model is given both positionally and as lossmodel.

  • 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.Loss instructions, counted in circuit order (1-based), are forced to Loss(p) while every other Loss is forced to Loss(0.0). The result is then resolved with resolve_losses(), so the returned circuit shows the effect of losing exactly those sites.

Parameters:
  • circuit (Circuit) – Circuit containing Loss instructions. It is not changed.

  • loss_indices – A 1-based index or iterable of indices selecting which Loss instructions 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 < 1 and by CustomRule generators.

  • 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:

Circuit

Raises:

ValueError – If an index is below 1 or beyond the number of Loss instructions, p is outside \([0, 1]\), or the circuit has no Loss instruction.

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]