mimiqcircuits.backends

Backend interface for quantum circuit simulators.

Subclass LocalBackend for a simulator that runs in this process, or RemoteBackend for one that runs on a service; MimiqRemoteBackend runs circuits on the MIMIQ cloud. See Implementing a Custom Backend for a step-by-step guide.

Where things live:

capabilities, limits, topology, admission  -> .capabilities
Backend, LocalBackend, RemoteBackend, State -> .backend
Fidelity types and reducers                 -> .fidelity
CompiledCircuit types, CompileMetadata      -> .compiled
AbstractPass, PassPipeline, apply_passes    -> .passes
CanonicalDecomposePass, MapCircuitPass,
mapping_target                              -> .concrete_passes
extract_projection, evaluate_projection     -> .measure_analysis
CompiledProjection                          -> .compiled_projection
StochasticKind and helpers                  -> .stochastic_kind
Progress, TqdmProgress, NoProgress          -> .progress
MimiqRemoteBackend                          -> .remote

Import the names from the package itself:

from mimiqcircuits.backends import Backend, LocalBackend, ...
Capability

alias of str

class Limits(max_qubits=None, max_bond_dim=None, max_classical_bits=None, max_zvars=None, max_samples=None, max_circuit_depth=None)[source]

Bases: object

Numeric limits a backend declares in Backend.limits().

None for a field means unbounded, or not applicable (such as max_bond_dim on a state-vector simulator). The default Backend.can_handle() checks max_qubits, max_classical_bits and max_zvars; the other fields are informational.

max_qubits

Largest number of qubits.

Type:

int or None

max_bond_dim

Largest bond dimension.

Type:

int or None

max_classical_bits

Largest number of classical bits.

Type:

int or None

max_zvars

Largest number of z-variables.

Type:

int or None

max_samples

Largest number of shots per execution.

Type:

int or None

max_circuit_depth

Largest circuit depth.

Type:

int or None

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import Limits
>>> lim = Limits(max_qubits=30)
>>> lim.max_qubits, lim.max_samples
(30, None)
class Topology[source]

Bases: object

Base class for the qubit connectivity a backend declares in Backend.topology().

class AllToAll[source]

Bases: Topology

Every pair of qubits can interact. The default for simulators.

class CouplingMap(edges)[source]

Bases: Topology

Connectivity given as a list of edges.

Each edge (i, j) means qubits i and j can interact directly. Indices are 1-based.

edges

The coupled pairs.

Type:

tuple[tuple[int, int], …]

class LinearChain(n)[source]

Bases: Topology

Linear chain of n qubits, each coupled to its neighbours.

n

Number of qubits.

Type:

int

class AdmissionResult[source]

Bases: object

Base class for the results of Backend.can_handle().

class Admissible[source]

Bases: AdmissionResult

The backend can execute the circuit.

class Marginal(warning)[source]

Bases: AdmissionResult

The backend can execute the circuit, but it is near a limit (memory, bond dimension, runtime).

is_admissible() treats it as admissible.

warning

Message for the user.

Type:

str

class Inadmissible(reason)[source]

Bases: AdmissionResult

The backend cannot execute the circuit.

reason

Why the circuit is rejected.

Type:

str

is_admissible(result)[source]

Return whether an admission result accepts the circuit.

Parameters:

result (AdmissionResult) – The result of Backend.can_handle().

Returns:

True for Admissible and Marginal, False otherwise.

Return type:

bool

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import (
...     Admissible, Inadmissible, Marginal, is_admissible)
>>> is_admissible(Admissible())
True
>>> is_admissible(Marginal(warning="close to the memory limit"))
True
>>> is_admissible(Inadmissible(reason="too many qubits"))
False
exception UnsupportedCapabilityError(backend_name, capability, detail='')[source]

Bases: Exception

Error for a feature the backend does not declare in Backend.capabilities().

Backends raise it when asked to run such a feature, instead of running something else in its place.

Parameters:
  • backend_name (str) – Name of the backend.

  • capability (Capability) – The capability token the circuit needs.

  • detail (str) – Optional extra text for the message.

register_cap_probe(capability, factory)[source]

Register a probe-circuit factory for capability in CAP_PROBES.

Conformance tests run each probe on every backend that does not declare its capability, and check that the backend rejects it. A factory registered for a capability that already has one replaces it.

Parameters:
  • capability (str) – The capability token.

  • factory (Callable) – A function of no arguments that returns a circuit whose execution needs capability.

Returns:

factory, unchanged.

class Fidelity[source]

Bases: object

Base class for typed fidelity values.

The subclasses say what a fidelity number means: ExactFidelity, UnknownFidelity, TruncationLowerBound, LowerBoundPerStep and EstimatedFidelity. as_lower_bound(), as_expected() and as_interval() reduce any of them to plain numbers.

Examples

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

An MPS simulator that discarded 1% of the norm reports a lower bound, not an exact value.

>>> f = TruncationLowerBound(0.99)
>>> as_lower_bound(f), as_expected(f)
(0.99, 0.99)

An estimate with a standard error is reduced conservatively by as_lower_bound() (mean minus three standard errors).

>>> e = EstimatedFidelity(mean=0.9, stderr=0.01)
>>> round(as_lower_bound(e), 2), as_expected(e)
(0.87, 0.9)
>>> as_lower_bound(UnknownFidelity())
nan
class ExactFidelity[source]

Bases: Fidelity

The simulator believes the state is exact.

BLAS and SIMD round-off are not tracked; this is a structural claim about the algorithm, not a bit-perfect guarantee.

class UnknownFidelity[source]

Bases: Fidelity

The backend does not track fidelity.

Reducers return nan. Prefer this variant over inventing a placeholder value when you genuinely do not know.

class TruncationLowerBound(value)[source]

Bases: Fidelity

A single lower bound on the fidelity of the whole circuit.

Typical for MPS and MPO simulators, where the bound comes from the singular values discarded during compression. Return it even when the bound is exactly 1.0: a plain 1.0 from LocalBackend.evolve() is read as ExactFidelity.

value

The lower bound.

Type:

float

class LowerBoundPerStep(values)[source]

Bases: Fidelity

Per-step lower-bound contributions.

as_lower_bound() returns the product of the values, each clipped to [0, 1]. That product bounds the circuit fidelity only when successive truncation errors are uncorrelated; a backend that cannot assume this returns a single TruncationLowerBound instead.

values

One contribution per step.

Type:

tuple[float, …]

class EstimatedFidelity(mean, stderr)[source]

Bases: Fidelity

Sample-based fidelity estimate with a standard error.

Use it for randomised benchmarking, direct fidelity estimation, or cross-entropy benchmarking. as_lower_bound() returns max(0, mean - 3 * stderr) and as_interval() returns (mean - stderr, mean + stderr).

mean

The estimate.

Type:

float

stderr

Its standard error.

Type:

float

as_lower_bound(f)[source]

Reduce f to a conservative lower bound.

Parameters:

f (Fidelity) – The fidelity.

Returns:

1.0 for ExactFidelity; nan for UnknownFidelity, so that statistics over many results do not count an unknown fidelity as a good one; the value for TruncationLowerBound; the product of the clipped values for LowerBoundPerStep; max(0, mean - 3 * stderr) for EstimatedFidelity.

Raises:

TypeError – If f is not one of these types.

Return type:

float

as_expected(f)[source]

Reduce f to a central estimate.

Parameters:

f (Fidelity) – The fidelity.

Returns:

The same as as_lower_bound(), except for EstimatedFidelity, which gives its mean.

Raises:

TypeError – If f is not a known Fidelity type.

Return type:

float

as_interval(f)[source]

Reduce f to a (low, high) interval.

Parameters:

f (Fidelity) – The fidelity.

Returns:

(mean - stderr, mean + stderr) for EstimatedFidelity, otherwise (as_lower_bound(f), as_expected(f)).

Raises:

TypeError – If f is not a known Fidelity type.

Return type:

tuple[float, float]

class CompiledCircuit[source]

Bases: object

Base class for the backend-specific form of a circuit.

Returned by LocalBackend.compile() and run by LocalBackend.evolve(). Backends subclass it to carry whatever they need: an MPO for an MPS simulator, a plain Circuit for a state-vector simulator, and so on. Subclasses implement metadata and source; DefaultCompiledCircuit does both and fits most backends.

property metadata: CompileMetadata

The CompileMetadata of this compiled circuit.

property source

The backend-specific artifact wrapped by this compiled circuit (for example a Circuit or an MPO).

class DefaultCompiledCircuit(_source, _metadata=<factory>)[source]

Bases: CompiledCircuit

Compiled circuit that wraps an artifact as it is.

Use it when the backend’s compile step has nothing to lower, for example a state-vector simulator that runs the input Circuit directly.

Parameters:

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import DefaultCompiledCircuit
>>> c = Circuit().push(GateH(), 0)
>>> compiled = DefaultCompiledCircuit(c)
>>> compiled.source is c
True
>>> compiled.metadata.active_qubits
[]
property metadata: CompileMetadata

The CompileMetadata given at construction.

property source

The wrapped artifact.

class CompiledParametricCircuit(_source, _metadata=<factory>)[source]

Bases: CompiledCircuit

Compiled circuit that still has free symbolic parameters.

A backend that declares the "parametric" capability can return it from LocalBackend.compile() for a symbolic circuit. LocalBackend.bind() resolves the parameters.

Parameters:
property metadata: CompileMetadata

The CompileMetadata given at construction.

property source

The symbolic circuit.

class CompileMetadata(measures=<factory>, active_qubits=<factory>, qubit_flips=<factory>, initial_layout=None, final_layout=None, measure_action_counts=<factory>, prefix_endpoint=0)[source]

Bases: object

Compile-time information carried by a CompiledCircuit.

Backends fill in the fields that apply to them and leave the others at their defaults. The execute driver of LocalBackend does not read them.

measures

Measurement-analysis entries, one per classical bit, classifying it as unused, read directly, read flipped, or constant 0 or 1. Empty when no analysis ran.

Type:

list

active_qubits

Qubits that must be simulated; the others are known to be in |0⟩ when measured.

Type:

list[int]

qubit_flips

Per qubit, whether a trailing X gate was absorbed into the read-out.

Type:

list[bool]

initial_layout

Where the pass pipeline put each qubit of the input circuit before the first instruction, 0-based, or None when the qubits keep their indices. See PassResult.

Type:

list[int] or None

final_layout

The same after the last instruction.

Type:

list[int] or None

measure_action_counts

Number of bits in each measurement-analysis class, for debugging.

Type:

dict[str, int]

prefix_endpoint

Index of the last instruction in the deterministic prefix, when the backend splits the circuit into a deterministic prefix and a random suffix; 0 otherwise.

Type:

int

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import CompileMetadata
>>> meta = CompileMetadata(active_qubits=[0, 1])
>>> meta.active_qubits, meta.final_layout
([0, 1], None)
exception UnboundSymbolicError(backend_name)[source]

Bases: Exception

Error for a circuit with free symbolic parameters on a backend that does not declare the "parametric" capability.

Backends raise it from LocalBackend.compile().

Parameters:

backend_name (str) – Name of the backend, kept as backend_name.

class PassParam[source]

Bases: object

Base class for the typed values used as pass parameters.

The variants (PStr, PInt, PFloat, PBool, PSym, PList, PDict) keep type information that a plain dictionary would lose when sent to a remote backend: the string "greedy" (a PStr) does not come back as a symbol (a PSym). Equality depends on the variant: PSym("x") != PStr("x"). Use to_pass_param() to convert plain Python values.

class PStr(value)[source]

Bases: PassParam

String pass parameter.

value

The string.

Type:

str

class PInt(value)[source]

Bases: PassParam

Integer pass parameter.

value

The integer.

Type:

int

class PFloat(value)[source]

Bases: PassParam

Floating-point pass parameter.

value

The number.

Type:

float

class PBool(value)[source]

Bases: PassParam

Boolean pass parameter.

value

The boolean.

Type:

bool

class PSym(value)[source]

Bases: PassParam

Pass parameter that names one of a fixed set of choices, like an enum.Enum member.

It never compares equal to a PStr with the same text, and to_pass_param() never produces it: build it explicitly.

value

The name of the choice.

Type:

str

class PList(items)[source]

Bases: PassParam

List pass parameter.

items

The elements.

Type:

tuple[PassParam, …]

class PDict(items)[source]

Bases: PassParam

Dictionary pass parameter with string keys.

items

The (key, value) pairs, as a tuple so that the parameter stays hashable.

Type:

tuple[tuple[str, PassParam], …]

to_pass_param(x)[source]

Convert a plain Python value into a PassParam.

Parameters:

x – A PassParam (returned as it is), a bool, int, float or str, or a list, tuple or dictionary of such values, converted recursively. Dictionary keys become strings.

Returns:

The matching PassParam. Strings become PStr, never PSym.

Raises:

TypeError – For any other type.

Return type:

PassParam

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import to_pass_param
>>> to_pass_param(True)
PBool(value=True)
>>> to_pass_param({"method": "greedy", "steps": [1, 2]})
PDict(items=(('method', PStr(value='greedy')), ('steps', PList(items=(PInt(value=1), PInt(value=2))))))
class PassSpec(name, parameters=(), requires=(), conflicts=())[source]

Bases: object

Description of a pass: its name and parameters.

Two specs with the same fields compare equal and hash the same. The name identifies the kind of pass: the preparation flags of Backend.execute() find the pass they act on by name, and MimiqRemoteBackend translates passes to server options by name.

name

Name of the kind of pass, such as "fuse_gates".

Type:

str

parameters

The parameters, as (name, value) pairs.

Type:

tuple[tuple[str, PassParam], …]

requires

Names of passes that must run before this one. Informational; nothing enforces it.

Type:

tuple[str, …]

conflicts

Names of passes that cannot be in the same pipeline. Informational; nothing enforces it.

Type:

tuple[str, …]

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import PassSpec
>>> PassSpec.from_dict("reorder_qubits", {"method": "sa"})
PassSpec(name='reorder_qubits', parameters=(('method', PStr(value='sa')),), requires=(), conflicts=())
static from_dict(name, parameters=None, requires=(), conflicts=())[source]

Build a spec from plain Python values.

Parameters:
  • name (str) – The name of the kind of pass.

  • parameters (dict | None) – The parameters, converted with to_pass_param().

  • requires (Iterable[str]) – Names of passes that must run before this one.

  • conflicts (Iterable[str]) – Names of passes that cannot be in the same pipeline.

Returns:

The new PassSpec.

Return type:

PassSpec

class PassResult(initial_layout=None, final_layout=None, metadata=<factory>)[source]

Bases: object

What a pass reports besides the new circuit, returned by AbstractPass.apply().

The two layouts say where the pass moved each qubit. Both are None when the pass keeps every qubit where it was, or both are lists with one entry per qubit of the pass’s input circuit, 0-based. The output circuit may be wider than the input, as after a mapping onto a larger device. apply_passes() composes them across the pipeline.

initial_layout

initial_layout[q] is the qubit of the output circuit that holds input qubit q before the first instruction.

Type:

list[int] or None

final_layout

final_layout[q] is the qubit of the output circuit that holds input qubit q after the last instruction.

Type:

list[int] or None

metadata

Free-form information about the run, such as timings or gate counts.

Type:

dict[str, Any]

class PassContext(backend=None, rng=<factory>, bitstrings=<factory>, features=<factory>)[source]

Bases: object

Inputs a pass may need, given to AbstractPass.apply().

backend

The backend the circuit is prepared for, or None. With a backend, apply_passes() also checks Backend.accepts_pass() and Backend.delegates_pass().

Type:

Backend or None

rng

The generator for randomised passes; LocalBackend.execute() passes RNGs.pass_.

Type:

random.Random

bitstrings

Basis states for passes that need them. The execute driver leaves it empty.

Type:

list

features

Circuit features for passes that need them. The execute driver leaves it empty.

Type:

set[str]

class AbstractPass[source]

Bases: ABC

Base class for circuit-transformation passes.

To write a pass, subclass it and implement spec() and apply(). Override preserves() when the pass breaks a circuit feature.

Examples

A pass that removes every Barrier.

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import (
...     AbstractPass, PassContext, PassResult, PassSpec)
>>> class DropBarriersPass(AbstractPass):
...     def spec(self):
...         return PassSpec("drop_barriers")
...     def apply(self, ctx, circuit):
...         kept = [i for i in circuit if not isinstance(i.operation, Barrier)]
...         # No qubit is relabelled, so the result reports nothing.
...         return Circuit(kept), PassResult()
>>> c = Circuit().push(GateH(), 0).push(Barrier(1), 0).push(GateX(), 0)
>>> new, result = DropBarriersPass().apply(PassContext(), c)
>>> new
1-qubit circuit with 2 instructions:
├── H @ q[0]
└── X @ q[0]

To run it in an execution, give it to a backend as backend.execute(c, passes=PassPipeline([DropBarriersPass()])).

abstract spec()[source]

Return a PassSpec describing the pass.

Its name is how the preparation flags and MimiqRemoteBackend identify the pass.

abstract apply(ctx, circuit)[source]

Run the pass on circuit.

Parameters:
  • ctx (PassContext) – The PassContext of the run.

  • circuit – The input circuit. Return a new circuit rather than changing it in place.

Returns:

A tuple (new_circuit, PassResult). A pass that moves qubits reports it in PassResult.initial_layout and PassResult.final_layout.

Return type:

tuple[Any, PassResult]

preserves(feature)[source]

Return whether the pass keeps feature of the input circuit intact.

The default returns True for every feature; override it when the pass breaks one. Neither apply_passes() nor the execute driver reads it.

Parameters:

feature (str) – One of "feed_forward", "midcircuit_measure", "parametric", "loss", "exact_equivalence", "strict_qubit_count".

class PassPipeline(passes=<factory>)[source]

Bases: object

An ordered sequence of passes.

It supports len, indexing and iteration, and + appends another pipeline or a list of passes, returning a new pipeline. Run it with apply_passes(), or give it to Backend.execute() as passes.

passes

The passes, in the order they run.

Type:

list[AbstractPass]

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import (
...     CanonicalDecomposePass, PassContext, PassPipeline, apply_passes)
>>> pipeline = PassPipeline([CanonicalDecomposePass()])
>>> len(pipeline)
1

Run the pipeline on a circuit. The Hadamard becomes a U gate, and no qubit was relabelled.

>>> c = Circuit().push(GateH(), 0)
>>> new, initial, final, results = apply_passes(pipeline, PassContext(), c)
>>> new
1-qubit circuit with 1 instruction:
└── U((1/2)*pi, 0, pi, 0.0) @ q[0]

>>> initial is None and final is None
True
apply_passes(pipeline, ctx, circuit)[source]

Run the passes of pipeline on circuit, in order.

When ctx.backend is set, each pass is first checked with Backend.accepts_pass(). A pass for which Backend.delegates_pass() returns True is not run: its result is PassResult(metadata={"delegated": True}) and the backend does the work itself.

The layouts of the pipeline start unset. A pass that reports layouts (i, f) on top of the pipeline’s (I, F) gives (i[I[q]], f[F[q]]) for each qubit q of circuit, or (i, f) itself while the pipeline’s are unset. A pass that reports none leaves them alone.

Parameters:
  • pipeline (PassPipeline) – The passes to run.

  • ctx (PassContext) – The PassContext given to every pass.

  • circuit – The input circuit. It is passed to the first pass as it is.

Returns:

the transformed circuit, the composed layouts (each None when no pass reported one, otherwise a 0-based list with one entry per qubit of the input circuit, see PassResult), and one PassResult per pass.

Return type:

A tuple (circuit, initial_layout, final_layout, results)

Raises:
  • UnacceptedPassError – If the backend refuses a pass.

  • ValueError – If a pass reports only one of the two layouts, or a layout that does not cover the qubits it receives.

See also

PassPipeline, whose example runs a pipeline.

invert_perm(perm)[source]

Return the inverse of a 0-based permutation.

Parameters:

perm (list[int]) – The permutation, as a list of the values 0 to len(perm) - 1.

Returns:

The inverse permutation, also 0-based.

Return type:

list[int]

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import invert_perm
>>> invert_perm([1, 2, 0])
[2, 0, 1]
exception UnacceptedPassError(backend_name, pass_name)[source]

Bases: Exception

Error for a pass the backend refuses in Backend.accepts_pass().

apply_passes() raises it instead of skipping the pass.

Parameters:
  • backend_name (str) – Name of the backend.

  • pass_name (str) – Name of the pass, from its PassSpec.

exception RemotePassOrderError(backend_name)[source]

Bases: Exception

Error for a non-empty passes given to a remote backend that does not declare "pass_order_honored", with strict_pass_order=True.

Pass strict_pass_order=False to submit the passes as an unordered set instead: MimiqRemoteBackend translates the passes it knows into server options and drops the others with a warning.

Parameters:

backend_name (str) – Name of the backend.

class CanonicalDecomposePass[source]

Bases: AbstractPass

Pass that decomposes a circuit to its canonical basis.

Wraps Circuit.decompose(). Qubit indices are unchanged, so the layouts of its PassResult are None.

spec()[source]

Return a PassSpec describing the pass.

Its name is how the preparation flags and MimiqRemoteBackend identify the pass.

apply(ctx, circuit)[source]

Run the pass on circuit.

Parameters:
  • ctx – The PassContext of the run.

  • circuit – The input circuit. Return a new circuit rather than changing it in place.

Returns:

A tuple (new_circuit, PassResult). A pass that moves qubits reports it in PassResult.initial_layout and PassResult.final_layout.

class MapCircuitPass(target=None, trials=10)[source]

Bases: AbstractPass

Pass that maps a circuit onto the sites of a device with map_circuit().

In the mapped circuit every operation on two or more qubits acts on sites that interact, with SWAP gates added where needed. The qubits of the output circuit are sites, so it may be wider than the input. The pass reports where each input qubit sits before and after in PassResult.initial_layout and PassResult.final_layout, and in metadata the seed, trials, forced and nsites of the MappingResult, and inserted_swaps, the number of SWAP gates it added.

Backend.execute() installs Backend.mapping_pass() by default on a backend whose topology is not AllToAll.

Parameters:
  • target (MappingTarget, optional) – The device. When None, the pass maps onto mapping_target(ctx.backend.topology()).

  • trials (int) – The number of layout and routing trials, passed to map_circuit(). Defaults to 10.

Raises:

ValueError – From apply(), when there is no target (neither target nor a backend with a topology other than AllToAll), and for everything map_circuit() refuses, with its message.

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.mapping import MappingTarget
>>> from mimiqcircuits.backends import MapCircuitPass, PassContext
>>> c = Circuit().push(GateCX(), 0, 2)
>>> mapped, result = MapCircuitPass(MappingTarget.line(3)).apply(PassContext(), c)
>>> result.initial_layout, result.final_layout
([0, 2, 1], [0, 2, 1])
>>> result.metadata["inserted_swaps"]
0
spec()[source]

Return a PassSpec describing the pass.

Its name is how the preparation flags and MimiqRemoteBackend identify the pass.

apply(ctx, circuit)[source]

Run the pass on circuit.

Parameters:
  • ctx – The PassContext of the run.

  • circuit – The input circuit. Return a new circuit rather than changing it in place.

Returns:

A tuple (new_circuit, PassResult). A pass that moves qubits reports it in PassResult.initial_layout and PassResult.final_layout.

preserves(feature)[source]

Return whether the pass keeps feature of the input circuit intact.

The default returns True for every feature; override it when the pass breaks one. Neither apply_passes() nor the execute driver reads it.

Parameters:

feature – One of "feed_forward", "midcircuit_measure", "parametric", "loss", "exact_equivalence", "strict_qubit_count".

mapping_target(topology)[source]

Return the MappingTarget of a backend topology.

Parameters:

topology – A Topology, such as backend.topology().

Returns:

None for AllToAll, which needs no mapping. MappingTarget.line(n) for LinearChain(n). For a CouplingMap, a target with as many sites as the largest index in its edges, and those edges converted from 1-based to 0-based. The target’s max_arity is 2, since a topology says nothing about wider native operations.

Raises:

Examples

>>> from mimiqcircuits.backends import CouplingMap, mapping_target
>>> target = mapping_target(CouplingMap(((1, 2), (2, 4))))
>>> target.nsites, target.edges
(4, ((0, 1), (1, 3)))
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:
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.

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 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 Progress[source]

Bases: ABC

Destination for execution progress, given to LocalBackend.execute() as progress.

Subclasses implement stage(). NoProgress draws nothing and TqdmProgress draws tqdm bars.

Examples

A sink that prints every stage it is asked to open.

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import NoProgress, Progress
>>> class PrintProgress(Progress):
...     def stage(self, name, *, total=None):
...         print(f"{name}: {total} steps")
...         return NoProgress().stage(name, total=total)
>>> bar = PrintProgress().stage("trajectories", total=100)
trajectories: 100 steps
>>> bar.step()
>>> bar.finish()
abstract stage(name, *, total=None)[source]

Open a stage.

Parameters:
  • name (str) – Name of the stage, such as "trajectories", "execute" or "compression".

  • total – Number of steps, or None when unknown.

Returns:

The Stage to advance and close.

Return type:

Stage

class Stage[source]

Bases: ABC

A single progress bar opened by Progress.stage().

Subclasses implement step() and finish().

abstract step(n=1)[source]

Advance the bar by n steps.

abstract finish()[source]

Close the bar.

class NoProgress[source]

Bases: Progress

Sink that draws nothing; the default of LocalBackend.execute().

Its stages ignore Stage.step() and Stage.finish().

stage(name, *, total=None)[source]

Open a stage.

Parameters:
  • name (str) – Name of the stage, such as "trajectories", "execute" or "compression".

  • total – Number of steps, or None when unknown.

Returns:

The Stage to advance and close.

Return type:

Stage

class TqdmProgress(*, leave=False)[source]

Bases: Progress

Sink that draws each stage as a tqdm bar.

execute(progress=True) uses it with the default arguments.

Parameters:

leave (bool) – Keep each bar on screen after its stage finishes. The default, False, clears it, so successive stages do not pile up.

stage(name, *, total=None)[source]

Open a stage.

Parameters:
  • name (str) – Name of the stage, such as "trajectories", "execute" or "compression".

  • total – Number of steps, or None when unknown.

Returns:

The Stage to advance and close.

Return type:

Stage

to_progress(progress)[source]

Turn the progress argument of LocalBackend.execute() into a Progress.

Parameters:

progress – A Progress, returned as it is, or a bool: True gives TqdmProgress, False gives NoProgress.

Returns:

The Progress sink.

Raises:

TypeError – For any other type.

Return type:

Progress

class MimiqRemoteBackend(connection, *, algorithm='auto', label=None, poll_interval=1.0)[source]

Bases: RemoteBackend

Backend that runs circuits on the MIMIQ cloud service.

It wraps a MimiqConnection (or another mimiqcircuits.remote.RemoteConnection) so that cloud execution takes the same seed, rng and passes arguments as a local backend and returns the same QCSResults. The simulator algorithm is fixed at construction; the other server options (bonddim, entdim, mpscutoff, mpsmethod, mpotraversal, timelimit, noisemodel) are given to execute() or submit().

Parameters:
  • connection – An authenticated connection, or any object with callable submit(...) and get_results(...) methods. The constructor does not log in, so call connection.connect() first.

  • algorithm (str) – "auto", "mps" or "statevector". It also sets capabilities() and limits().

  • label (Optional[str]) – Label of the jobs on the service. Defaults to "pyapi_remote_backend".

  • poll_interval (float) – Seconds between two checks of a running job.

Raises:

TypeError – If connection lacks submit or get_results.

Notes

  1. The capabilities are decided on the client, since the service does not report them: a fixed set, plus "bond_dim" and "schmidt_rank" when algorithm is "auto" or "mps".

  2. "pass_order_honored" is not declared, because the service takes a flat set of options (remove_swaps, fuse, …), not an ordered pipeline. A non-empty passes with the default strict_pass_order=True raises RemotePassOrderError. With strict_pass_order=False the passes the service knows are translated into options, and the others are dropped with one UserWarning.

  3. param_grid raises NotImplementedError. Evaluate the circuit for each point and execute the results instead.

  4. noisemodel= together with a pass named "apply_noise_model" in passes raises ValueError.

  5. seed and rng are mutually exclusive. The seed sent to the service is derived from them through an RNGs bundle, so it is not the integer passed in.

  6. A single circuit returns a single QCSResults; a list returns a list of the same length. A list of more than one circuit needs algorithm set to "mps" or "statevector"; with "auto" it raises ValueError.

  7. With algorithm="statevector", a noisemodel fails on the service, and the MPS options (bonddim, entdim, mpscutoff, mpsmethod, mpotraversal) have no effect. They are still sent; the backend does not reject them for this algorithm.

  8. execute() waits for the job without a time limit. For a bounded wait, call submit() and then job.wait(timeout=seconds), which raises TimeoutError.

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import MimiqRemoteBackend

Log in once, then wrap the connection in a backend that uses the MPS simulator.

>>> conn = MimiqConnection()
>>> conn.connect()  
>>> backend = MimiqRemoteBackend(conn, algorithm="mps")

Run a Bell circuit; bonddim is an option of the service.

>>> c = Circuit().push(GateH(), 0).push(GateCX(), 0, 1)
>>> c.push(Measure(), range(2), range(2))  
2-qubit, 2-bit circuit with 4 instructions:
...
>>> res = backend.execute(c, nsamples=1000, seed=42, bonddim=64)  
>>> res.histogram()  
property name: str

"Mimiq".

property version: str

The version of the mimiqcircuits package.

capabilities()[source]

Return the capabilities, decided on the client.

"bond_dim" and "schmidt_rank" are included only when algorithm is "auto" or "mps".

limits()[source]

Return the limits known to the client.

max_samples is the largest number of shots the client sends; max_bond_dim is set only when algorithm is "auto" or "mps".

topology()[source]

Return AllToAll.

submit(circuits, nsamples=1000, *, rngs=None, passes=None, callback=None, param_grid=None, strict_pass_order=True, fuse=None, reorderqubits=None, canonicaldecompose=None, remove_swaps=None, reorderqubits_seed=None, bonddim=None, entdim=None, mpscutoff=None, mpsmethod=None, mpotraversal=None, timelimit=None, noisemodel=None, **kwargs)[source]

Submit circuits to the service without waiting.

execute() calls it; call it directly to wait with a time limit.

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

  • nsamples (int) – Number of shots.

  • rngs – An RNGs bundle or an integer seed, folded into the single seed sent to the service; None draws a random seed.

  • passes (PassPipeline | None) – A PassPipeline. See the class notes for how it is handled.

  • callback – Accepted for compatibility with RemoteBackend.submit(); not used.

  • param_grid (list[dict] | None) – Must be empty or None.

  • strict_pass_order (bool) – See Backend.execute().

  • fuse (bool | None) – Server-side gate fusion; None lets the service choose.

  • reorderqubits – Server-side qubit reordering, as a bool or a method name.

  • canonicaldecompose (bool | None) – Server-side decomposition into the canonical gate set.

  • remove_swaps (bool | None) – Server-side SWAP removal.

  • reorderqubits_seed (int | None) – Seed of the server-side reordering.

  • bonddim (int | None) – Bond dimension of the MPS simulator.

  • entdim (int | None) – Entanglement dimension of the MPS simulator.

  • mpscutoff (float | None) – Singular-value cutoff of the MPS simulator.

  • mpsmethod (str | None) – MPO application method of the MPS simulator.

  • mpotraversal (str | None) – MPO compression traversal of the MPS simulator.

  • timelimit (int | None) – Time limit of the job, in minutes.

  • noisemodel – A NoiseModel applied to each circuit before it is uploaded.

  • **kwargs – Only simplify and mapping, which must be falsy: the service runs neither, and its topology is AllToAll.

Returns:

A job handle. Its request_id is the service’s job id, and its wait(timeout=None) blocks until the job is done and returns the list of QCSResults, with their fidelities converted to Fidelity types (exact for the state-vector simulator, a truncation lower bound for MPS, unknown otherwise). With a timeout in seconds it raises TimeoutError instead of waiting longer.

Raises:
Return type:

_MimiqJob

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

Submit circuit to the service and wait for the results.

To request specific amplitudes, push Amplitude instructions into circuit and read results.zstates.

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

  • nsamples (int) – Number of shots.

  • seed (int | None) – Integer seed. Mutually exclusive with rng; with neither, a fresh seed is drawn.

  • rng – A random.Random to draw the seed from.

  • passes (PassPipeline | None) – See the class notes.

  • callback – Not used.

  • param_grid (list[dict] | None) – Must be empty or None.

  • strict_pass_order (bool) – See Backend.execute().

  • **kwargs – Preparation flags and service options, passed to submit(): fuse, reorderqubits, canonicaldecompose, remove_swaps, reorderqubits_seed, mapping, bonddim, entdim, mpscutoff, mpsmethod, mpotraversal, timelimit, noisemodel.

Returns:

A QCSResults for a single circuit, or a list of them for a list of circuits.

Raises:
optimize(experiment, initparams=None, *, return_history=False, seed=None, rng=None, **kwargs)[source]

Run optimization experiments on the service and wait for the results.

Takes the same experiment arguments as LocalBackend.optimize(): an OptimizationExperiment, a list of them, or a circuit with its initial values and the experiment fields (optimizer, maxiters, zregister, label) as keywords. The service runs the optimizer with the backend’s algorithm.

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

  • initparams – Initial values when experiment is a circuit.

  • return_history (bool) – Also return every evaluated run.

  • seed (int | None) – Integer seed. Mutually exclusive with rng.

  • rng – A random.Random to draw the seed from.

  • **kwargs – Experiment fields (with a circuit only), and options of the connection’s optimize: nsamples, timelimit, bonddim, entdim, mpscutoff, fuse, reorderqubits, reorderqubits_seed, canonicaldecompose, remove_swaps, mpsmethod, mpotraversal, streaming.

Returns:

An OptimizationResults, or a list of them for a list of experiments.

Raises:
  • TypeError – If the connection has no optimize method, or both seed and rng are given.

  • ValueError – For more than one experiment with algorithm="auto"; use "mps" or "statevector".

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import MimiqRemoteBackend
>>> from symengine import symbols
>>> theta = symbols("theta")
>>> c = Circuit().push(GateRY(theta), 0)
>>> c.push(ExpectationValue(GateZ()), 0, 0)  
1-qubit, 1-zvar circuit with 2 instructions:
...
>>> conn = MimiqConnection()
>>> conn.connect()  
>>> backend = MimiqRemoteBackend(conn, algorithm="statevector")
>>> res = backend.optimize(c, {theta: 0.1}, optimizer="COBYLA")  
>>> res.get_best().cost  
normalize_seed(seed, rngs)[source]

Turn seed or rngs into a single integer seed.

Parameters:
  • seed (int | None) – An integer seed, or None.

  • rngs (RNGs | int | None) – An integer, returned as it is; an RNGs bundle, folded into one seed by XOR-ing one 63-bit draw from each of its four streams (which advances them); or None, in which case seed is returned.

Returns:

The seed, or None when both arguments are None.

Raises:

TypeError – If both are given, or rngs has another type.

Return type:

int | None

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import RNGs, normalize_seed
>>> normalize_seed(7, None)
7
>>> normalize_seed(None, RNGs.from_seed(7)) == normalize_seed(None, RNGs.from_seed(7))
True
derive_grid_seeds(base_seed, n)[source]

Derive n distinct seeds from base_seed.

The param_grid loop of LocalBackend.execute() uses it so that each point gets its own random stream; reusing base_seed for every point would correlate their outcomes. The result depends only on base_seed and the position, and two different base seeds, however close, have no seed in common.

Parameters:
  • base_seed (int | None) – The base seed, or None.

  • n (int) – Number of seeds.

Returns:

A list of n 63-bit seeds, or [None] * n when base_seed is None.

Return type:

list[int | None]

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import derive_grid_seeds
>>> seeds = derive_grid_seeds(42, 3)
>>> len(set(seeds)), seeds == derive_grid_seeds(42, 3)
(3, True)
>>> derive_grid_seeds(None, 2)
[None, None]
extract_projection(circuit)[source]

Split circuit into the part to evolve and a classical projection.

The circuit is scanned backwards. Trailing operations that do not change the final quantum state seen by the remaining operations move into a projection circuit of classical-bit instructions; the rest is the quantum circuit the simulator evolves.

Absorbed operations:

  • Trailing Measure(q, b) / MeasureReset(q, b) → Measure(q, b).

  • Trailing classical logic: Not, And, Or, Xor, SetBit0, SetBit1. These read other classical bits, so what comes out is a straight-line program over the register rather than a per-bit map, emitted in source order. A logic op is absorbed only when no operation left in quantum_circuit touches any of its bits, otherwise moving it past that operation would change what it reads.

  • Trailing GateID — dropped as a no-op. GateX / GateY / GateZ are NOT absorbed: Y and Z carry phases that would corrupt amplitude lookups, and X absorbed alone would require XOR-ing the qubit-flip pattern into every user-supplied bitstrings entry for amplitudes to stay consistent. Keeping all Paulis in quantum_circuit means the projection only contains phase-free transformations and amplitude lookups need no compensation.

  • Reset(q) whose qubit has captured pending bits → those bits become classical constants (SetBit0 / SetBit1 based on absorbed X parity). A Reset whose qubit has no captured bits is harmless and dropped.

Anything that cannot be absorbed (other gates, Kraus channels, IfStatement, Amplitude, ExpectationValue, …) blocks its qubits and survives into quantum_circuit.

If the source has no classical register, the projection is synthesised over an identity bit↔qubit mapping (bit i mirrors qubit i, length = circuit.num_qubits()).

A write to a classical bit that a later absorbed operation overwrites without reading is dropped from the projection, so reusing a classical bit does not cost a per-shot write that nothing observes.

Parameters:

circuit (Circuit) – The circuit to split. It is not changed.

Returns:

A tuple (quantum_circuit, projection_circuit).

Return type:

Tuple[Circuit, Circuit]

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import evaluate_projection, extract_projection
>>> c = Circuit().push(GateH(), 0).push(GateCX(), 0, 1)
>>> c.push(Measure(), range(2), range(2))
2-qubit, 2-bit circuit with 4 instructions:
├── H @ q[0]
├── CX @ q[0], q[1]
├── M @ q[0], c[0]
└── M @ q[1], c[1]

>>> quantum, projection = extract_projection(c)

The measurements leave the quantum circuit …

>>> quantum
2-qubit circuit with 2 instructions:
├── H @ q[0]
└── CX @ q[0], q[1]

… and become the projection, applied to each sampled shot.

>>> projection
2-qubit, 2-bit circuit with 2 instructions:
├── M @ q[0], c[0]
└── M @ q[1], c[1]

>>> evaluate_projection(projection, BitString("11")) == BitString("11")
True
evaluate_projection(projection, sample)[source]

Run a projection circuit on one shot.

The projection may hold Measure, SetBit0, SetBit1, Not, And, Or and Xor. The logic operations take their target as the first bit and read the rest, and the whole right-hand side is evaluated before the target is written, so a target that is also one of its own operands reads its old value. A Measure(q, b) whose qubit is outside sample leaves bit b untouched, so it reads zero unless an earlier instruction set it.

This is the reference implementation; CompiledProjection gives the same results faster for many shots.

Parameters:
Returns:

The classical register after the projection, of length projection.num_bits().

Raises:

ValueError – If projection holds any other operation.

Return type:

BitString

See also

extract_projection(), whose example uses it.

needs_trajectories(circuit)[source]

Return whether circuit must be evolved once per shot.

That is the case when it has an operation on qubits that is not unitary (a measurement, a reset, a noise channel, …). Operations on no qubits and operations that declare themselves unitary (gates, annotations, ExpectationValue, …) are ignored. Apply it to the quantum circuit returned by extract_projection(), since trailing measurements do not need per-shot evolution.

Parameters:

circuit (Circuit) – The circuit to check.

Returns:

True if a non-unitary operation acts on qubits.

Return type:

bool

needs_loss_sampling(circuit)[source]

Return whether circuit has loss operations to resolve before simulation.

Parameters:

circuit (Circuit) – The circuit to check.

Returns:

True if it has a Loss, Reload, Check or MeasureCheck instruction at the top level.

Return type:

bool

any_mixed_unitary(circuit)[source]

Return whether circuit has a mixed-unitary Kraus channel.

This is the default of LocalBackend.recompile_per_trajectory().

Parameters:

circuit (Circuit) – The circuit to check.

Returns:

True if a top-level Kraus channel has ismixedunitary() true.

Return type:

bool

remap_projection_qubits(projection, qubit_order, do_remap)[source]

Rename the qubits read by the Measure instructions of a projection.

Every Measure(q, b) becomes Measure(qubit_order[q], b); other instructions are copied as they are.

Parameters:
  • projection (Circuit) – The projection circuit.

  • qubit_order (list[int]) – The new index of each qubit, 0-based.

  • do_remap (bool) – When False, projection itself is returned unchanged.

Returns:

A new circuit, or projection when do_remap is False. The input is never changed.

Return type:

Circuit

class CompiledProjection(num_bits, steps=<factory>, _plans=<factory>)[source]

Bases: object

A projection circuit compiled for block evaluation.

Build one with from_circuit() and evaluate a whole block of shots with evaluate_batch(). An instance can be reused across blocks and holds no per-shot state. It gives the same results as evaluate_projection() applied to each shot.

num_bits

Width of the classical bitstring the projection produces, equal to projection.num_bits().

Type:

int

steps

The straight-line program, before it is specialised to a sample width. Internal representation, subject to change.

Type:

list[tuple]

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import CompiledProjection, extract_projection

A Bell circuit whose measurements are swapped, with the parity of the two outcomes written to a third bit.

>>> c = Circuit().push(GateH(), 0).push(GateCX(), 0, 1)
>>> c.push(Measure(), 1, 0).push(Measure(), 0, 1).push(Xor(3), 2, 0, 1)
2-qubit, 3-bit circuit with 5 instructions:
├── H @ q[0]
├── CX @ q[0], q[1]
├── M @ q[1], c[0]
├── M @ q[0], c[1]
└── c[2] = c[0] ^ c[1]

Split off the trailing classical part and compile it.

>>> quantum, projection = extract_projection(c)
>>> proj = CompiledProjection.from_circuit(projection)

Each sample has one bit per qubit; each result has one bit per classical bit.

>>> proj.evaluate_batch([BitString("00"), BitString("11"), BitString("01")])
[bs"000", bs"110", bs"101"]
classmethod from_circuit(projection)[source]

Compile projection for block evaluation.

Parameters:

projection (Circuit) – The projection circuit returned by extract_projection(), with qubit indices in the frame the samples will arrive in. Apply any qubit remapping first, or a permuted read-out is mistaken for an identity one.

Returns:

The compiled form, of width projection.num_bits().

Raises:

ValueError – If projection holds an operation other than Measure, SetBit0, SetBit1, Not, And, Or and Xor.

Return type:

CompiledProjection

evaluate_batch(samples)[source]

Evaluate the projection for every shot in samples.

When the projection copies qubit b into bit b for every bit and the samples are as wide as the register, the input bitstrings are returned as they are, without copying.

Parameters:

samples (Sequence[BitString]) – One computational-basis outcome per shot, all of the same width.

Returns:

One classical bitstring per shot, of length num_bits, in the order of samples.

Return type:

List[BitString]

evaluate(sample)[source]

Evaluate the projection for a single shot.

Same result as evaluate_projection(). evaluate_batch() is faster for many shots.

Parameters:

sample (BitString) – One computational-basis outcome.

Returns:

The classical bitstring, of length num_bits.

Return type:

BitString

class StochasticKind(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

When a backend resolves the randomness of an operation.

The members are ordered, Deterministic < TrajectorySampleable < RuntimeOnly, so max gives the kind of a group of operations.

  • Deterministic: no randomness; LocalBackend.compile() can lower the operation from the circuit alone.

  • TrajectorySampleable: random, but resolvable in LocalBackend.prepare_trajectory() from random draws alone, because the outcomes and their probabilities do not depend on the state, for this backend.

  • RuntimeOnly: must be resolved during LocalBackend.evolve(), because the probabilities or a control-flow condition depend on the live quantum or classical state.

The kind of an operation depends on the backend; see Backend.stochastic_kind().

default_stochastic_kind(op)[source]

Classify an operation without reference to a backend.

This is the default of Backend.stochastic_kind(). Backends that classify an operation differently override that method, not this function.

  • IfStatement: the kind of the operation it wraps.

  • Kraus channels: TrajectorySampleable if mixed-unitary, otherwise RuntimeOnly.

  • Loss and every measurement: RuntimeOnly.

  • Everything else: Deterministic.

Parameters:

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

Returns:

A StochasticKind.

Return type:

StochasticKind

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import default_stochastic_kind
>>> default_stochastic_kind(GateH()).name
'Deterministic'

A depolarizing channel applies a random Pauli with fixed probabilities, so its branch can be drawn ahead of time.

>>> default_stochastic_kind(Depolarizing(1, 0.1)).name
'TrajectorySampleable'

The branch probabilities of amplitude damping depend on the state.

>>> default_stochastic_kind(AmplitudeDamping(0.1)).name
'RuntimeOnly'
stochastic_kind(backend, x)[source]

Return backend.stochastic_kind(x).

Parameters:
  • backend (Backend) – The backend that classifies x.

  • x – An operation or an instruction.

Returns:

A StochasticKind.

Return type:

StochasticKind

is_deterministic(backend, x)[source]

Return whether backend classifies x as Deterministic.

is_trajectory_sampleable(backend, x)[source]

Return whether backend classifies x as TrajectorySampleable.

is_runtime_only(backend, x)[source]

Return whether backend classifies x as RuntimeOnly.

is_stochastic(backend, x)[source]

Return whether backend classifies x as anything but Deterministic.

first_stochastic(backend, circuit)[source]

Return the index of the first instruction of circuit that backend does not classify as Deterministic, or None.

last_stochastic(backend, circuit)[source]

Return the index of the last instruction of circuit that backend does not classify as Deterministic, or None.

first_runtime_only(backend, circuit)[source]

Return the index of the first instruction of circuit that backend classifies as RuntimeOnly, or None.

Unlike first_stochastic(), it skips TrajectorySampleable instructions, which a backend can resolve before evolving.

last_runtime_only(backend, circuit)[source]

Return the index of the last instruction of circuit that backend classifies as RuntimeOnly, or None.

Modules

backend

Abstract base classes for simulator backends.

capabilities

Capability vocabulary, numeric limits, topology, and admission types.

compiled

Compiled-circuit types and the metadata they carry.

compiled_projection

Compiled form of a projection circuit.

concrete_passes

Concrete circuit-preparation passes.

fidelity

Typed fidelity values returned by LocalBackend.evolve().

measure_analysis

Final-block analysis.

optimize

Variational optimization of a parametric circuit on a local backend.

passes

Optimization-pass framework.

progress

Progress reporting for LocalBackend.execute().

remote

Concrete RemoteBackend for the MIMIQ cloud service.

stochastic_kind(backend, x)

Return backend.stochastic_kind(x).