mimiqcircuits.backends¶
mimiqcircuits.backends — abstract Backend interface for quantum simulators.
Mirrors the Julia AbstractQCSs.jl surface so simulators plug in uniformly across both languages.
Module map:
capabilities, limits, topology -> .capabilities Backend, LocalBackend, RemoteBackend -> .backend Fidelity ADT -> .fidelity CompiledCircuit subclasses + bind -> .compiled AbstractPass + PassPipeline -> .passes Concrete passes (RemoveSwapsPass, …) -> .concrete_passes
Recommended import:
from mimiqcircuits.backends import Backend, LocalBackend, …
- class mimiqcircuits.backends.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 simulator advertises.
None for any field means “unbounded” (or “not applicable” for fields like max_bond_dim on a state-vector simulator).
- __init__(max_qubits=None, max_bond_dim=None, max_classical_bits=None, max_zvars=None, max_samples=None, max_circuit_depth=None)¶
- class mimiqcircuits.backends.Topology[source]¶
Bases:
objectBase class for device / connectivity topologies.
- class mimiqcircuits.backends.AllToAll[source]¶
Bases:
TopologyAll-to-all connectivity (no constraint). Default for simulators.
- __init__()¶
- class mimiqcircuits.backends.CouplingMap(edges)[source]¶
Bases:
TopologyCoupling map: each edge
(i, j)means qubitsiandjcan interact directly. 1-based qubit indices to match the rest of MIMIQ.- __init__(edges)¶
- class mimiqcircuits.backends.LinearChain(n)[source]¶
Bases:
TopologyLinear chain of
nqubits with nearest-neighbor coupling.- __init__(n)¶
- class mimiqcircuits.backends.AdmissionResult[source]¶
Bases:
objectBase class for
can_handle(backend, circuit)results.
- class mimiqcircuits.backends.Admissible[source]¶
Bases:
AdmissionResultThe backend can execute the circuit.
- __init__()¶
- class mimiqcircuits.backends.Marginal(warning)[source]¶
Bases:
AdmissionResultThe backend can execute the circuit but it is near a limit (memory, bond dimension, runtime).
warningis a user-facing message; downstream code still treats this as admissible.- __init__(warning)¶
- class mimiqcircuits.backends.Inadmissible(reason)[source]¶
Bases:
AdmissionResultThe backend cannot execute the circuit.
- __init__(reason)¶
- mimiqcircuits.backends.is_admissible(result)[source]¶
TrueforAdmissibleandMarginal.
- exception mimiqcircuits.backends.UnsupportedCapabilityError(backend_name, capability, detail='')[source]¶
Bases:
ExceptionRaised when a backend is asked to run a feature it does not advertise in
Backend.capabilities().Backends use this to fail loudly rather than silently degrade. Tests rely on it to verify a backend’s capability set is honest (no “positive lies”).
- mimiqcircuits.backends.register_cap_probe(capability, factory)[source]¶
Register a probe-circuit constructor for
capability.factory()must return a Circuit whose execution requires the named capability. Conformance tests use this registry to assert that backends reject what they do not advertise — silently accepting an undeclared feature would let “positive lies” slip through.
- class mimiqcircuits.backends.Fidelity[source]¶
Bases:
objectBase class for typed fidelity values. See the module docstring for the list of variants and the reducer functions.
- class mimiqcircuits.backends.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.
- __init__()¶
- class mimiqcircuits.backends.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.- __init__()¶
- class mimiqcircuits.backends.TruncationLowerBound(value)[source]¶
Bases:
FidelityA single scalar lower bound on the whole-circuit fidelity.
Typical for MPS / MPO simulators, where
valueis the product of singular-value tails discarded during compression.- __init__(value)¶
- class mimiqcircuits.backends.LowerBoundPerStep(values)[source]¶
Bases:
FidelityPer-step lower-bound contributions.
as_lower_boundreturnsprod(clip(values, 0, 1)), which is a lower bound on the circuit fidelity only when successive truncation errors are uncorrelated. If your backend cannot make that assumption, collapse to a singleTruncationLowerBoundat construction time.- __init__(values)¶
- class mimiqcircuits.backends.EstimatedFidelity(mean, stderr)[source]¶
Bases:
FidelitySample-based fidelity estimate with a standard error.
Use for randomised benchmarking, direct fidelity estimation, or cross-entropy benchmarking.
as_lower_boundreturnsmax(0, mean − 3·stderr);as_intervalreturns the ±1σ band.- __init__(mean, stderr)¶
- mimiqcircuits.backends.as_lower_bound(f)[source]¶
Reduce
fto a conservative scalar lower bound.Returns
nanwhenfisUnknownFidelityso that statistics over mixed-type fidelities do not silently treat “unknown” as “good”.
- mimiqcircuits.backends.as_expected(f)[source]¶
Reduce
fto a central / expected scalar.For
TruncationLowerBoundthe lower bound is the estimate; forEstimatedFidelityit is the sample mean. ReturnsnanforUnknownFidelity.
- mimiqcircuits.backends.as_interval(f)[source]¶
(lo, hi)band. ±1σ forEstimatedFidelity; otherwise(as_lower_bound, as_expected).
- class mimiqcircuits.backends.CompiledCircuit[source]¶
Bases:
objectBackend-specific deterministic representation of a circuit.
Returned by
LocalBackend.compile(). Concrete backends subclass to carry whatever payload they need — an MPO for an MPS simulator, a plainCircuitfor a state-vector backend, a streaming thunk for an out-of-core simulator, …Every subclass exposes two attributes:
metadata— aCompileMetadatadescribing compile-time side effects;source— the wrapped, backend-specific artifact.
- property metadata: CompileMetadata¶
- property source¶
The backend-specific artifact wrapped by this compiled circuit (e.g. a
Circuit, an MPO, a streaming thunk).
- class mimiqcircuits.backends.DefaultCompiledCircuit(_source, _metadata=<factory>)[source]¶
Bases:
CompiledCircuitGeneric passthrough wrapper.
Use this when your backend’s
compilestep is effectively the identity — for example a state-vector simulator that consumes the inputCircuitdirectly.- property metadata: CompileMetadata¶
- property source¶
The backend-specific artifact wrapped by this compiled circuit (e.g. a
Circuit, an MPO, a streaming thunk).
- __init__(_source, _metadata=<factory>)¶
- class mimiqcircuits.backends.CompiledParametricCircuit(_source, _metadata=<factory>)[source]¶
Bases:
CompiledCircuitCompiled artifact that still carries free symbolic parameters.
Produced by
LocalBackend.compile()when the input is symbolic and the backend advertises the"parametric"capability. Resolve the parameters by callingLocalBackend.bind().- property metadata: CompileMetadata¶
- property source¶
The backend-specific artifact wrapped by this compiled circuit (e.g. a
Circuit, an MPO, a streaming thunk).
- __init__(_source, _metadata=<factory>)¶
- class mimiqcircuits.backends.CompileMetadata(measures=<factory>, active_qubits=<factory>, qubit_flips=<factory>, qubit_permutation=None, measure_action_counts=<factory>, prefix_endpoint=0)[source]¶
Bases:
objectCompile-time side effects carried alongside a
CompiledCircuit.- measures¶
Measurement-analysis entries (classifies each classical bit as Unused / Direct / Flip / Const0 / Const1). Empty when analysis has not run.
- Type:
- active_qubits¶
Qubit indices that must be simulated; the others can be dropped because they are provably
|0⟩at measurement.
- qubit_permutation¶
Composed permutation applied by the pass pipeline.
Nonewhen the pipeline is identity on qubit indices.
- measure_action_counts¶
Frequency of each measurement-action branch (debug aid).
- prefix_endpoint¶
Index of the last instruction folded into the deterministic prefix when the backend splits prefix from stochastic suffix;
0when no split applies.- Type:
- __init__(measures=<factory>, active_qubits=<factory>, qubit_flips=<factory>, qubit_permutation=None, measure_action_counts=<factory>, prefix_endpoint=0)¶
- exception mimiqcircuits.backends.UnboundSymbolicError(backend_name)[source]¶
Bases:
ExceptionRaised when
LocalBackend.compile()is handed a circuit that still has free symbolic parameters but the backend does not advertise the"parametric"capability.
- class mimiqcircuits.backends.PassParam[source]¶
Bases:
objectBase class for the JSON-safe sum used to serialise pass parameters.
The tagged variants (
PStr,PInt,PFloat,PBool,PSym,PList,PDict) keep type information a plain dict would lose on the wire — e.g."greedy"(aPStr) must not silently degrade and come back as aPSym. Equality is tag-sensitive:PSym("x") != PStr("x").
- class mimiqcircuits.backends.PSym(value)[source]¶
Bases:
PassParamPass parameter that is semantically a
Symbol(Julia) orenum.Enum-like in Python. Distinct fromPStrat the tag level.- __init__(value)¶
- class mimiqcircuits.backends.PList(items: 'tuple[PassParam, ...]')[source]¶
Bases:
PassParam- __init__(items)¶
- class mimiqcircuits.backends.PDict(items: 'tuple[tuple[str, PassParam], ...]')[source]¶
Bases:
PassParam- __init__(items)¶
- mimiqcircuits.backends.to_pass_param(x)[source]¶
Coerce a common Python value into a
PassParam.The bool-before-int check is load-bearing:
boolis a subclass ofintin Python, soisinstance(True, int)isTrueand reversing the order would tag every boolean asPInt.
- class mimiqcircuits.backends.PassSpec(name, parameters=(), requires=(), conflicts=())[source]¶
Bases:
objectDeclarative summary of a pass.
Used for equality / memoisation (two passes with the same spec have the same hash and compare equal), for remote dispatch (the spec is the only thing shipped over the wire), and for observability. Equality is structural.
requiresnames other passes that must run before this one;conflictsnames passes that cannot coexist with this one in the same pipeline. Both are advisory.- __init__(name, parameters=(), requires=(), conflicts=())¶
- class mimiqcircuits.backends.PassResult(qubit_permutation=None, metadata=<factory>)[source]¶
Bases:
objectSide effects returned from
AbstractPass.apply().qubit_permutationisNonewhen the pass leaves qubit indices unchanged. Any pass that does relabel qubits must return the relabel here so the pipeline can compose permutations and un-shuffle downstream outputs.metadatais free-form pass-specific information (timings, gate counts, …) surfaced for observability.- __init__(qubit_permutation=None, metadata=<factory>)¶
- class mimiqcircuits.backends.PassContext(backend=None, rng=<factory>, bitstrings=<factory>, features=<factory>)[source]¶
Bases:
objectInputs a pass needs but should not fetch from global state.
backendis the Backend the pipeline is compiling for, orNonefor backend-agnostic runs.rngis the dedicated pass-internal RNG.bitstringsare user-supplied amplitude targets in the original qubit space; the pipeline rewrites them into post-pass space as permutations compose.featuresare detected on the input circuit and filter passes viaAbstractPass.preserves().- __init__(backend=None, rng=<factory>, bitstrings=<factory>, features=<factory>)¶
- class mimiqcircuits.backends.AbstractPass[source]¶
Bases:
ABCBase class for circuit-transformation passes.
Subclasses implement:
spec()— return aPassSpecdescribing the pass (used for equality, serialisation, and remote dispatch).apply()— return(new_circuit, PassResult).preserves()— override when the pass breaks a circuit feature; the default returnsTruefor every feature. The pipeline filters passes by feature when the input circuit has a feature that the pass must preserve.
Recognised feature tokens:
"feed_forward","midcircuit_measure","parametric","loss","exact_equivalence","strict_qubit_count".
- class mimiqcircuits.backends.PassPipeline(passes=<factory>)[source]¶
Bases:
objectAn ordered, iterable sequence of passes.
Run via
apply_passes(), which composes each pass’squbit_permutationinto a single permutation. Callers use the inverse of that permutation to map samples andAmplitude/ExpectationValueresults back to the user’s original qubit space.- passes: list[AbstractPass]¶
- __init__(passes=<factory>)¶
- mimiqcircuits.backends.apply_passes(pipeline, ctx, circuit)[source]¶
Run
pipelineagainstcircuit.Returns
(transformed_circuit, composed_permutation, per_pass_results).composed_permutationisNonewhen every pass left qubit indices unchanged.Raises
UnacceptedPassErrorif the backend rejects any pass. When the backend reportsdelegates_pass(p) is Truethe pass is not run here: the pipeline records a marker result and the backend handles the pass natively inside itscompileorevolve.
- exception mimiqcircuits.backends.UnacceptedPassError(backend_name, pass_name)[source]¶
Bases:
ExceptionRaised when a pipeline contains a pass the backend rejects.
The backend’s
Backend.accepts_pass()is the gate; the pipeline fails loudly rather than silently dropping a pass the user explicitly requested.
- exception mimiqcircuits.backends.RemotePassOrderError(backend_name)[source]¶
Bases:
ExceptionRaised when an ordered pipeline is submitted to a remote backend that does not advertise the
"pass_order_honored"capability whilestrict_pass_order=True.Pass
strict_pass_order=Falseto opt into an unordered submission (recognised passes are translated into the server’s flat option set; unrecognised passes are dropped with a warning).
- class mimiqcircuits.backends.Backend[source]¶
Bases:
ABCAbstract base class for any simulator backend.
A concrete backend must:
advertise its feature set via
capabilities(),limits(),topology();implement
execute()(or subclassLocalBackend/RemoteBackendand inherit a sensible default).
Pick the right base for your simulator:
LocalBackend— the simulator runs in-process and you can hand it aStateit mutates with each instruction.RemoteBackend— the simulator runs elsewhere (cloud service, queued executor) and your wrapper submits jobs and polls for results.
See Implementing a Custom Backend.
- can_handle(circuit)[source]¶
Default admission check against
limits()and the backend’s advertisedcapabilities().Backends with richer admission criteria (bond-dimension estimates, hardware connectivity, gate-set whitelists) should override.
Rejects (returns
Inadmissible) when:the circuit exceeds one of
max_qubits/max_classical_bits/max_zvarsdeclared bylimits();the circuit contains a loss-bearing operation (
LossErr,QubitLoss) but the backend does not advertise the"loss"capability.
Returns
Admissibleotherwise.
- stochastic_kind(op_or_instruction)[source]¶
Classify how this backend resolves
op_or_instruction—StochasticKind.Deterministic,StochasticKind.TrajectorySampleable, orStochasticKind.RuntimeOnly.The default delegates to
default_stochastic_kind()(mix-unitary Kraus is TS; non-mix-unitary Kraus, mid-circuitMeasure, andLossErrare RT; everything else Deterministic). Backends that handle a specific op type differently override this method.Backend-dependent: a
MixedUnitaryisTrajectorySampleablefor an MPS-style sampler but could beRuntimeOnlyfor a backend that resolves it state-dependently. The classification lives on the backend, not on the op.
- abstract execute(circuit, *, nsamples=1000, seed=None, rng=None, passes=None, callback=None, param_grid=None, strict_pass_order=True)[source]¶
Run
circuiton this backend and returnQCSResults.Pass
circuitas a singleCircuitor a list of circuits — a list returns a list of results in the same shape.seedandrngare mutually exclusive sources of randomness; pass at most one. With neither, the backend draws fresh entropy. To request specific amplitudes, pushAmplitudeinstructions intocircuitand read the resultingresults.zstates.
- expectation(state, op, *qubits)[source]¶
Compute
⟨ψ|op|ψ⟩onstatenon-destructively.qubitsis the list of qubit indicesopacts on (0-based). Backends override when they advertise the"expectation_state"capability; the default raisesNotImplementedErrorso undeclared backends fail loudly rather than silently degrading.
- class mimiqcircuits.backends.LocalBackend[source]¶
Bases:
BackendBase class for simulators that run in the local process.
Subclasses implement a handful of primitives and inherit a full
execute()driver — the Python analog of the JuliaAbstractQCSs.executedriver. Once the hooks are wired up, routing (sampling-vs-trajectory), the final-block projection circuit, loss-sampling pre-pass, and amplitude lookups all work without any per-backend duplication.Required hooks:
build_state()— allocate a fresh zero state.compile()— turn aCircuitinto aCompiledCircuit(a backend-specific lowered form).evolve()— apply the compiled circuit to a state and return the mutated state plus a typedFidelity.
Optional hooks (sensible defaults provided):
prepare_trajectory()— refresh the compiled artifact once per Monte Carlo trajectory (default: identity).recompile_per_trajectory()— predicate; default returnsTrueiff the circuit contains a mixed-unitary Kraus channel.bind()— substitute parameters into a parametric compile artifact (default: re-compile after substitution).
- prepare_trajectory(compiled, rng)[source]¶
Refresh
compiledfor one Monte Carlo trajectory.Override when the compiled artifact contains stochastic elements (sampled mixed-unitary channels, sampled Kraus branches, …) that must be redrawn per trajectory. The default leaves
compiledunchanged, which is correct for fully deterministic compilation.
- recompile_per_trajectory(circuit)[source]¶
Return
Trueiffcompile()should be re-run for every trajectory. The default fires on any mixed-unitarykrauschannel: those backends sample a branch at compile time, so the compiled artifact has to be regenerated per trajectory to expose a fresh sample. Backends that own their per-trajectory sampling internally (insideprepare_trajectory()orevolve()) should override to returnFalse.Mirrors the Julia
AbstractQCSs.recompile_per_trajectory.
- bind(compiled, params)[source]¶
Substitute
paramsinto a parametric compiled circuit.The default implementation substitutes the symbols in the source circuit and re-runs
compile(). This is correct but pays the full compile cost at every parameter point. Override when your backend can re-bind a pre-compiled artifact in-place (slot maps, pre-baked gate templates, …).
- execute(circuit, *, nsamples=1000, seed=None, rng=None, passes=None, callback=None, param_grid=None, strict_pass_order=True, stopped=None, num_qubits=None)[source]¶
Run
circuiton this backend and returnQCSResults.Pass
circuitas a singleCircuitor a list of circuits — a list returns a list of results in the same shape.seedandrngare mutually exclusive sources of randomness; pass at most one. With neither, the backend draws fresh entropy. To request specific amplitudes, pushAmplitudeinstructions intocircuitand read the resultingresults.zstates.
- class mimiqcircuits.backends.RemoteBackend[source]¶
Bases:
BackendBase class for simulators that run on a remote service.
Subclasses implement
submit(), which dispatches the request and returns a job handle. The inheritedexecute()callssubmit(), then blocks on the returnedjob.wait().- abstract submit(circuits, nsamples, **kwargs)[source]¶
Send the request and return a job handle.
The job handle must expose a
wait()method that blocks until results are available and returnsmimiqcircuits.QCSResults(or a list whencircuitswas a list).
- execute(circuit, *, nsamples=1000, seed=None, rng=None, passes=None, callback=None, param_grid=None, strict_pass_order=True)[source]¶
Run
circuiton this backend and returnQCSResults.Pass
circuitas a singleCircuitor a list of circuits — a list returns a list of results in the same shape.seedandrngare mutually exclusive sources of randomness; pass at most one. With neither, the backend draws fresh entropy. To request specific amplitudes, pushAmplitudeinstructions intocircuitand read the resultingresults.zstates.
- class mimiqcircuits.backends.State[source]¶
Bases:
ABCComposite simulation state held by a backend.
A state bundles three registers:
the quantum register (whatever representation the backend uses; state vector, MPS, tensor network, …);
the classical-bit register written by measurements and
IfStatementoutcomes;the complex-valued register written by non-destructive observations (
Amplitude,ExpectationValue,BondDim, …).
Required surface for every subclass:
num_qubits,num_bits,num_zvars— register sizes.amplitude(),sample()— observation primitives.classical_bits,complex_values— register accessors.
Optional surface:
expectation()— backend overrides when it can compute⟨ψ|O|ψ⟩non-destructively (gated by the"expectation_state"capability).reset()— backend overrides when it can rebuild itself in place to the zero state.
- abstract sample(nsamples, rng=None, *, seed=None)[source]¶
Sample
nsamplesmeasurement outcomes from the state.Exactly one source of randomness is consumed:
rng(positional or keyword): arandom.Randomwhosegetrandbits(63)produces the seed forwarded to the simulator’s PRNG.seed(keyword): an int that seeds the simulator’s default PRNG directly.neither: the simulator draws fresh cryptographic entropy.
Passing both
rngandseedmust raiseTypeError. The two arguments are mutually exclusive.
- expectation(op, *qubits)[source]¶
Compute
⟨ψ|op|ψ⟩on this state.Most backends implement expectation on the Backend rather than the State (so they can route through the simulator’s compile / evolve machinery). State-level expectation is provided as a convenience hook for backends whose quantum register supports it directly.
- abstract property classical_bits¶
- abstract property complex_values¶
- class mimiqcircuits.backends.RNGs(shot, noise, trajectory, pass_)[source]¶
Bases:
objectFour independent RNG streams, one per simulation stage.
Keeping the streams separate means seeding one stage (for example sampling) does not affect the determinism of another (for example noise selection), even when the same execution touches both.
- shot¶
Sampling shots from the final state.
- Type:
- noise¶
Kraus and mixed-unitary noise sampling.
- Type:
- trajectory¶
Monte Carlo trajectory selection.
- Type:
- pass_¶
Randomised compilation passes (e.g. simulated-annealing reorderers).
- Type:
- Construct from a single int seed via :py:meth:`from_seed`.
- static from_seed(master)[source]¶
Derive four streams from a single
masterseed.XOR-tags the seed bits per stream — cheap, deterministic, and stable across Python versions, which matters because the downstream backends must reproduce results bit-for-bit from the same input.
- static from_generator(gen)[source]¶
Draw a master seed from
genand forward tofrom_seed().
- __init__(shot, noise, trajectory, pass_)¶
- class mimiqcircuits.backends.MimiqRemoteBackend(connection, *, algorithm='auto', label=None, poll_interval=1.0)[source]¶
Bases:
RemoteBackendCloud backend wrapping a
mimiqcircuits.remote.RemoteConnection.Construct with an authenticated connection (or any object that exposes callable
submit(...)andget_results(...)methods). The constructor pins the simulatoralgorithm(which in turn shapescapabilities()) and the label / poll cadence; all other server knobs (bonddim,entdim,mpscutoff,mpsmethod,mpotraversal,timelimit,noisemodel) are passed atsubmit()/execute()time.Caveats:
Capabilities are synthesised client-side. The server has no capability endpoint yet, so
capabilities()returns a conservative best-guess (_BASE_REMOTE_CAPABILITIESplus algorithm-conditional MPS tokens).``pass_order_honored`` is not declared. The server takes a flat bag of booleans (
remove_swaps,fuse, …) with no notion of pipeline order. A non-emptypasses=with the defaultstrict_pass_order=TrueraisesRemotePassOrderError. Opt out withstrict_pass_order=False: recognised passes are translated into legacy knobs and unrecognised ones are dropped with a singleUserWarning.``param_grid=`` raises
NotImplementedError. Loop on the client side instead:for params in grid: backend.execute(c.evaluate(params), nsamples=n, seed=...)
``noisemodel=`` and ``ApplyNoiseModelPass`` are mutually exclusive. Specifying both raises
ValueError.``_MimiqJob.wait()`` blocks indefinitely by default. Pass
timeout=<seconds>for a bounded wait that raisesTimeoutError.``seed=`` / ``rng=`` are mutually exclusive. The wire seed is a deterministic xor-fold of the four-stream
RNGsbundle derived from your input, not literally the integer passed in.The connection must be authenticated (
conn.connect()called) before the firstexecute(). The constructor does not trigger interactive auth, so an unauthenticated connection produces a 401 at submit time.Output shape mirrors input: a single
Circuitreturns a singleQCSResults; a list returns a list of matching length.``algorithm=”statevector”`` + ``noisemodel=`` is a server-side runtime error — state-vector cannot apply Kraus — and there is currently no client-side guard.
``algorithm=”statevector”`` makes MPS knobs meaningless (
bonddim=,entdim=,mpscutoff=,mpsmethod=,mpotraversal=,BondDim/SchmidtRankinstructions).capabilities()correctly omits:bond_dim/:schmidt_rankin that mode andlimits()returnsmax_bond_dim=None, butsubmit()still forwards the kwargs to the server, which is canonical.
Example:
import mimiqcircuits as mc conn = mc.MimiqConnection() conn.connect() backend = mc.backends.MimiqRemoteBackend(conn, algorithm="mps") results = backend.execute(circuit, nsamples=1000, seed=42, bonddim=64)
- capabilities()[source]¶
Synthesised client-side. Tensor-network annotations (
:bond_dim,:schmidt_rank) are declared only when the configuredalgorithmadmits MPS execution.
- limits()[source]¶
Static client-side limits.
max_bond_dimis dropped on state-vector deployments where bond dimension is meaningless.
- submit(circuits, nsamples=1000, *, rngs=None, passes=None, callback=None, param_grid=None, strict_pass_order=True, bonddim=None, entdim=None, mpscutoff=None, mpsmethod=None, mpotraversal=None, timelimit=None, noisemodel=None, **kwargs)[source]¶
Submit
circuitsto the remote server.Returns a
_MimiqJob. Callingjob.wait()blocks until results are available and post-processesQCSResults.fidelitiesinto typedFidelityinstances.
- execute(circuit, *, nsamples=1000, seed=None, rng=None, passes=None, callback=None, param_grid=None, strict_pass_order=True, **kwargs)[source]¶
Submit
circuitto the cloud and wait for results.seedandrngare mutually exclusive sources of randomness. Submit-time tuning options (bonddim,entdim,mpscutoff,mpsmethod,mpotraversal,timelimit,noisemodel) pass through tosubmit().Output shape mirrors input: a single
Circuitreturns a singleQCSResults;list[Circuit]returnslist[QCSResults].To request specific amplitudes, push
Amplitudeinstructions intocircuitand readresults.zstates.
- mimiqcircuits.backends.normalize_seed(seed, rngs)[source]¶
Reconcile the legacy
seed=and the newrngs=kwargs.Either may be provided, never both.
rngsmay be anint(passed through), anRNGsbundle (xor-folded to one seed), orNone(returns theseedargument).
- mimiqcircuits.backends.derive_grid_seeds(base_seed, n)[source]¶
Deterministically derive
ndistinct seeds frombase_seed.The
param_gridloop calls this so each parameter point gets a different RNG stream; reusingbase_seeddirectly would tie measurement outcomes across grid points. ANonebase_seedpropagates as[None] * n(caller wants nondeterminism).
- mimiqcircuits.backends.extract_projection(circuit)[source]¶
Reverse-scan circuit, absorbing every trailing operation that does not affect the qubit observables of the post-evolution state into a projection_circuit of classical-bit instructions. The remaining operations are returned as quantum_circuit — the part the simulator must evolve.
Absorbed operations:
Trailing
Measure(q, b)/MeasureReset(q, b)→Measure(q, b).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()).
- mimiqcircuits.backends.evaluate_projection(projection, sample)[source]¶
Run the projection circuit on a single raw quantum-state sample, returning the resulting classical bitstring.
- mimiqcircuits.backends.needs_trajectories(circuit)[source]¶
Return True if circuit still contains any non-unitary op that requires per-shot evolution. Operations that don’t touch qubits (Amplitude on a z-register, Tick, …) or that declare themselves unitary (Gates, AbstractAnnotation, ExpectationValue, …) are ignored.
Mirrors the Julia AbstractQCSs.needs_trajectories:
num_qubits(op) != 0 && !isunitary(op).
- mimiqcircuits.backends.needs_loss_sampling(circuit)[source]¶
Return True if circuit contains a LossErr or QubitLoss operation that must be sampled (Method-1 pre-evolve sampling) before the simulator runs.
- mimiqcircuits.backends.any_mixed_unitary(circuit)[source]¶
Return True if circuit contains a mixed-unitary
krauschannelwhose ismixedunitary() is true. Used as the default predicate for the per-trajectory recompile decision inLocalBackend.recompile_per_trajectory().Mirrors the Julia AbstractQCSs.any_mixed_unitary.
- mimiqcircuits.backends.remap_projection_qubits(projection, qubit_order, do_remap)[source]¶
Rewrite every Measure(q, b) instruction in projection so that
q → qubit_order[q]. Used by the driver when the pass pipeline reordered the qubits and the projection was synthesised in the reordered frame.Returns a new Circuit; the input is not mutated.
- class mimiqcircuits.backends.StochasticKind(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Bases:
IntEnumResolution-time taxonomy for operations.
Ordered so worst-case combines (
max) compose across composite ops:Deterministic < TrajectorySampleable < RuntimeOnly.Deterministic— no randomness;compile()can lower the op into the backend’s compiled form using only the source-circuit information.TrajectorySampleable— non-deterministic but resolvable inprepare_trajectory()using RNG draws alone. Classical sample space and probabilities are state-independent as far as this backend is concerned.RuntimeOnly— must be resolved duringevolve()because branch probabilities or control-flow truth values depend on the live quantum or classical state.
Backend-dependent. See
Backend.stochastic_kind().- Deterministic = 0¶
- TrajectorySampleable = 1¶
- RuntimeOnly = 2¶
- mimiqcircuits.backends.default_stochastic_kind(op)[source]¶
Backend-agnostic default classification used by
Backend.stochastic_kind(). Concrete backends override the method onBackend(not this function) when they handle a specific op type differently.Defaults:
IfStatement/ similar wrappers: recurse on the inner op.krauschannel:TrajectorySampleableifismixedunitary, elseRuntimeOnly.LossErr:RuntimeOnly(untilsample_lossesmoves intoprepare_trajectory(); F-S2 follow-up).AbstractMeasurement:RuntimeOnly.everything else:
Deterministic.
- mimiqcircuits.backends.stochastic_kind(backend, x)[source]¶
Free-function form:
stochastic_kind(backend, x). Delegates tobackend.stochastic_kind(x)so subclasses’ overrides bite.
- mimiqcircuits.backends.first_stochastic(backend, circuit)[source]¶
Index of the first non-deterministic instruction in
circuitas classified bybackend, orNoneif purely deterministic.
- mimiqcircuits.backends.last_stochastic(backend, circuit)[source]¶
Index of the last non-deterministic instruction in
circuit, orNoneif purely deterministic.
- mimiqcircuits.backends.first_runtime_only(backend, circuit)[source]¶
Index of the first
RuntimeOnlyinstruction incircuit, orNoneif none exists. Distinct fromfirst_stochastic():TrajectorySampleableops do not require barrier protection in MPS-style backends.
Modules
Abstract base classes for simulator backends. |
|
Capability vocabulary, numeric limits, topology, and admission types. |
|
Compiled-circuit types and the metadata they carry. |
|
Typed fidelity values returned by |
|
Final-block analysis. |
|
Optimization-pass framework. |
|
Concrete |
|
|
Free-function form: |