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

apply_passes(pipeline, ctx, circuit)

Run the passes of pipeline on circuit, in order.

check_prep_flags(*[, fuse, fuse_threshold, ...])

Validate the circuit-preparation flags and return them normalised, as a dict keyed by flag name.

invert_perm(perm)

Return the inverse of a 0-based permutation.

resolve_pipeline(backend, passes, *[, fuse, ...])

Circuit preparation, resolved: the backend's default_passes(), adjusted by the flags, then extended with the caller's own passes.

to_pass_param(x)

Convert a plain Python value into a PassParam.

Classes

AbstractPass()

Base class for circuit-transformation passes.

PBool(value)

Boolean pass parameter.

PDict(items)

Dictionary pass parameter with string keys.

PFloat(value)

Floating-point pass parameter.

PInt(value)

Integer pass parameter.

PList(items)

List pass parameter.

PStr(value)

String pass parameter.

PSym(value)

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

PassContext([backend, rng, bitstrings, features])

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

PassParam()

Base class for the typed values used as pass parameters.

PassPipeline([passes])

An ordered sequence of passes.

PassResult([initial_layout, final_layout, ...])

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

PassSpec(name[, parameters, requires, conflicts])

Description of a pass: its name and parameters.

Exceptions

RemotePassOrderError(backend_name)

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

UnacceptedPassError(backend_name, pass_name)

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

class PassParam[source]

Bases: object

Base class for the typed values used as pass parameters.

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

class PStr(value)[source]

Bases: PassParam

String pass parameter.

value

The string.

Type:

str

class PInt(value)[source]

Bases: PassParam

Integer pass parameter.

value

The integer.

Type:

int

class PFloat(value)[source]

Bases: PassParam

Floating-point pass parameter.

value

The number.

Type:

float

class PBool(value)[source]

Bases: PassParam

Boolean pass parameter.

value

The boolean.

Type:

bool

class PSym(value)[source]

Bases: PassParam

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

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

value

The name of the choice.

Type:

str

class PList(items)[source]

Bases: PassParam

List pass parameter.

items

The elements.

Type:

tuple[PassParam, …]

class PDict(items)[source]

Bases: PassParam

Dictionary pass parameter with string keys.

items

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

Type:

tuple[tuple[str, PassParam], …]

to_pass_param(x)[source]

Convert a plain Python value into a PassParam.

Parameters:

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

Returns:

The matching PassParam. Strings become PStr, never PSym.

Raises:

TypeError – For any other type.

Return type:

PassParam

Examples

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

Bases: object

Description of a pass: its name and parameters.

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

name

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

Type:

str

parameters

The parameters, as (name, value) pairs.

Type:

tuple[tuple[str, PassParam], …]

requires

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

Type:

tuple[str, …]

conflicts

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

Type:

tuple[str, …]

Examples

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

Build a spec from plain Python values.

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

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

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

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

Returns:

The new PassSpec.

Return type:

PassSpec

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

Bases: object

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

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

initial_layout

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

Type:

list[int] or None

final_layout

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

Type:

list[int] or None

metadata

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

Type:

dict[str, Any]

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

Bases: object

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

backend

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

Type:

Backend or None

rng

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

Type:

random.Random

bitstrings

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

Type:

list

features

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

Type:

set[str]

class AbstractPass[source]

Bases: ABC

Base class for circuit-transformation passes.

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

Examples

A pass that removes every Barrier.

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

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

abstract spec()[source]

Return a PassSpec describing the pass.

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

abstract apply(ctx, circuit)[source]

Run the pass on circuit.

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

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

Returns:

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

Return type:

tuple[Any, PassResult]

preserves(feature)[source]

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

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

Parameters:

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

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

Bases: object

An ordered sequence of passes.

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

passes

The passes, in the order they run.

Type:

list[AbstractPass]

Examples

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

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

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

>>> initial is None and final is None
True
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, mapping and reorderqubits must be None or a bool (NumPy bools become bool); reorderqubits may also be a method name. fuse_threshold and reorderqubits_seed must be None or an integer other than a bool, and become int. Anything else raises TypeError: a value like fuse=0 would 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 own passes.

Each flag speaks about one kind of pass. Set to False it 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 not AllToAll, mapping=None adds mapping_pass() if the backend declared no pass named "map_circuit"; only mapping=False leaves the circuit unmapped.

passes are appended at the end, as given. Invalid flag values raise TypeError; see check_prep_flags().

Raises:
  • TypeError – For an invalid flag value.

  • ValueError – If fuse_threshold is given with fuse=False, if mapping=True on a backend whose topology is AllToAll (give a MapCircuitPass with a target in passes instead), or if the resolved pipeline holds both a "map_circuit" and a "reorder_qubits" pass.

exception UnacceptedPassError(backend_name, pass_name)[source]

Bases: Exception

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

apply_passes() raises it instead of skipping the pass.

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

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

exception RemotePassOrderError(backend_name)[source]

Bases: Exception

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

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

Parameters:

backend_name (str) – Name of the backend.

invert_perm(perm)[source]

Return the inverse of a 0-based permutation.

Parameters:

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

Returns:

The inverse permutation, also 0-based.

Return type:

list[int]

Examples

>>> from mimiqcircuits import *
>>> from mimiqcircuits.backends import invert_perm
>>> invert_perm([1, 2, 0])
[2, 0, 1]
apply_passes(pipeline, ctx, circuit)[source]

Run the passes of pipeline on circuit, in order.

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

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

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

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

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

Returns:

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

Return type:

A tuple (circuit, initial_layout, final_layout, results)

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

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

See also

PassPipeline, whose example runs a pipeline.