mimiqcircuits.backends.passes¶
Optimization-pass framework.
A pass transforms a Circuit before evolution. A
PassPipeline holds passes in order, and apply_passes() runs
them and composes the qubit layouts they report.
Parameters travel over the wire (to remote backends) through a
JSON-safe ADT, PassParam, instead of a loose dict: the
tagged variants preserve type information that a plain dict would
silently lose.
Custom passes subclass AbstractPass and implement
spec() (a declarative PassSpec) and
apply() (the actual rewrite). See
Implementing a Custom Backend for a worked example.
Functions
|
Run the passes of |
|
Validate the circuit-preparation flags and return them normalised, as a dict keyed by flag name. |
|
Return the inverse of a 0-based permutation. |
|
Circuit preparation, resolved: the backend's |
Convert a plain Python value into a |
Classes
Base class for circuit-transformation passes. |
|
|
Boolean pass parameter. |
|
Dictionary pass parameter with string keys. |
|
Floating-point pass parameter. |
|
Integer pass parameter. |
|
List pass parameter. |
|
String pass parameter. |
|
Pass parameter that names one of a fixed set of choices, like an |
|
Inputs a pass may need, given to |
Base class for the typed values used as pass parameters. |
|
|
An ordered sequence of passes. |
|
What a pass reports besides the new circuit, returned by |
|
Description of a pass: its name and parameters. |
Exceptions
|
Error for a non-empty |
|
Error for a pass the backend refuses in |
- 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
- check_prep_flags(*, fuse=None, fuse_threshold=None, canonicaldecompose=None, reorderqubits=None, remove_swaps=None, simplify=None, reorderqubits_seed=None, mapping=None)[source]¶
Validate the circuit-preparation flags and return them normalised, as a dict keyed by flag name.
fuse,canonicaldecompose,remove_swaps,simplify,mappingandreorderqubitsmust beNoneor a bool (NumPy bools becomebool);reorderqubitsmay also be a method name.fuse_thresholdandreorderqubits_seedmust beNoneor an integer other than a bool, and becomeint. Anything else raisesTypeError: a value likefuse=0would otherwise read as “set” and install the pass.
- resolve_pipeline(backend, passes, *, fuse=None, fuse_threshold=None, canonicaldecompose=None, reorderqubits=None, remove_swaps=None, simplify=None, reorderqubits_seed=None, mapping=None)[source]¶
Circuit preparation, resolved: the backend’s
default_passes(), adjusted by the flags, then extended with the caller’s ownpasses.Each flag speaks about one kind of pass. Set to
Falseit drops that pass from the backend’s declaration; set to anything else it replaces it with the pass the backend builds for that flag (fuse_pass(),reorder_pass(),canonical_decompose_pass(),remove_swaps_pass(),simplify_pass(),mapping_pass()), or adds that one if the backend declared none. Everything the flags say nothing about is left exactly as the backend wants it.When the backend’s
topology()is notAllToAll,mapping=Noneaddsmapping_pass()if the backend declared no pass named"map_circuit"; onlymapping=Falseleaves the circuit unmapped.passesare appended at the end, as given. Invalid flag values raiseTypeError; seecheck_prep_flags().- Raises:
TypeError – For an invalid flag value.
ValueError – If
fuse_thresholdis given withfuse=False, ifmapping=Trueon a backend whose topology isAllToAll(give aMapCircuitPasswith a target inpassesinstead), or if the resolved pipeline holds both a"map_circuit"and a"reorder_qubits"pass.
- 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.
- 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]
- 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.