mimiqcircuits.backends.backend¶
Abstract base classes for simulator backends.
This module defines the contract every simulator must satisfy:
Backend— the common interface, advertising identity, capabilities, limits, topology, and anexecute()entry point.LocalBackend— for in-process simulators. Addsbuild_state(),compile(),evolve(), and a defaultexecute()loop built on top of them.RemoteBackend— for cloud or submit/poll execution. Addssubmit()and provides a defaultexecute()that waits on the returned job.
See Implementing a Custom Backend for a step-by-step guide.
Classes
|
Abstract base class for every simulator backend. |
Base class for simulators that run in this process. |
|
|
Per-qubit register that records which qubits are lost. |
|
Four independent random streams, one per simulation stage. |
Base class for simulators that run on a remote service. |
|
|
Simulation state that a |
- 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 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 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:
A
StochasticKind.- 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.- Parameters:
circuit – The prepared circuit.
progress – A
Progresssink.
- Returns:
The result of
compile().
- 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.