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, ...
- 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:
objectNumeric limits a backend declares in
Backend.limits().Nonefor a field means unbounded, or not applicable (such asmax_bond_dimon a state-vector simulator). The defaultBackend.can_handle()checksmax_qubits,max_classical_bitsandmax_zvars; the other fields are informational.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:
objectBase class for the qubit connectivity a backend declares in
Backend.topology().
- class AllToAll[source]¶
Bases:
TopologyEvery pair of qubits can interact. The default for simulators.
- class CouplingMap(edges)[source]¶
Bases:
TopologyConnectivity given as a list of edges.
Each edge
(i, j)means qubitsiandjcan interact directly. Indices are 1-based.
- class LinearChain(n)[source]¶
Bases:
TopologyLinear chain of
nqubits, each coupled to its neighbours.
- class AdmissionResult[source]¶
Bases:
objectBase class for the results of
Backend.can_handle().
- class Admissible[source]¶
Bases:
AdmissionResultThe backend can execute the circuit.
- class Marginal(warning)[source]¶
Bases:
AdmissionResultThe backend can execute the circuit, but it is near a limit (memory, bond dimension, runtime).
is_admissible()treats it as admissible.
- class Inadmissible(reason)[source]¶
Bases:
AdmissionResultThe backend cannot execute the circuit.
- is_admissible(result)[source]¶
Return whether an admission result accepts the circuit.
- Parameters:
result (AdmissionResult) – The result of
Backend.can_handle().- Returns:
TrueforAdmissibleandMarginal,Falseotherwise.- Return type:
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:
ExceptionError 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.
- register_cap_probe(capability, factory)[source]¶
Register a probe-circuit factory for
capabilityinCAP_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.
- class Fidelity[source]¶
Bases:
objectBase class for typed fidelity values.
The subclasses say what a fidelity number means:
ExactFidelity,UnknownFidelity,TruncationLowerBound,LowerBoundPerStepandEstimatedFidelity.as_lower_bound(),as_expected()andas_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:
FidelityThe 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:
FidelityThe 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:
FidelityA 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 plain1.0fromLocalBackend.evolve()is read asExactFidelity.
- class LowerBoundPerStep(values)[source]¶
Bases:
FidelityPer-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 singleTruncationLowerBoundinstead.
- class EstimatedFidelity(mean, stderr)[source]¶
Bases:
FidelitySample-based fidelity estimate with a standard error.
Use it for randomised benchmarking, direct fidelity estimation, or cross-entropy benchmarking.
as_lower_bound()returnsmax(0, mean - 3 * stderr)andas_interval()returns(mean - stderr, mean + stderr).
- as_lower_bound(f)[source]¶
Reduce
fto a conservative lower bound.- Parameters:
f (Fidelity) – The fidelity.
- Returns:
1.0forExactFidelity;nanforUnknownFidelity, so that statistics over many results do not count an unknown fidelity as a good one; the value forTruncationLowerBound; the product of the clipped values forLowerBoundPerStep;max(0, mean - 3 * stderr)forEstimatedFidelity.- Raises:
TypeError – If
fis not one of these types.- Return type:
- as_expected(f)[source]¶
Reduce
fto a central estimate.- Parameters:
f (Fidelity) – The fidelity.
- Returns:
The same as
as_lower_bound(), except forEstimatedFidelity, which gives its mean.- Raises:
- Return type:
- class CompiledCircuit[source]¶
Bases:
objectBase class for the backend-specific form of a circuit.
Returned by
LocalBackend.compile()and run byLocalBackend.evolve(). Backends subclass it to carry whatever they need: an MPO for an MPS simulator, a plainCircuitfor a state-vector simulator, and so on. Subclasses implementmetadataandsource;DefaultCompiledCircuitdoes both and fits most backends.- property metadata: CompileMetadata¶
The
CompileMetadataof this compiled circuit.
- property source¶
The backend-specific artifact wrapped by this compiled circuit (for example a
Circuitor an MPO).
- class DefaultCompiledCircuit(_source, _metadata=<factory>)[source]¶
Bases:
CompiledCircuitCompiled 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
Circuitdirectly.- Parameters:
_metadata (CompileMetadata) – The
CompileMetadata, returned bymetadata. Defaults to an empty one.
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
CompileMetadatagiven at construction.
- property source¶
The wrapped artifact.
- class CompiledParametricCircuit(_source, _metadata=<factory>)[source]¶
Bases:
CompiledCircuitCompiled circuit that still has free symbolic parameters.
A backend that declares the
"parametric"capability can return it fromLocalBackend.compile()for a symbolic circuit.LocalBackend.bind()resolves the parameters.- Parameters:
_source (Any) – The symbolic
Circuit, kept so thatLocalBackend.bind()can evaluate it._metadata (CompileMetadata) – The
CompileMetadata. Defaults to an empty one.
- property metadata: CompileMetadata¶
The
CompileMetadatagiven 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:
objectCompile-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
LocalBackenddoes 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:
- active_qubits¶
Qubits that must be simulated; the others are known to be in
|0⟩when measured.
- initial_layout¶
Where the pass pipeline put each qubit of the input circuit before the first instruction, 0-based, or
Nonewhen the qubits keep their indices. SeePassResult.
- measure_action_counts¶
Number of bits in each measurement-analysis class, for debugging.
- 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;
0otherwise.- Type:
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:
ExceptionError 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:
objectBase 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"(aPStr) does not come back as a symbol (aPSym). Equality depends on the variant:PSym("x") != PStr("x"). Useto_pass_param()to convert plain Python values.
- class PSym(value)[source]¶
Bases:
PassParamPass parameter that names one of a fixed set of choices, like an
enum.Enummember.It never compares equal to a
PStrwith the same text, andto_pass_param()never produces it: build it explicitly.
- to_pass_param(x)[source]¶
Convert a plain Python value into a
PassParam.- Parameters:
x – A
PassParam(returned as it is), abool,int,floatorstr, or a list, tuple or dictionary of such values, converted recursively. Dictionary keys become strings.- Returns:
- Raises:
TypeError – For any other type.
- Return type:
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:
objectDescription 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, andMimiqRemoteBackendtranslates passes to server options by name.- requires¶
Names of passes that must run before this one. Informational; nothing enforces it.
- conflicts¶
Names of passes that cannot be in the same pipeline. Informational; nothing enforces it.
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=())
- class PassResult(initial_layout=None, final_layout=None, metadata=<factory>)[source]¶
Bases:
objectWhat a pass reports besides the new circuit, returned by
AbstractPass.apply().The two layouts say where the pass moved each qubit. Both are
Nonewhen 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 qubitqbefore the first instruction.
- final_layout¶
final_layout[q]is the qubit of the output circuit that holds input qubitqafter the last instruction.
- class PassContext(backend=None, rng=<factory>, bitstrings=<factory>, features=<factory>)[source]¶
Bases:
objectInputs a pass may need, given to
AbstractPass.apply().- backend¶
The backend the circuit is prepared for, or
None. With a backend,apply_passes()also checksBackend.accepts_pass()andBackend.delegates_pass().- Type:
Backend or None
- rng¶
The generator for randomised passes;
LocalBackend.execute()passesRNGs.pass_.- Type:
- class AbstractPass[source]¶
Bases:
ABCBase class for circuit-transformation passes.
To write a pass, subclass it and implement
spec()andapply(). Overridepreserves()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
PassSpecdescribing the pass.Its name is how the preparation flags and
MimiqRemoteBackendidentify the pass.
- abstract apply(ctx, circuit)[source]¶
Run the pass on
circuit.- Parameters:
ctx (PassContext) – The
PassContextof 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 inPassResult.initial_layoutandPassResult.final_layout.- Return type:
- preserves(feature)[source]¶
Return whether the pass keeps
featureof the input circuit intact.The default returns
Truefor every feature; override it when the pass breaks one. Neitherapply_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:
objectAn 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 withapply_passes(), or give it toBackend.execute()aspasses.- passes¶
The passes, in the order they run.
- Type:
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
Ugate, 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
pipelineoncircuit, in order.When
ctx.backendis set, each pass is first checked withBackend.accepts_pass(). A pass for whichBackend.delegates_pass()returnsTrueis not run: its result isPassResult(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 qubitqofcircuit, 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
PassContextgiven 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
Nonewhen no pass reported one, otherwise a 0-based list with one entry per qubit of the input circuit, seePassResult), and onePassResultper 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
0tolen(perm) - 1.- Returns:
The inverse permutation, also 0-based.
- Return type:
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:
ExceptionError for a pass the backend refuses in
Backend.accepts_pass().apply_passes()raises it instead of skipping the pass.
- exception RemotePassOrderError(backend_name)[source]¶
Bases:
ExceptionError for a non-empty
passesgiven to a remote backend that does not declare"pass_order_honored", withstrict_pass_order=True.Pass
strict_pass_order=Falseto submit the passes as an unordered set instead:MimiqRemoteBackendtranslates 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:
AbstractPassPass that decomposes a circuit to its canonical basis.
Wraps
Circuit.decompose(). Qubit indices are unchanged, so the layouts of itsPassResultareNone.- spec()[source]¶
Return a
PassSpecdescribing the pass.Its name is how the preparation flags and
MimiqRemoteBackendidentify the pass.
- apply(ctx, circuit)[source]¶
Run the pass on
circuit.- Parameters:
ctx – The
PassContextof 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 inPassResult.initial_layoutandPassResult.final_layout.
- class MapCircuitPass(target=None, trials=10)[source]¶
Bases:
AbstractPassPass 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_layoutandPassResult.final_layout, and inmetadatatheseed,trials,forcedandnsitesof theMappingResult, andinserted_swaps, the number of SWAP gates it added.Backend.execute()installsBackend.mapping_pass()by default on a backend whose topology is notAllToAll.- Parameters:
target (MappingTarget, optional) – The device. When
None, the pass maps ontomapping_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 (neithertargetnor a backend with a topology other thanAllToAll), and for everythingmap_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
PassSpecdescribing the pass.Its name is how the preparation flags and
MimiqRemoteBackendidentify the pass.
- apply(ctx, circuit)[source]¶
Run the pass on
circuit.- Parameters:
ctx – The
PassContextof 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 inPassResult.initial_layoutandPassResult.final_layout.
- preserves(feature)[source]¶
Return whether the pass keeps
featureof the input circuit intact.The default returns
Truefor every feature; override it when the pass breaks one. Neitherapply_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
MappingTargetof a backend topology.- Parameters:
topology – A
Topology, such asbackend.topology().- Returns:
NoneforAllToAll, which needs no mapping.MappingTarget.line(n)forLinearChain(n). For aCouplingMap, 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’smax_arityis 2, since a topology says nothing about wider native operations.- Raises:
TypeError – For any other kind of topology.
ValueError – If a
CouplingMapedge joins a site to itself or names a site below 1.
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:
ABCAbstract base class for every simulator backend.
Subclasses implement
name,version,capabilities()andexecute(); they may overridelimits(),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()andexpectation().Most backends subclass one of the two bases below, which implement
execute():LocalBackend, when the simulator runs in this process and evolves aState;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.simulatorand used in error messages.
- 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.
- limits()[source]¶
Return the numeric limits of this backend.
The default returns
Limits(), with every limit unbounded.
- can_handle(circuit)[source]¶
Check whether this backend can run
circuit.The default compares
circuitwithlimits()andcapabilities(). It returnsInadmissiblewhen the circuit:has more qubits, classical bits or z-variables than
max_qubits,max_classical_bitsormax_zvarsallow;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
IfStatementorWhileStatement, and the backend does not declare"noise";has free symbolic parameters and the backend does not declare
"parametric".
Otherwise it returns
Admissible. It never returnsMarginal. Backends with other criteria (bond-dimension estimates, connectivity, gate sets) override it.- Parameters:
circuit – The circuit to check.
- Returns:
An
AdmissionResult. Useis_admissible()to turn it into a bool.- Return type:
- 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
TrajectorySampleablefor a backend that draws its branch before evolving, butRuntimeOnlyfor one that draws it from the live state. The default returnsdefault_stochastic_kind(); backends that handle an operation differently override this.- Parameters:
op_or_instruction – An operation, or an instruction whose operation is classified.
- Returns:
- Return type:
- 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 throughfuse_pass(),reorder_pass(),canonical_decompose_pass(),remove_swaps_pass(),simplify_pass()ormapping_pass(). A flag finds the pass it acts on by itsspec().name, so a pass that no flag names is never removed by one.- Returns:
A
PassPipeline. The default is empty.- Return type:
- fuse_pass(*, threshold=None)[source]¶
Return the pass that
execute(fuse=True)orfuse_threshold=ninstalls.Backends with their own fusion pass override this, so the flag retunes that pass instead of replacing it.
- 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:
- Returns:
The reorder pass.
- Raises:
NotImplementedError – In the default implementation.
- Return type:
- 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
SimplifyPasswithDEFAULT_SIMPLIFY_PASSES.
- mapping_pass()[source]¶
Return the pass that maps circuits onto this backend’s topology.
execute()installs it whentopology()is notAllToAll, unlessmapping=False. Backends with their own mapping override this; the pass should report the spec name"map_circuit"so themappingflag finds it.- Returns:
The default is
MapCircuitPasswith no target, which maps ontomapping_target(self.topology()).- Return type:
- accepts_pass(p)[source]¶
Return whether this backend can run pass
p.apply_passes()raisesUnacceptedPassErrorfor a pass the backend refuses, instead of skipping it. The default accepts every pass.
- delegates_pass(p)[source]¶
Return whether this backend runs pass
pitself.For a delegated pass,
apply_passes()does not callAbstractPass.apply(); it records aPassResultwithmetadata={"delegated": True}and leaves the work to the backend’sLocalBackend.compile()orLocalBackend.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
circuiton this backend and return its results.To request specific amplitudes or expectation values, push
AmplitudeorExpectationValueinstructions intocircuitand read them fromresults.zstates.The preparation flags (
fuse,canonicaldecompose,reorderqubits,remove_swaps,simplify) adjust the backend’sdefault_passes()instead of replacing them. Each speaks about one kind of pass:Noneleaves that pass as the backend declared it,Falsedrops 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. Sofuse=Falsemeans “the backend’s pipeline, without fusion”. A pass that no flag names stays even when every flag isFalse.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.
passesare appended after all of that, as given; nothing is deduplicated.On a backend whose
topology()is notAllToAll, the circuit is mapped onto the device withmapping_pass()unlessmapping=False. When the circuit has no classical bits, bitqof each result still reads logical qubitq, 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=Truerewrites the circuit withsimplify_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
Circuitor a list of circuits. Local backends also take aSweepExperiment, 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.Randomto 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.Nonemaps when the topology is notAllToAll.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 intocircuitwithevaluate()and runs as its own execution, with a seed derived fromseedorrng, so points are independent and a repeated sweep with the sameseedgives the same results. Every dictionary must bind all free symbols. An empty list runscircuitonce.strict_pass_order (bool) – On a remote backend that does not declare
"pass_order_honored", refuse a non-emptypassesinstead of submitting it as an unordered set.
- Returns:
A
QCSResults. A list of circuits gives a list of results in the same order;param_gridor aSweepExperimentgives one result per point (a list of such lists for a list of circuits).- Raises:
TypeError – If both
seedandrngare given, or a flag has the wrong type (for examplefuse=0).NotImplementedError – If
param_gridis given to a remote backend that does not support it (such asMimiqRemoteBackend), or a flag asks for a pass the backend cannot build.ValueError – If
mapping=Trueon a backend whose topology isAllToAll, or the pipeline holds both a mapping and a reorder pass.RemotePassOrderError – See
strict_pass_order.
- expectation(state, op, *qubits)[source]¶
Return
⟨ψ|op|ψ⟩onstate, without changing it.Backends that declare the
"expectation_state"capability override this; the default raisesNotImplementedError.- Parameters:
- Returns:
The complex expectation value.
- Raises:
NotImplementedError – In the default implementation.
- Return type:
- class LocalBackend[source]¶
Bases:
BackendBase class for simulators that run in this process.
Subclasses implement
build_state(),compile()andevolve(), plus theBackendidentity members; they may overrideprepare_trajectory(),recompile_per_trajectory(),bind()andcompile_progress(), and opt into the runtime-loss driver withuses_loss_driver(),apply_instruction(),sample_kraus()andapply_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
XandCXgates 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
nsamplestimes.>>> 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.
compilehas 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()
executedoes the rest. The final measurements never reachevolve: 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.
- 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 onrecompile_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 returnsDefaultCompiledCircuit(circuit).- Return type:
- prepare_trajectory(compiled, rng)[source]¶
Refresh
compiledfor one Monte Carlo trajectory.Backends whose compiled form holds random choices (sampled mixed-unitary branches, …) override this to redraw them. The default returns
compiledunchanged.- Parameters:
compiled (CompiledCircuit) – The result of
compile().rng – The trajectory generator,
RNGs.trajectory.
- Returns:
The compiled circuit for this trajectory.
- Return type:
- 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,ExpectationValueand 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()passesRNGs.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 expectscallback(i, total)once per step, withithe 1-based step andtotalthe number of steps orNone.stopped – The
stoppedargument ofexecute(), passed through unchanged.
- Returns:
the evolved state and a
Fidelity. A plain float is also accepted:1.0is read asExactFidelity, any other value asTruncationLowerBound, andNoneasUnknownFidelity.- Return type:
A tuple
(state, fidelity)
- recompile_per_trajectory(circuit)[source]¶
Return whether
compile()runs again for every trajectory.The default returns
Truewhencircuithas a mixed-unitary Kraus channel, for backends that draw its branch while compiling. Backends that draw it inprepare_trajectory()orevolve()override this to returnFalseand compile once.- Parameters:
circuit – The prepared circuit.
- Returns:
Whether to recompile per trajectory.
- Return type:
- bind(compiled, params)[source]¶
Substitute
paramsinto a compiled parametric circuit.The default evaluates the source circuit with
paramsand callscompile()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
CompiledParametricCircuitwhosesourceis the symbolic circuit.params (dict) – Values for the free symbols, as for
evaluate().
- Returns:
A fully bound
CompiledCircuit.- Return type:
- 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-registerzregisterover the samples. Push the quantity to minimize into that register, for example withpush_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 fromscipy.optimize.minimize();"CMAES"needs thecmaesextra (pip install 'mimiqcircuits[cmaes]').maxiters: iteration limit, orNonefor 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,passesand so on. With a fixedseedevery 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
experimentis a circuit; must beNoneotherwise.return_history – Also keep every evaluated run.
**kwargs – Experiment fields (with a circuit only) and
execute()options.
- Returns:
An
OptimizationResultswith the lowest-costOptimizationRunand, withreturn_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
zregisterthe circuit does not have, or a circuit and initial values that do not form a valid experiment.TypeError – If
initparamsor an experiment field is given together with an experiment.
Examples
A one-qubit backend for circuits of
RYgates followed by⟨Z⟩measurements. It tracks the rotation angle and writescos(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, attheta = 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=1is 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
progressand callscompile(). Backends whose compilation has countable steps (such as fusing gates into tensors) override this to open a stage onprogressand step it.
- uses_loss_driver()[source]¶
Return whether
execute()resolves runtime loss throughevolve_with_loss().Runtime loss comes from Kraus channels with a
LossyOperatorbranch: which qubit is lost depends on the branch that fires. A backend opts in by returningTrue, implementingapply_instruction()andsample_kraus(), and giving its state aLossState(seeState.get_loss_state()). The default returnsFalse.
- apply_instruction(state, inst, *, rng=None)[source]¶
Apply one instruction to
statefor 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.0when 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
LossyOperatorkeeps 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
circuitonstatewhile resolving qubit loss as it happens.The lost qubits are tracked in the state’s
LossStateand interpreted aslower_losses()does. The circuit is walked as alternating runs and loss events: each run of instructions on present qubits goes toapply_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 whenuses_loss_driver()returnsTrueand the circuit has a loss that can only be resolved while it runs.- Parameters:
state – A state from
build_state()whoseget_loss_state()works.circuit – The prepared circuit.
lossmodel – The
LossModelthat decides how an operation on partly lost qubits is rewritten.rng – The noise generator.
callback – Called as
callback(i, total)once per instruction ofcircuit, withifrom 1 tototal, 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), wherefidelityis 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
circuiton this backend and return its results.Takes every argument of
Backend.execute(), plus the ones below.circuitmay also be aSweepExperiment; passing one together withparam_gridraisesTypeError, 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=Falseit raisesValueError.stopped – Passed through unchanged to
evolve()andevolve_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 –
Trueto show progress bars withTqdmProgress,Falsefor none, or aProgresssink.
- Returns:
See
Backend.execute().
See also
Backend.execute()for the shared arguments.
- class RemoteBackend[source]¶
Bases:
BackendBase class for simulators that run on a remote service.
Subclasses implement
submit(), plus theBackendidentity members; they may overrideexecute(). The inheritedexecute()checks the pass order, callssubmit(), and blocks on the returned job’swait().See also
MimiqRemoteBackend, the backend for the MIMIQ cloud service.- abstract submit(circuits, nsamples, **kwargs)[source]¶
Send
circuitsto the service and return a job handle.execute()calls it with the keywordsrngs(anRNGsbundle),passes,callback,param_gridandstrict_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: aQCSResults, 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
circuitwithsubmit()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
passesis non-empty,strict_pass_orderisTrueand the backend does not declare"pass_order_honored".TypeError – If both
seedandrngare given.
- class State[source]¶
Bases:
ABCSimulation state that a
LocalBackendbuilds 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,ExpectationValueand similar operations.Subclasses implement
num_qubits,num_bits,num_zvars,amplitude(),sample(),classical_bitsandcomplex_values; they may overrideexpectation(),reset()andget_loss_state(), whose defaults raiseNotImplementedError.See also
LocalBackend, whose example defines a complete state.- abstract amplitude(bs)[source]¶
Return the amplitude
⟨bs|ψ⟩of a computational basis state.- Parameters:
bs – The basis state, as a
BitStringwith one bit per qubit.- Returns:
The complex amplitude.
- Return type:
- abstract sample(nsamples, rng=None)[source]¶
Draw
nsamplesmeasurement outcomes of all qubits from the state.The state is not changed.
rngis 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. Withoutrngthe simulator draws fresh entropy.- Parameters:
nsamples (int) – Number of outcomes to draw.
rng (Random | None) – The generator to draw from.
LocalBackend.execute()passesRNGs.shothere.
- Returns:
A list of
nsamplesBitString, one bit per qubit.- Return type:
- 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 raisesNotImplementedError.- Parameters:
op – The operator to measure.
*qubits (int) – The qubits
opacts on, 0-based.
- Returns:
The complex expectation value.
- Raises:
NotImplementedError – If the state does not support it.
- Return type:
- abstract property classical_bits¶
The classical register, as a
BitString.The execute driver stores it as one entry of
QCSResults.cstatesper trajectory.
- abstract property complex_values¶
The z-register, as a list of complex numbers.
The execute driver stores it as one entry of
QCSResults.zstatesper 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 inreset(), and override this to return it. The default raisesNotImplementedError.
- class LossState(n_or_flags)[source]¶
Bases:
objectPer-qubit register that records which qubits are lost.
It sits next to the quantum, classical and complex registers of a
State. EntryqisTruewhen qubitqhas 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 inState.reset(), and returns it fromState.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.
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]
- class RNGs(shot, noise, trajectory, pass_)[source]¶
Bases:
objectFour 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 fromseedorrngand hands each stream to the stage it belongs to. Build one withfrom_seed()orfrom_generator().- shot¶
Sampling shots from the final state.
- Type:
- noise¶
Kraus and mixed-unitary noise sampling during
LocalBackend.evolve().- Type:
- trajectory¶
Per-trajectory work, such as
LocalBackend.prepare_trajectory()and loss sampling.- Type:
- pass_¶
Randomised compilation passes, read through
PassContext.rng.- Type:
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
- class Progress[source]¶
Bases:
ABCDestination for execution progress, given to
LocalBackend.execute()asprogress.Subclasses implement
stage().NoProgressdraws nothing andTqdmProgressdraws 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()
- class Stage[source]¶
Bases:
ABCA single progress bar opened by
Progress.stage().
- class NoProgress[source]¶
Bases:
ProgressSink that draws nothing; the default of
LocalBackend.execute().Its stages ignore
Stage.step()andStage.finish().
- class TqdmProgress(*, leave=False)[source]¶
Bases:
ProgressSink 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.
- to_progress(progress)[source]¶
Turn the
progressargument ofLocalBackend.execute()into aProgress.- Parameters:
progress – A
Progress, returned as it is, or a bool:TruegivesTqdmProgress,FalsegivesNoProgress.- Returns:
The
Progresssink.- Raises:
TypeError – For any other type.
- Return type:
- class MimiqRemoteBackend(connection, *, algorithm='auto', label=None, poll_interval=1.0)[source]¶
Bases:
RemoteBackendBackend that runs circuits on the MIMIQ cloud service.
It wraps a
MimiqConnection(or anothermimiqcircuits.remote.RemoteConnection) so that cloud execution takes the sameseed,rngandpassesarguments as a local backend and returns the sameQCSResults. The simulator algorithm is fixed at construction; the other server options (bonddim,entdim,mpscutoff,mpsmethod,mpotraversal,timelimit,noisemodel) are given toexecute()orsubmit().- Parameters:
connection – An authenticated connection, or any object with callable
submit(...)andget_results(...)methods. The constructor does not log in, so callconnection.connect()first.algorithm (str) –
"auto","mps"or"statevector". It also setscapabilities()andlimits().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
connectionlackssubmitorget_results.
Notes
The capabilities are decided on the client, since the service does not report them: a fixed set, plus
"bond_dim"and"schmidt_rank"whenalgorithmis"auto"or"mps"."pass_order_honored"is not declared, because the service takes a flat set of options (remove_swaps,fuse, …), not an ordered pipeline. A non-emptypasseswith the defaultstrict_pass_order=TrueraisesRemotePassOrderError. Withstrict_pass_order=Falsethe passes the service knows are translated into options, and the others are dropped with oneUserWarning.param_gridraisesNotImplementedError. Evaluate the circuit for each point and execute the results instead.noisemodel=together with a pass named"apply_noise_model"inpassesraisesValueError.seedandrngare mutually exclusive. The seed sent to the service is derived from them through anRNGsbundle, so it is not the integer passed in.A single circuit returns a single
QCSResults; a list returns a list of the same length. A list of more than one circuit needsalgorithmset to"mps"or"statevector"; with"auto"it raisesValueError.With
algorithm="statevector", anoisemodelfails 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.execute()waits for the job without a time limit. For a bounded wait, callsubmit()and thenjob.wait(timeout=seconds), which raisesTimeoutError.
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;
bonddimis 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()
- capabilities()[source]¶
Return the capabilities, decided on the client.
"bond_dim"and"schmidt_rank"are included only whenalgorithmis"auto"or"mps".
- limits()[source]¶
Return the limits known to the client.
max_samplesis the largest number of shots the client sends;max_bond_dimis set only whenalgorithmis"auto"or"mps".
- 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
circuitsto 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
RNGsbundle or an integer seed, folded into the single seed sent to the service;Nonedraws 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.strict_pass_order (bool) – See
Backend.execute().fuse (bool | None) – Server-side gate fusion;
Nonelets 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
NoiseModelapplied to each circuit before it is uploaded.**kwargs – Only
simplifyandmapping, which must be falsy: the service runs neither, and its topology isAllToAll.
- Returns:
A job handle. Its
request_idis the service’s job id, and itswait(timeout=None)blocks until the job is done and returns the list ofQCSResults, with their fidelities converted toFidelitytypes (exact for the state-vector simulator, a truncation lower bound for MPS, unknown otherwise). With atimeoutin seconds it raisesTimeoutErrorinstead of waiting longer.- Raises:
ValueError – If a preparation flag is given with a non-empty
passes, ornoisemodelwith a pass named"apply_noise_model".NotImplementedError – If
param_gridis not empty, orsimplifyis set.ValueError – If
mappingis set.RemotePassOrderError – See
strict_pass_order.TypeError – For an unknown keyword.
- 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
circuitto the service and wait for the results.To request specific amplitudes, push
Amplitudeinstructions intocircuitand readresults.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.Randomto draw the seed from.passes (PassPipeline | None) – See the class notes.
callback – Not used.
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
QCSResultsfor a single circuit, or a list of them for a list of circuits.- Raises:
TypeError – If both
seedandrngare given, or for an unknown keyword.ValueError – See
submit().NotImplementedError – See
submit().RemotePassOrderError – See
strict_pass_order.
- 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(): anOptimizationExperiment, 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’salgorithm.- Parameters:
experiment – An
OptimizationExperiment, a list of them, or a symbolic circuit.initparams – Initial values when
experimentis a circuit.return_history (bool) – Also return every evaluated run.
seed (int | None) – Integer seed. Mutually exclusive with
rng.rng – A
random.Randomto 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
optimizemethod, or bothseedandrngare 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
seedorrngsinto a single integer seed.- Parameters:
- Returns:
The seed, or
Nonewhen both arguments areNone.- Raises:
TypeError – If both are given, or
rngshas 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
ndistinct seeds frombase_seed.The
param_gridloop ofLocalBackend.execute()uses it so that each point gets its own random stream; reusingbase_seedfor every point would correlate their outcomes. The result depends only onbase_seedand the position, and two different base seeds, however close, have no seed in common.- Parameters:
- Returns:
A list of
n63-bit seeds, or[None] * nwhenbase_seedisNone.- Return type:
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
circuitinto 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 inquantum_circuittouches any of its bits, otherwise moving it past that operation would change what it reads.Trailing
GateID— dropped as a no-op.GateX/GateY/GateZare NOT absorbed:YandZcarry phases that would corrupt amplitude lookups, andXabsorbed alone would require XOR-ing the qubit-flip pattern into every user-suppliedbitstringsentry for amplitudes to stay consistent. Keeping all Paulis inquantum_circuitmeans 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/SetBit1based on absorbed X parity). AResetwhose 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 intoquantum_circuit.If the source has no classical register, the projection is synthesised over an identity bit↔qubit mapping (bit
imirrors qubiti, 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:
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,OrandXor. 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. AMeasure(q, b)whose qubit is outsidesampleleaves bitbuntouched, so it reads zero unless an earlier instruction set it.This is the reference implementation;
CompiledProjectiongives the same results faster for many shots.- Parameters:
projection (Circuit) – The projection circuit returned by
extract_projection().sample (BitString) – One computational-basis outcome, one bit per qubit of the evolved state.
- Returns:
The classical register after the projection, of length
projection.num_bits().- Raises:
ValueError – If
projectionholds any other operation.- Return type:
See also
extract_projection(), whose example uses it.
- needs_trajectories(circuit)[source]¶
Return whether
circuitmust 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 byextract_projection(), since trailing measurements do not need per-shot evolution.
- needs_loss_sampling(circuit)[source]¶
Return whether
circuithas loss operations to resolve before simulation.
- any_mixed_unitary(circuit)[source]¶
Return whether
circuithas a mixed-unitary Kraus channel.This is the default of
LocalBackend.recompile_per_trajectory().
- remap_projection_qubits(projection, qubit_order, do_remap)[source]¶
Rename the qubits read by the
Measureinstructions of a projection.Every
Measure(q, b)becomesMeasure(qubit_order[q], b); other instructions are copied as they are.- Parameters:
- Returns:
A new circuit, or
projectionwhendo_remapisFalse. The input is never changed.- Return type:
- class CompiledProjection(num_bits, steps=<factory>, _plans=<factory>)[source]¶
Bases:
objectA projection circuit compiled for block evaluation.
Build one with
from_circuit()and evaluate a whole block of shots withevaluate_batch(). An instance can be reused across blocks and holds no per-shot state. It gives the same results asevaluate_projection()applied to each shot.- num_bits¶
Width of the classical bitstring the projection produces, equal to
projection.num_bits().- Type:
- steps¶
The straight-line program, before it is specialised to a sample width. Internal representation, subject to change.
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
projectionfor 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
projectionholds an operation other thanMeasure,SetBit0,SetBit1,Not,And,OrandXor.- Return type:
- evaluate_batch(samples)[source]¶
Evaluate the projection for every shot in
samples.When the projection copies qubit
binto bitbfor every bit and the samples are as wide as the register, the input bitstrings are returned as they are, without copying.
- evaluate(sample)[source]¶
Evaluate the projection for a single shot.
Same result as
evaluate_projection().evaluate_batch()is faster for many shots.
- class StochasticKind(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Bases:
IntEnumWhen a backend resolves the randomness of an operation.
The members are ordered,
Deterministic < TrajectorySampleable < RuntimeOnly, somaxgives the kind of a group of operations.Deterministic: no randomness;LocalBackend.compile()can lower the operation from the circuit alone.TrajectorySampleable: random, but resolvable inLocalBackend.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 duringLocalBackend.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:
TrajectorySampleableif mixed-unitary, otherwiseRuntimeOnly.Lossand every measurement:RuntimeOnly.Everything else:
Deterministic.
- Parameters:
op – An operation, or an instruction whose operation is classified.
- Returns:
- Return type:
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:
- Return type:
- is_trajectory_sampleable(backend, x)[source]¶
Return whether
backendclassifiesxasTrajectorySampleable.
- is_stochastic(backend, x)[source]¶
Return whether
backendclassifiesxas anything butDeterministic.
- first_stochastic(backend, circuit)[source]¶
Return the index of the first instruction of
circuitthatbackenddoes not classify asDeterministic, orNone.
- last_stochastic(backend, circuit)[source]¶
Return the index of the last instruction of
circuitthatbackenddoes not classify asDeterministic, orNone.
- first_runtime_only(backend, circuit)[source]¶
Return the index of the first instruction of
circuitthatbackendclassifies asRuntimeOnly, orNone.Unlike
first_stochastic(), it skipsTrajectorySampleableinstructions, which a backend can resolve before evolving.
- last_runtime_only(backend, circuit)[source]¶
Return the index of the last instruction of
circuitthatbackendclassifies asRuntimeOnly, orNone.
Modules
Abstract base classes for simulator backends. |
|
Capability vocabulary, numeric limits, topology, and admission types. |
|
Compiled-circuit types and the metadata they carry. |
|
Compiled form of a projection circuit. |
|
Concrete circuit-preparation passes. |
|
Typed fidelity values returned by |
|
Final-block analysis. |
|
Variational optimization of a parametric circuit on a local backend. |
|
Optimization-pass framework. |
|
Progress reporting for |
|
Concrete |
|
|
Return |