mimiqcircuits.backends.backend

Abstract base classes for simulator backends.

This module defines the contract every simulator must satisfy:

See Implementing a Custom Backend for a step-by-step guide.

Classes

Backend()

Abstract base class for every simulator backend.

LocalBackend()

Base class for simulators that run in this process.

LossState(n_or_flags)

Per-qubit register that records which qubits are lost.

RNGs(shot, noise, trajectory, pass_)

Four independent random streams, one per simulation stage.

RemoteBackend()

Base class for simulators that run on a remote service.

State()

Simulation state that a LocalBackend builds and evolves.

class RNGs(shot, noise, trajectory, pass_)[source]

Bases: object

Four independent random streams, one per simulation stage.

Keeping the streams separate means that the draws of one stage (for example sampling) do not shift the draws of another (for example noise selection), even when the same execution uses both. LocalBackend.execute() builds one bundle per call from seed or rng and hands each stream to the stage it belongs to. Build one with from_seed() or from_generator().

shot

Sampling shots from the final state.

Type:

random.Random

noise

Kraus and mixed-unitary noise sampling during LocalBackend.evolve().

Type:

random.Random

trajectory

Per-trajectory work, such as LocalBackend.prepare_trajectory() and loss sampling.

Type:

random.Random

pass_

Randomised compilation passes, read through PassContext.rng.

Type:

random.Random

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import RNGs

The same master seed always gives the same four streams.

>>> a = RNGs.from_seed(42)
>>> b = RNGs.from_seed(42)
>>> a.shot.random() == b.shot.random()
True

Each stream is seeded differently, so they do not repeat each other.

>>> c = RNGs.from_seed(42)
>>> c.shot.random() == c.noise.random()
False
static from_seed(master)[source]

Derive the four streams from one integer seed.

The same seed always gives the same streams. The stream seeds are scrambled from master, so two different master seeds, however close, have no stream in common.

Parameters:

master (int) – The master seed.

Returns:

A new RNGs bundle.

Return type:

RNGs

static from_generator(gen)[source]

Draw a master seed from gen and pass it to from_seed().

This advances gen, so two calls with the same generator give two different bundles.

Parameters:

gen (Random) – The generator to draw a 63-bit master seed from.

Returns:

A new RNGs bundle.

Return type:

RNGs

class State[source]

Bases: ABC

Simulation state that a LocalBackend builds and evolves.

A state bundles three registers: the quantum register, in whatever representation the backend uses (state vector, MPS, tensor network, …); the classical-bit register, written by measurements and classical operations; and the z-register of complex values, written by Amplitude, ExpectationValue and similar operations.

Subclasses implement num_qubits, num_bits, num_zvars, amplitude(), sample(), classical_bits and complex_values; they may override expectation(), reset() and get_loss_state(), whose defaults raise NotImplementedError.

See also

LocalBackend, whose example defines a complete state.

abstract property num_qubits: int

Number of qubits in the quantum register.

abstract property num_bits: int

Number of classical bits in the classical register.

abstract property num_zvars: int

Number of complex values in the z-register.

abstract amplitude(bs)[source]

Return the amplitude ⟨bs|ψ⟩ of a computational basis state.

Parameters:

bs – The basis state, as a BitString with one bit per qubit.

Returns:

The complex amplitude.

Return type:

complex

abstract sample(nsamples, rng=None)[source]

Draw nsamples measurement outcomes of all qubits from the state.

The state is not changed. rng is a generator whose draws seed the simulator’s own generator, which advances it: sampling twice with the same generator gives two independent sets of outcomes. Without rng the simulator draws fresh entropy.

Parameters:
Returns:

A list of nsamples BitString, one bit per qubit.

Return type:

list

expectation(op, *qubits)[source]

Return ⟨ψ|op|ψ⟩ on this state, without changing it.

Most backends compute expectation values on the backend instead, with Backend.expectation(). States whose quantum register can do it directly override this; the default raises NotImplementedError.

Parameters:
  • op – The operator to measure.

  • *qubits (int) – The qubits op acts on, 0-based.

Returns:

The complex expectation value.

Raises:

NotImplementedError – If the state does not support it.

Return type:

complex

abstract property classical_bits

The classical register, as a BitString.

The execute driver stores it as one entry of QCSResults.cstates per trajectory.

abstract property complex_values

The z-register, as a list of complex numbers.

The execute driver stores it as one entry of QCSResults.zstates per evolution.

reset()[source]

Return the state to all qubits in |0⟩, with all registers cleared, in place.

States that can do this override it; the default raises NotImplementedError.

get_loss_state()[source]

Return the per-qubit loss register (see LossState).

States of backends that use the runtime-loss driver (LocalBackend.uses_loss_driver()) hold one, clear it in reset(), and override this to return it. The default raises NotImplementedError.

class LossState(n_or_flags)[source]

Bases: object

Per-qubit register that records which qubits are lost.

It sits next to the quantum, classical and complex registers of a State. Entry q is True when qubit q has left the system. The register holds no loss policy: the runtime-loss driver (LocalBackend.evolve_with_loss()) is the only code that marks qubits; a state that holds one only creates it, clears it in State.reset(), and returns it from State.get_loss_state().

Parameters:

n_or_flags – The number of qubits, all present, or an iterable of booleans giving the initial flag of each qubit.

lost

The flag of each qubit.

Type:

list[bool]

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import LossState

Start with three qubits, all present, then lose qubit 1.

>>> ls = LossState(3)
>>> ls.mark_lost(1)
>>> ls.is_lost(1), ls.any_lost([0, 1]), ls.all_lost([0, 1])
(True, True, False)
>>> ls.reset()
>>> ls.lost
[False, False, False]
is_lost(q)[source]

Return whether qubit q is lost.

mark_lost(q)[source]

Mark qubit q as lost.

mark_present(q)[source]

Mark qubit q as present.

any_lost(qubits)[source]

Return whether at least one of qubits is lost.

all_lost(qubits)[source]

Return whether every one of qubits is lost (True when qubits is empty).

reset()[source]

Mark every qubit as present.

as_map()[source]

Return the lost qubits as a {qubit: True} dictionary.

Present qubits get no entry. This is the form the loss-model rewrite reads.

class Backend[source]

Bases: ABC

Abstract base class for every simulator backend.

Subclasses implement name, version, capabilities() and execute(); they may override limits(), topology(), can_handle(), stochastic_kind(), default_passes(), the pass hooks (fuse_pass(), reorder_pass(), canonical_decompose_pass(), remove_swaps_pass(), simplify_pass()), accepts_pass(), delegates_pass() and expectation().

Most backends subclass one of the two bases below, which implement execute():

  • LocalBackend, when the simulator runs in this process and evolves a State;

  • RemoteBackend, when the simulator runs elsewhere (a cloud service, a job queue) and the backend submits jobs and waits for the results.

See Implementing a Custom Backend for a step-by-step guide.

abstract property name: str

Name of the simulator, such as "Mimiq".

It is stored in QCSResults.simulator and used in error messages.

abstract property version: str

Version string of the simulator, stored in QCSResults.version.

abstract capabilities()[source]

Return the set of features this backend can run.

Each entry is a capability token, normally one of CAPABILITY_VOCABULARY. Declare only what the backend really delivers: can_handle() and the conformance tests rely on it.

Returns:

A set of capability strings.

Return type:

set[str]

limits()[source]

Return the numeric limits of this backend.

The default returns Limits(), with every limit unbounded.

topology()[source]

Return the qubit connectivity of this backend.

The default returns AllToAll.

can_handle(circuit)[source]

Check whether this backend can run circuit.

The default compares circuit with limits() and capabilities(). It returns Inadmissible when the circuit:

  • has more qubits, classical bits or z-variables than max_qubits, max_classical_bits or max_zvars allow;

  • contains a Kraus channel with a LossyOperator (loss decided at run time) and the backend does not declare "loss";

  • contains any Kraus channel, also inside an IfStatement or WhileStatement, and the backend does not declare "noise";

  • has free symbolic parameters and the backend does not declare "parametric".

Otherwise it returns Admissible. It never returns Marginal. Backends with other criteria (bond-dimension estimates, connectivity, gate sets) override it.

Parameters:

circuit – The circuit to check.

Returns:

An AdmissionResult. Use is_admissible() to turn it into a bool.

Return type:

AdmissionResult

stochastic_kind(op_or_instruction)[source]

Classify when this backend resolves the randomness of an operation.

The answer depends on the backend as well as on the operation: a mixed-unitary channel is TrajectorySampleable for a backend that draws its branch before evolving, but RuntimeOnly for one that draws it from the live state. The default returns default_stochastic_kind(); backends that handle an operation differently override this.

Parameters:

op_or_instruction – An operation, or an instruction whose operation is classified.

Returns:

A StochasticKind.

Return type:

StochasticKind

default_passes()[source]

Return the pipeline this backend wants applied before evolution.

This is the backend’s whole part in circuit preparation: it declares the passes it expects, and execute() adjusts that declaration to match the flags the caller set. The backend never sees the flags; when a flag asks for a pass, the backend builds it through fuse_pass(), reorder_pass(), canonical_decompose_pass(), remove_swaps_pass(), simplify_pass() or mapping_pass(). A flag finds the pass it acts on by its spec().name, so a pass that no flag names is never removed by one.

Returns:

A PassPipeline. The default is empty.

Return type:

PassPipeline

fuse_pass(*, threshold=None)[source]

Return the pass that execute(fuse=True) or fuse_threshold=n installs.

Backends with their own fusion pass override this, so the flag retunes that pass instead of replacing it.

Parameters:

threshold (int | None) – The fuse_threshold the caller gave, or None.

Returns:

The default is FusePass with qubit_threshold=threshold (0 for None).

Return type:

AbstractPass

reorder_pass(method=None, *, seed=None)[source]

Return the pass that execute(reorderqubits=...) installs.

Backends that can reorder qubits override this; there is no generic local reorder pass, so the default raises NotImplementedError.

Parameters:
  • method (str | None) – The method name given as reorderqubits, or None for reorderqubits=True, which leaves the choice to the backend.

  • seed (int | None) – The reorderqubits_seed the caller gave, or None.

Returns:

The reorder pass.

Raises:

NotImplementedError – In the default implementation.

Return type:

AbstractPass

canonical_decompose_pass()[source]

Return the pass that execute(canonicaldecompose=True) installs.

The default is CanonicalDecomposePass.

remove_swaps_pass()[source]

Return the pass that execute(remove_swaps=True) installs.

Backends that can remove SWAP gates override this; there is no generic local remove-swaps pass, so the default raises NotImplementedError.

simplify_pass()[source]

Return the pass that execute(simplify=True) installs.

The default is SimplifyPass with DEFAULT_SIMPLIFY_PASSES.

mapping_pass()[source]

Return the pass that maps circuits onto this backend’s topology.

execute() installs it when topology() is not AllToAll, unless mapping=False. Backends with their own mapping override this; the pass should report the spec name "map_circuit" so the mapping flag finds it.

Returns:

The default is MapCircuitPass with no target, which maps onto mapping_target(self.topology()).

Return type:

AbstractPass

accepts_pass(p)[source]

Return whether this backend can run pass p.

apply_passes() raises UnacceptedPassError for a pass the backend refuses, instead of skipping it. The default accepts every pass.

delegates_pass(p)[source]

Return whether this backend runs pass p itself.

For a delegated pass, apply_passes() does not call AbstractPass.apply(); it records a PassResult with metadata={"delegated": True} and leaves the work to the backend’s LocalBackend.compile() or LocalBackend.evolve(). The default delegates nothing.

abstract execute(circuit, *, nsamples=1000, seed=None, rng=None, passes=None, fuse=None, canonicaldecompose=None, reorderqubits=None, remove_swaps=None, simplify=None, reorderqubits_seed=None, mapping=None, callback=None, param_grid=None, strict_pass_order=True)[source]

Run circuit on this backend and return its results.

To request specific amplitudes or expectation values, push Amplitude or ExpectationValue instructions into circuit and read them from results.zstates.

The preparation flags (fuse, canonicaldecompose, reorderqubits, remove_swaps, simplify) adjust the backend’s default_passes() instead of replacing them. Each speaks about one kind of pass: None leaves that pass as the backend declared it, False drops it, and any other value replaces it with the pass the backend builds for that flag, or adds that pass when the backend declared none of that kind. So fuse=False means “the backend’s pipeline, without fusion”. A pass that no flag names stays even when every flag is False.

The flags have a fixed order among themselves: remove swaps, simplify, canonical decompose, mapping, fuse, reorder. A pass added by a flag goes just before the first declared pass of a kind that runs later, or at the end if there is none. passes are appended after all of that, as given; nothing is deduplicated.

On a backend whose topology() is not AllToAll, the circuit is mapped onto the device with mapping_pass() unless mapping=False. When the circuit has no classical bits, bit q of each result still reads logical qubit q, wherever the mapping left it, so the results have the circuit’s width. A circuit with loss is mapped too, before its losses are resolved, so a loss rule that names qubits refers to device sites.

simplify=True rewrites the circuit with simplify_pass() while keeping its unitary exactly: inverse pairs cancel, rotations merge, and one- and two-qubit blocks are resynthesised with fewer gates.

Parameters:
  • circuit – A Circuit or a list of circuits. Local backends also take a SweepExperiment, which runs the circuit once per point of its table.

  • nsamples (int) – Number of shots.

  • seed (int | None) – Integer seed for all randomness of the run. Mutually exclusive with rng; with neither, the backend draws fresh entropy.

  • rng (Random | None) – A random.Random to draw the seed from. It is advanced, so two runs with the same generator differ.

  • passes (PassPipeline | None) – Extra passes to run after the backend’s adjusted pipeline.

  • fuse (bool | None) – Install (True) or drop (False) gate fusion.

  • canonicaldecompose (bool | None) – Install or drop the decomposition into the canonical gate set.

  • reorderqubits (bool | str | None) – Install or drop qubit reordering; a string names the reordering method.

  • remove_swaps (bool | None) – Install or drop SWAP removal.

  • simplify (bool | None) – Install or drop circuit simplification. Off unless set.

  • reorderqubits_seed (int | None) – Seed for the reordering pass. It configures reordering; it does not request it.

  • mapping (bool | None) – Install (True) or drop (False) the mapping onto the backend’s topology. None maps when the topology is not AllToAll.

  • callback – Called by the backend during evolution, once per step.

  • param_grid (list[dict] | None) – A list of dictionaries, each mapping the circuit’s symbols (or their names) to values, such as [{theta: 0.1}, {theta: 0.2}]. Each dictionary is substituted into circuit with evaluate() and runs as its own execution, with a seed derived from seed or rng, so points are independent and a repeated sweep with the same seed gives the same results. Every dictionary must bind all free symbols. An empty list runs circuit once.

  • strict_pass_order (bool) – On a remote backend that does not declare "pass_order_honored", refuse a non-empty passes instead of submitting it as an unordered set.

Returns:

A QCSResults. A list of circuits gives a list of results in the same order; param_grid or a SweepExperiment gives one result per point (a list of such lists for a list of circuits).

Raises:
  • TypeError – If both seed and rng are given, or a flag has the wrong type (for example fuse=0).

  • NotImplementedError – If param_grid is given to a remote backend that does not support it (such as MimiqRemoteBackend), or a flag asks for a pass the backend cannot build.

  • ValueError – If mapping=True on a backend whose topology is AllToAll, or the pipeline holds both a mapping and a reorder pass.

  • RemotePassOrderError – See strict_pass_order.

expectation(state, op, *qubits)[source]

Return ⟨ψ|op|ψ⟩ on state, without changing it.

Backends that declare the "expectation_state" capability override this; the default raises NotImplementedError.

Parameters:
  • state – A State built by this backend.

  • op – The operator to measure.

  • *qubits (int) – The qubits op acts on, 0-based.

Returns:

The complex expectation value.

Raises:

NotImplementedError – In the default implementation.

Return type:

complex

class LocalBackend[source]

Bases: Backend

Base class for simulators that run in this process.

Subclasses implement build_state(), compile() and evolve(), plus the Backend identity members; they may override prepare_trajectory(), recompile_per_trajectory(), bind() and compile_progress(), and opt into the runtime-loss driver with uses_loss_driver(), apply_instruction(), sample_kraus() and apply_segment().

In return they inherit execute(), which runs the pass pipeline, splits the trailing measurements off into a classical projection, and then either evolves the circuit once and samples the final state, or evolves one fresh state per shot when the circuit has mid-circuit measurements, noise, or loss.

Examples

A backend for circuits of X and CX gates only. Its state is a single computational basis state, so it is exact and fully deterministic.

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import (
...     DefaultCompiledCircuit, ExactFidelity, LocalBackend, State)

The state holds the three registers, and samples by returning its basis state nsamples times.

>>> class BasisState(State):
...     def __init__(self, nq, nb, nz):
...         self.qubits = [0] * nq
...         self.bits = [0] * nb
...         self.zvars = [0j] * nz
...     @property
...     def num_qubits(self):
...         return len(self.qubits)
...     @property
...     def num_bits(self):
...         return len(self.bits)
...     @property
...     def num_zvars(self):
...         return len(self.zvars)
...     @property
...     def classical_bits(self):
...         return BitString(self.bits)
...     @property
...     def complex_values(self):
...         return list(self.zvars)
...     def amplitude(self, bs):
...         return 1.0 + 0j if list(bs) == self.qubits else 0j
...     def sample(self, nsamples, rng=None):
...         return [BitString(self.qubits) for _ in range(nsamples)]

The backend declares what it supports, builds states, and evolves them. compile has nothing to lower here, so it wraps the circuit as it is.

>>> class BasisBackend(LocalBackend):
...     @property
...     def name(self):
...         return "Basis"
...     @property
...     def version(self):
...         return "0.1"
...     def capabilities(self):
...         return {"sampling", "classical_bits", "midcircuit_measure"}
...     def build_state(self, nq, nb=0, nz=0, **kwargs):
...         return BasisState(nq, nb, nz)
...     def compile(self, circuit):
...         return DefaultCompiledCircuit(circuit)
...     def evolve(self, state, compiled, *, rng=None, callback=None,
...                stopped=None):
...         for inst in compiled.source:
...             op, qs = inst.operation, inst.qubits
...             if isinstance(op, GateX):
...                 state.qubits[qs[0]] ^= 1
...             elif isinstance(op, GateCX):
...                 state.qubits[qs[1]] ^= state.qubits[qs[0]]
...             elif isinstance(op, Measure):
...                 state.bits[inst.bits[0]] = state.qubits[qs[0]]
...             else:
...                 raise ValueError(f"unsupported operation {op}")
...         return state, ExactFidelity()

execute does the rest. The final measurements never reach evolve: the driver samples the state and maps the samples to the classical register itself.

>>> backend = BasisBackend()
>>> c = Circuit()
>>> c.push(GateX(), 0)
1-qubit circuit with 1 instruction:
└── X @ q[0]

>>> c.push(GateCX(), 0, 1)
2-qubit circuit with 2 instructions:
├── X @ q[0]
└── CX @ q[0], q[1]

>>> c.push(Measure(), range(2), range(2))
2-qubit, 2-bit circuit with 4 instructions:
├── X @ q[0]
├── CX @ q[0], q[1]
├── M @ q[0], c[0]
└── M @ q[1], c[1]

>>> res = backend.execute(c, nsamples=3, seed=1)
>>> res.cstates
[bs"11", bs"11", bs"11"]
>>> res.fidelities
[1.0]

The default can_handle() rejects what the backend does not declare, such as noise.

>>> noisy = Circuit().push(Depolarizing(1, 0.1), 0)
>>> backend.can_handle(noisy)
Inadmissible(reason="circuit contains a noise channel but backend Basis does not declare the 'noise' capability")
abstract build_state(nq, nb=0, nz=0, **kwargs)[source]

Return a new state with every qubit in |0⟩ and every register cleared.

Parameters:
  • nq (int) – Number of qubits.

  • nb (int) – Number of classical bits.

  • nz (int) – Number of z-variables.

  • **kwargs – Backend-specific options. The execute driver passes none.

Returns:

A State of this backend.

Return type:

State

abstract compile(circuit)[source]

Lower a circuit into the form evolve() runs.

Compilation should be pure: it gets no random generator, and a result that samples nothing can be reused across trajectories and parameter points. Per-trajectory randomness belongs in prepare_trajectory(). A backend that does draw random choices while compiling relies on recompile_per_trajectory() to be compiled again for every trajectory.

Parameters:

circuit – The prepared Circuit.

Returns:

A CompiledCircuit. A backend that runs circuits as they are returns DefaultCompiledCircuit(circuit).

Return type:

CompiledCircuit

prepare_trajectory(compiled, rng)[source]

Refresh compiled for one Monte Carlo trajectory.

Backends whose compiled form holds random choices (sampled mixed-unitary branches, …) override this to redraw them. The default returns compiled unchanged.

Parameters:
Returns:

The compiled circuit for this trajectory.

Return type:

CompiledCircuit

abstract evolve(state, compiled, *, rng=None, callback=None, stopped=None)[source]

Apply a compiled circuit to state.

The state can be changed in place and returned. Measurements and classical operations write the classical register, and Amplitude, ExpectationValue and similar operations write the z-register.

Parameters:
  • state (State) – A state from build_state().

  • compiled (CompiledCircuit) – The compiled circuit, after prepare_trajectory().

  • rng – The generator that randomness resolved during evolution (measurements, resets, noise) is drawn from; execute() passes RNGs.noise. It is advanced, so successive calls sharing one generator draw independent numbers. Without it the backend draws fresh entropy.

  • callback – None, or a callable to report progress. When progress reporting is on, the driver passes a callable that expects callback(i, total) once per step, with i the 1-based step and total the number of steps or None.

  • stopped – The stopped argument of execute(), passed through unchanged.

Returns:

the evolved state and a Fidelity. A plain float is also accepted: 1.0 is read as ExactFidelity, any other value as TruncationLowerBound, and None as UnknownFidelity.

Return type:

A tuple (state, fidelity)

recompile_per_trajectory(circuit)[source]

Return whether compile() runs again for every trajectory.

The default returns True when circuit has a mixed-unitary Kraus channel, for backends that draw its branch while compiling. Backends that draw it in prepare_trajectory() or evolve() override this to return False and compile once.

Parameters:

circuit – The prepared circuit.

Returns:

Whether to recompile per trajectory.

Return type:

bool

bind(compiled, params)[source]

Substitute params into a compiled parametric circuit.

The default evaluates the source circuit with params and calls compile() again, which pays the full compile cost at every point. Backends that can rebind a compiled form in place override this.

Parameters:
  • compiled (CompiledParametricCircuit) – A CompiledParametricCircuit whose source is the symbolic circuit.

  • params (dict) – Values for the free symbols, as for evaluate().

Returns:

A fully bound CompiledCircuit.

Return type:

CompiledCircuit

optimize(experiment, initparams=None, *, return_history=False, **kwargs)[source]

Minimize a cost read from a parametric circuit by running it on this backend.

At every step the optimizer proposes values for the circuit’s symbols, the circuit is evaluated with them and run with execute(), and the cost is the real part of the mean of z-register zregister over the samples. Push the quantity to minimize into that register, for example with push_expval().

Call it with an OptimizationExperiment, a list of them, or a circuit and a dictionary of initial values for all its symbols plus the experiment’s fields as keywords:

  • optimizer: "BFGS", "LBFGS", "CG", "NELDERMEAD", "NEWTON", "COBYLA" (default) or "CMAES". All but "CMAES" come from scipy.optimize.minimize(); "CMAES" needs the cmaes extra (pip install 'mimiqcircuits[cmaes]').

  • maxiters: iteration limit, or None for the optimizer’s own.

  • zregister: index of the z-register holding the cost (default 0).

  • label: a name for the experiment.

With an experiment these fields come from it, and passing them again is an error. Every other keyword goes to execute() on each evaluation: nsamples, seed, fuse, passes and so on. With a fixed seed every evaluation draws the same random numbers, so a noisy cost does not jump between otherwise equal points.

Parameters:
  • experiment – An OptimizationExperiment, a list of them, or a symbolic circuit.

  • initparams – Initial values when experiment is a circuit; must be None otherwise.

  • return_history – Also keep every evaluated run.

  • **kwargs – Experiment fields (with a circuit only) and execute() options.

Returns:

An OptimizationResults with the lowest-cost OptimizationRun and, with return_history=True, every evaluated run in order. A list of experiments gives a list of results in the same order.

Raises:
  • ValueError – For an unknown optimizer, a zregister the circuit does not have, or a circuit and initial values that do not form a valid experiment.

  • TypeError – If initparams or an experiment field is given together with an experiment.

Examples

A one-qubit backend for circuits of RY gates followed by ⟨Z⟩ measurements. It tracks the rotation angle and writes cos(theta) to the z-register.

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import (
...     DefaultCompiledCircuit, LocalBackend, State)
>>> import math
>>> from symengine import symbols
>>> class RYState(State):
...     num_qubits = property(lambda self: 1)
...     num_bits = property(lambda self: 0)
...     num_zvars = property(lambda self: len(self.z))
...     classical_bits = property(lambda self: BitString(0))
...     complex_values = property(lambda self: list(self.z))
...     def __init__(self, nz):
...         self.theta, self.z = 0.0, [0j] * nz
...     def amplitude(self, bs):
...         raise NotImplementedError
...     def sample(self, nsamples, rng=None):
...         return [BitString(1)] * nsamples
>>> class RYBackend(LocalBackend):
...     name = "RY"
...     version = "0.1"
...     def capabilities(self):
...         return {"zvars", "expectation_1q"}
...     def build_state(self, nq, nb=0, nz=0, **kwargs):
...         return RYState(nz)
...     def compile(self, circuit):
...         return DefaultCompiledCircuit(circuit)
...     def evolve(self, state, compiled, *, rng=None,
...                callback=None, stopped=None):
...         for inst in compiled.source:
...             if isinstance(inst.operation, GateRY):
...                 state.theta += float(inst.operation.theta)
...             else:
...                 state.z[inst.zvars[0]] = math.cos(state.theta)
...         return state, 1.0

The cost is ⟨Z⟩ on qubit 0, written to z-register 0. It is lowest, -1, at theta = pi.

>>> theta = symbols("theta")
>>> c = Circuit().push(GateRY(theta), 0)
>>> c.push(ExpectationValue(GateZ()), 0, 0)
1-qubit, 1-zvar circuit with 2 instructions:
├── RY(theta) @ q[0]
└── ⟨Z⟩ @ q[0], z[0]

Start from theta = 0.1. nsamples=1 is enough because the cost is exact.

>>> res = RYBackend().optimize(c, {theta: 0.1},
...                            optimizer="NELDERMEAD", nsamples=1)
>>> best = res.get_best()
>>> round(best.cost, 4), round(best.parameters[theta], 2)
(-1.0, 3.14)
compile_progress(circuit, progress)[source]

Compile circuit, optionally reporting progress.

The default ignores progress and calls compile(). Backends whose compilation has countable steps (such as fusing gates into tensors) override this to open a stage on progress and step it.

Parameters:
  • circuit – The prepared circuit.

  • progress – A Progress sink.

Returns:

The result of compile().

uses_loss_driver()[source]

Return whether execute() resolves runtime loss through evolve_with_loss().

Runtime loss comes from Kraus channels with a LossyOperator branch: which qubit is lost depends on the branch that fires. A backend opts in by returning True, implementing apply_instruction() and sample_kraus(), and giving its state a LossState (see State.get_loss_state()). The default returns False.

apply_instruction(state, inst, *, rng=None)[source]

Apply one instruction to state for the runtime-loss driver.

Backends that use the runtime-loss driver override this; the default raises NotImplementedError. The instruction never involves a lost qubit, so the method needs no loss logic.

Parameters:
  • state – The state to change in place.

  • inst – The instruction to apply.

  • rng – The noise generator.

Returns:

The fidelity factor of this step, 1.0 when it is exact.

sample_kraus(state, channel, targets, *, rng=None)[source]

Draw and apply one branch of a Kraus channel, for the runtime-loss driver.

Backends that use the runtime-loss driver override this; the default raises NotImplementedError.

Parameters:
  • state – The state to change in place.

  • channel – The Kraus channel.

  • targets – The qubits it acts on.

  • rng – The noise generator.

Returns:

the fidelity factor and the Kraus operator that fired, as the channel holds it, so that a LossyOperator keeps its type and the driver can mark its qubits as lost.

Return type:

A tuple (fidelity, fired)

apply_segment(state, insts, *, rng=None)[source]

Apply a run of instructions on present qubits, for the runtime-loss driver.

The driver passes the longest run between two loss events, and every instruction in it acts only on present qubits, so a backend that compresses or fuses gates (MPS, MPO) can override this to process the whole run at once. The default calls apply_instruction() on each instruction in turn.

Parameters:
  • state – The state to change in place.

  • insts – The instructions to apply.

  • rng – The noise generator.

Returns:

The product of the fidelity factors.

evolve_with_loss(state, circuit, lossmodel, *, rng=None, callback=None, stopped=None)[source]

Evolve circuit on state while resolving qubit loss as it happens.

The lost qubits are tracked in the state’s LossState and interpreted as lower_losses() does. The circuit is walked as alternating runs and loss events: each run of instructions on present qubits goes to apply_segment(), then the loss event after it (Loss, Reload, Check, MeasureCheck, a Kraus channel, or an operation on a lost qubit) is resolved against the live state. execute() calls this once per shot when uses_loss_driver() returns True and the circuit has a loss that can only be resolved while it runs.

Parameters:
  • state – A state from build_state() whose get_loss_state() works.

  • circuit – The prepared circuit.

  • lossmodel – The LossModel that decides how an operation on partly lost qubits is rewritten.

  • rng – The noise generator.

  • callback – Called as callback(i, total) once per instruction of circuit, with i from 1 to total, its length. An instruction dropped because its qubits are lost still counts, so the total doesn’t depend on which qubits are lost.

  • stopped – Accepted for symmetry with evolve(); not used.

Returns:

A tuple (state, fidelity), where fidelity is the product of the per-step fidelity factors.

execute(circuit, *, nsamples=1000, seed=None, rng=None, passes=None, fuse=None, fuse_threshold=None, canonicaldecompose=None, reorderqubits=None, remove_swaps=None, simplify=None, reorderqubits_seed=None, mapping=None, callback=None, param_grid=None, strict_pass_order=True, stopped=None, num_qubits=None, progress=False)[source]

Run circuit on this backend and return its results.

Takes every argument of Backend.execute(), plus the ones below. circuit may also be a SweepExperiment; passing one together with param_grid raises TypeError, and one with an empty table returns [].

Parameters:
  • fuse_threshold (int | None) – Fuse gates only from this many qubits up. On its own it also requests fusion; with fuse=False it raises ValueError.

  • stopped – Passed through unchanged to evolve() and evolve_with_loss().

  • num_qubits (int | None) – Simulate at least this many qubits. When the circuit has no classical bits and runs as a single evolution, the samples cover the extra qubits too.

  • progress – True to show progress bars with TqdmProgress, False for none, or a Progress sink.

Returns:

See Backend.execute().

See also

Backend.execute() for the shared arguments.

class RemoteBackend[source]

Bases: Backend

Base class for simulators that run on a remote service.

Subclasses implement submit(), plus the Backend identity members; they may override execute(). The inherited execute() checks the pass order, calls submit(), and blocks on the returned job’s wait().

See also

MimiqRemoteBackend, the backend for the MIMIQ cloud service.

abstract submit(circuits, nsamples, **kwargs)[source]

Send circuits to the service and return a job handle.

execute() calls it with the keywords rngs (an RNGs bundle), passes, callback, param_grid and strict_pass_order.

Parameters:
  • circuits – A circuit or a list of circuits.

  • nsamples (int) – Number of shots.

  • **kwargs – The keywords above, and any backend-specific options.

Returns:

A job handle with a wait() method that blocks until the results are available and returns them: a QCSResults, or a list for a list of circuits.

execute(circuit, *, nsamples=1000, seed=None, rng=None, passes=None, callback=None, param_grid=None, strict_pass_order=True)[source]

Submit circuit with submit() and wait for the results.

Takes the arguments of Backend.execute() except the preparation flags, which a remote backend may accept in its own override.

Returns:

Whatever the job’s wait() returns.

Raises:
  • RemotePassOrderError – If passes is non-empty, strict_pass_order is True and the backend does not declare "pass_order_honored".

  • TypeError – If both seed and rng are given.