mimiqcircuits.decomposition

Rewrite circuits into a target gate set.

The framework has two building blocks. A RewriteRule says how to rewrite one operation into simpler ones, one step at a time, and nothing about when to stop. A DecompositionBasis says what is terminal, the operations to keep, and how to rewrite everything else; decompose() applies it recursively until only terminal operations are left.

Functions

A function that takes a basis also accepts a rewrite rule, wrapped in a RuleBasis.

Bases

  • CanonicalBasis: GateU and GateCX, plus the non-unitary primitives. The default.

  • CliffordTBasis: Clifford+T, approximating arbitrary rotations.

  • StimBasis: the Clifford gates, measurements and noise of Stim.

  • QASMBasis: the OpenQASM 2.0 gate library (qelib1.inc).

  • FlattenedBasis: expands GateCall, Block and BlockCall containers and keeps everything else.

  • RuleBasis: applies one rewrite rule until it no longer matches.

Rules

An operation that a basis cannot rewrite raises DecompositionError.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]

>>> c.push(GateCCX(), 0, 1, 2)
3-qubit circuit with 2 instructions:
├── H @ q[0]
└── C₂X @ q[0:1], q[2]
>>> # the default basis leaves only GateU and GateCX
>>> sorted({type(inst.operation).__name__ for inst in decompose(c)})
['GateCX', 'GateU']
>>> # the Clifford+T basis rewrites the Toffoli with H, T, T† and CX
>>> sorted({type(inst.operation).__name__ for inst in decompose(c, CliffordTBasis())})
['GateCX', 'GateH', 'GateT', 'GateTDG']
>>> # a rule applied once rewrites the Toffoli into 15 gates and keeps H
>>> stepped = decompose_step(c, ToffoliToCliffordTRewrite())
>>> len(stepped), stepped[0].operation
(16, H)

To add a gate set of your own, subclass RewriteRule or DecompositionBasis; their documentation shows how.

class RewriteRule[source]

Bases: ABC

Abstract base class for single-step rewrite rules.

A rewrite rule says how to rewrite an operation into a circuit of other operations, but not when to stop. Apply it once with decompose_step(), or repeatedly with decompose(), which wraps it in a RuleBasis and rewrites until nothing matches. For a target gate set, see DecompositionBasis.

A subclass implements matches() and decompose_step().

Examples

>>> from mimiqcircuits import *
>>> # a rule that rewrites a SWAP into three CX gates
>>> class SwapToCX(RewriteRule):
...     def matches(self, op):
...         return isinstance(op, GateSWAP)
...
...     def decompose_step(self, op, qubits, bits, zvars):
...         # qubits are the targets of the SWAP in the circuit
...         a, b = qubits
...         circ = Circuit()
...         circ.push(GateCX(), a, b)
...         circ.push(GateCX(), b, a)
...         circ.push(GateCX(), a, b)
...         return circ
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]

>>> c.push(GateSWAP(), 0, 1)
2-qubit circuit with 2 instructions:
├── H @ q[0]
└── SWAP @ q[0:1]

>>> # the SWAP matches and is rewritten; the H does not and is kept
>>> decompose_step(c, SwapToCX())
2-qubit circuit with 4 instructions:
├── H @ q[0]
├── CX @ q[0], q[1]
├── CX @ q[1], q[0]
└── CX @ q[0], q[1]
abstract matches(op)[source]

Check whether this rule can rewrite an operation.

Parameters:

op (Operation) – The operation to check.

Returns:

True if decompose_step() accepts op.

Return type:

bool

abstract decompose_step(op, qubits, bits, zvars)[source]

Rewrite an operation one step.

Call it only on an operation that matches() accepts. The result acts on the given indices, so it can be appended in place of the original instruction. Its operations may themselves match the rule again.

Parameters:
  • op (Operation) – The operation to rewrite.

  • qubits (Sequence[int]) – Qubit indices the operation acts on.

  • bits (Sequence[int]) – Classical bit indices the operation acts on.

  • zvars (Sequence[int]) – Z-variable indices the operation acts on.

Returns:

A new Circuit that implements op on those indices.

Raises:

DecompositionError – If the rule cannot rewrite op.

Return type:

Circuit

decompose_step_ctx(op, qubits, bits, zvars, ctx)[source]

Apply this rule with a DecompositionContext.

Rules that use the context, for example to borrow qubits, override this method. The default drops the context and calls decompose_step().

class DecompositionBasis[source]

Bases: ABC

Abstract base class for decomposition targets.

A basis decides which operations are terminal, that is kept as they are, and how to rewrite every other operation. decompose() rewrites each non-terminal operation with decompose() and repeats on the result until only terminal operations are left.

A subclass implements isterminal() and decompose().

Examples

>>> from mimiqcircuits import *
>>> # a basis of GateU and GateCZ: CX becomes H, CZ, H and the rest
>>> # follows the built-in decomposition
>>> class CZBasis(DecompositionBasis):
...     def isterminal(self, op):
...         return isinstance(op, (GateU, GateCZ))
...
...     def decompose(self, op, qubits, bits, zvars):
...         if isinstance(op, GateCX):
...             control, target = qubits
...             circ = Circuit()
...             circ.push(GateH(), target)
...             circ.push(GateCZ(), control, target)
...             circ.push(GateH(), target)
...             return circ
...         return CanonicalRewrite().decompose_step(op, qubits, bits, zvars)
>>> c = Circuit()
>>> c.push(GateCX(), 0, 1)
2-qubit circuit with 1 instruction:
└── CX @ q[0], q[1]

>>> # the H gates are not terminal, so they are decomposed in turn
>>> decompose(c, CZBasis())
2-qubit circuit with 3 instructions:
├── U((1/2)*pi, 0, pi, 0.0) @ q[1]
├── CZ @ q[0], q[1]
└── U((1/2)*pi, 0, pi, 0.0) @ q[1]
abstract isterminal(op)[source]

Check whether an operation is terminal in this basis.

Terminal operations are the target set: decompose() keeps them as they are.

Parameters:

op (Operation) – The operation to check.

Returns:

True if op is kept, False if it is rewritten.

Return type:

bool

abstract decompose(op, qubits, bits, zvars)[source]

Rewrite a non-terminal operation one step.

Called by decompose() only for operations that isterminal() rejects. The result does not need to be terminal: decompose() keeps rewriting it.

Parameters:
  • op (Operation) – The operation to rewrite.

  • qubits (Sequence[int]) – Qubit indices the operation acts on.

  • bits (Sequence[int]) – Classical bit indices the operation acts on.

  • zvars (Sequence[int]) – Z-variable indices the operation acts on.

Returns:

A new Circuit that implements op on those indices.

Raises:

DecompositionError – If the basis has no rewrite for op.

Return type:

Circuit

decompose_ctx(op, qubits, bits, zvars, ctx)[source]

Decompose a non-terminal operation with a DecompositionContext.

decompose() always calls this method. Bases that pass the context on to their rules override it. The default drops the context and calls decompose().

class DecompositionContext(nqubits=0, borrow=False, unitary_only=False, allocator=None, bit=None)[source]

Bases: object

State that decompose() hands to a basis and its rules.

The context goes next to the operation and its targets, through DecompositionBasis.decompose_ctx() and RewriteRule.decompose_step_ctx().

Parameters:
  • nqubits (int) – Width of the circuit being decomposed. Qubits 0, ..., nqubits - 1 that are not targets of the operation may be borrowed. 0 means the width is unknown, and nothing is borrowed.

  • borrow (bool) – Whether rules may borrow qubits outside the operation’s targets. A borrowed qubit can be in any state; the decomposition acts as the identity on it.

  • unitary_only (bool) – Set when the result must be unitary, as for the body of a wrapped GateDecl or of an IfStatement.

decompose() also hands out clean ancillas through the context when the basis has max_ancillas > 0. A rule that takes them brackets their use with AncillaAlloc and AncillaFree and returns them in |0>. With allow_measurement=True on the basis, the context also holds a classical bit, numbered after those of the circuit, that rules may measure an ancilla into.

Bases and rules that do not use the context inherit the default *_ctx methods, which drop it and call the method without it.

classmethod from_basis(basis, nqubits, nbits=0)[source]

The context for a circuit nqubits wide with nbits bits.

Clean ancillas and the measured bit are numbered after them, so a circuit of unknown width gets none.

unitary()[source]

The same context for a result that must be unitary.

can_measure()[source]

Whether a rule may measure an ancilla.

available()[source]

Number of clean ancillas that can be taken now.

take_clean(k)[source]

Up to k clean ancillas for the rule that receives this context.

exception DecompositionError[source]

Bases: Exception

Raised when an operation cannot be decomposed.

A basis raises it from DecompositionBasis.decompose() for an operation it is not terminal for and has no rewrite for, and most rules raise it from RewriteRule.decompose_step() for an operation they do not match.

class CanonicalBasis(borrow=False, max_ancillas=0, allow_measurement=False)[source]

Bases: DecompositionBasis

Decomposition basis targeting GateU and GateCX.

Every gate is rewritten into GateU (an arbitrary single-qubit gate) and GateCX, with the built-in decomposition of each operation (CanonicalRewrite). The non-unitary primitives are kept as they are; isterminal() lists them. This is the default basis of decompose().

Parameters:
  • borrow (bool) – Let decompositions borrow qubits of the circuit that the operation does not act on. A borrowed qubit can be in any state; the decomposition leaves it as it found it.

  • max_ancillas (int) – Let decompositions add up to this many clean ancillas, numbered after the qubits of the circuit and marked with AncillaAlloc and AncillaFree. Ancillas freed by one operation are reused by the next.

  • allow_measurement (bool) – With max_ancillas, let decompositions undo steps by measuring an ancilla into one extra bit, numbered after the bits of the circuit. A circuit without bits is refused with a ValueError.

The three ancilla options are off by default, and only change how multi-controlled X gates are decomposed. Circuits whose width is unknown, such as a lone operation, get no ancillas.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]

>>> c.push(GateSWAP(), 0, 1)
2-qubit circuit with 2 instructions:
├── H @ q[0]
└── SWAP @ q[0:1]

>>> c.push(Measure(), 0, 0)
2-qubit, 1-bit circuit with 3 instructions:
├── H @ q[0]
├── SWAP @ q[0:1]
└── M @ q[0], c[0]

>>> # gates become GateU and GateCX; the measurement is kept
>>> decompose(c, CanonicalBasis())
2-qubit, 1-bit circuit with 5 instructions:
├── U((1/2)*pi, 0, pi, 0.0) @ q[0]
├── CX @ q[0], q[1]
├── CX @ q[1], q[0]
├── CX @ q[0], q[1]
└── M @ q[0], c[0]
isterminal(op)[source]

Check whether an operation is terminal in the canonical basis.

The terminal operations are GateU and GateCX; Measure; Reset, ResetX and ResetY; Loss, Reload, Check and MeasureCheck; Barrier and Delay; classical operations and annotations; noise channels and ReadoutErr; ExpectationValue, Amplitude, SchmidtRank, VonNeumannEntropy and BondDim; and the z-register operations Add, Multiply and Pow. An IfStatement or WhileStatement is terminal when its body is.

Parameters:

op (Operation) – The operation to check.

Returns:

True if op is terminal.

Return type:

bool

decompose(op, qubits, bits, zvars)[source]

Rewrite a non-terminal operation with its built-in decomposition.

Parameters:
  • op (Operation) – The operation to rewrite.

  • qubits (Sequence[int]) – Qubit indices the operation acts on.

  • bits (Sequence[int]) – Classical bit indices the operation acts on.

  • zvars (Sequence[int]) – Z-variable indices the operation acts on.

Returns:

A new Circuit with one decomposition step.

Raises:

DecompositionError – If op has no built-in decomposition.

Return type:

Circuit

decompose_ctx(op, qubits, bits, zvars, ctx)[source]

Decompose with a context, which only some operations use.

Operations without a rule that uses the context go to decompose(), so an override of it keeps being called.

class CliffordTBasis(sk_depth=None, rotations=None, borrow=False, max_ancillas=0, allow_measurement=False)[source]

Bases: DecompositionBasis

Decomposition basis targeting the Clifford+T gate set.

Clifford+T is the standard universal gate set of error-corrected quantum computing. The terminal operations of this basis are those of StimBasis plus GateT and GateTDG, so the two bases always keep the same Clifford and stabilizer operations:

  • single-qubit Cliffords: GateID, GateX, GateY, GateZ, GateH, GateHXY, GateHYZ, GateS, GateSDG, GateSX, GateSXDG, GateSY, GateSYDG;

  • two-qubit Cliffords: GateCX, GateCY, GateCZ, GateSWAP, GateISWAP, GateISWAPDG, GateDCX, GateECR;

  • Pauli rotations by +-pi/2: GateRXX, GateRYY, GateRZZ, and RPauli with a non-identity Pauli string;

  • the non-Clifford GateT and GateTDG;

  • measurements, resets and measure-and-resets in the X, Y and Z bases, MeasureXX, MeasureYY, MeasureZZ and MeasurePauli;

  • Pauli noise: PauliX, PauliY, PauliZ, Depolarizing1, Depolarizing2 and PauliNoise;

  • barriers and annotations;

  • classical operations, which StimBasis does not keep;

  • an IfStatement whose body is terminal in this basis, with any condition. StimBasis only keeps a conditional GateX, GateY or GateZ on a single bit.

Non-terminal operations are rewritten by the first rule that matches, in this order:

  1. SpecialAngleRewrite: rotations by multiples of pi/4 to exact Clifford+T.

  2. GateECR to S, SX, CX and X, as in StimBasis, with no T gate.

  3. ToffoliToCliffordTRewrite: GateCCX to Clifford+T with 7 T gates.

  4. A GateU whose angles are all zero (a pure global phase) is dropped.

  5. ZYZRewrite: GateU to RZ*RY*RZ, and GateRX to GateRY between S and S†.

  6. ToZRotationRewrite: GateRY to GateRZ and Cliffords.

  7. The rotations rule (default GridSynthRewrite): remaining GateRZ to an approximate Clifford+T sequence.

  8. CanonicalRewrite: any other operation, toward GateU and GateCX. A GateRX, GateRY or GateRZ that reaches this point has a symbolic angle and raises DecompositionError.

The rotations rule only sees angles that step 1 could not decompose exactly. The body of an IfStatement goes through the same pipeline and stays conditional. No T-count optimization is performed on the result.

Parameters:
  • sk_depth (int | None) – Use SolovayKitaevRewrite with this recursion depth as the rotations rule.

  • rotations (RewriteRule) – Rule that synthesizes the remaining Z-rotations. The default GridSynthRewrite() approximates each rotation to operator-norm error 1e-10. The rule must match GateRZ with a numeric angle and emit only gates of this basis.

  • borrow (bool) – Let decompositions borrow qubits of the circuit that the operation does not act on. A borrowed qubit can be in any state; the decomposition leaves it as it found it.

  • max_ancillas (int) – Let decompositions add up to this many clean ancillas, numbered after the qubits of the circuit and marked with AncillaAlloc and AncillaFree. Ancillas freed by one operation are reused by the next.

  • allow_measurement (bool) – With max_ancillas, let decompositions undo steps by measuring an ancilla into one extra bit, numbered after the bits of the circuit. A circuit without bits is refused with a ValueError. With a clean ancilla, a GateCCX then costs 4 T instead of 7.

The three ancilla options are off by default, and only change how multi-controlled X gates are decomposed. Circuits whose width is unknown, such as a lone operation, get no ancillas.

Raises:

ValueError – If both sk_depth and rotations are given, or if rotations does not match GateRZ.

Decomposing an operation that no rule handles, such as a noise channel other than the Pauli ones above, raises a DecompositionError.

Examples

>>> from mimiqcircuits import *
>>> from symengine import pi
>>> c = Circuit()
>>> c.push(GateRZ(pi/4), 0)
1-qubit circuit with 1 instruction:
└── RZ((1/4)*pi) @ q[0]

>>> # a special angle is decomposed exactly
>>> decompose(c, CliffordTBasis())
1-qubit circuit with 1 instruction:
└── T @ q[0]
>>> # An arbitrary angle is approximated to 1e-10 by gridsynth
>>> c2 = Circuit()
>>> c2.push(GateRZ(0.123), 0)
1-qubit circuit with 1 instruction:
└── RZ(0.123) @ q[0]

>>> decomposed2 = decompose(c2, CliffordTBasis())
>>> # A looser error bound per rotation gives fewer T gates
>>> basis = CliffordTBasis(rotations=GridSynthRewrite(epsilon=1e-6))
>>> decomposed3 = decompose(c2, basis)
>>> def tcount(c):
...     return sum(isinstance(inst.operation, (GateT, GateTDG)) for inst in c)
>>> tcount(decomposed3) < tcount(decomposed2)
True
>>> # Solovay-Kitaev instead of gridsynth
>>> decomposed4 = decompose(c2, CliffordTBasis(sk_depth=0))
isterminal(op)[source]

Check if an operation is terminal in the Clifford+T basis.

Parameters:

op (Operation) – The operation to check.

Returns:

True if the operation is terminal in StimBasis, is GateT, GateTDG or a classical operation, or is an IfStatement whose body is terminal in this basis.

Return type:

bool

decompose(op, qubits, bits, zvars)[source]

Rewrite a non-terminal operation one step toward Clifford+T.

Applies the first matching rule of the list in the class description.

Parameters:
  • op (Operation) – The operation to decompose.

  • qubits (Sequence[int]) – Qubit indices for the operation.

  • bits (Sequence[int]) – Classical bit indices for the operation.

  • zvars (Sequence[int]) – Z-variable indices for the operation.

Returns:

A new Circuit with the rewrite.

Raises:

DecompositionError – If no rule applies to op.

Return type:

Circuit

decompose_ctx(op, qubits, bits, zvars, ctx)[source]

Decompose with a context, which only some operations use.

Operations without a rule that uses the context go to decompose(), so an override of it keeps being called.

class FlattenedBasis[source]

Bases: DecompositionBasis

Decomposition basis that expands containers and keeps every other operation.

GateCall, Block and BlockCall, and the Inverse of a GateCall, are expanded with FlattenContainers until none is left, at any depth. An IfStatement whose body is a container becomes one conditional instruction per instruction of the body. Gates are not decomposed, and that includes a GateCall wrapped in Control, Power, Parallel or Repeat, which is kept.

Examples

>>> from mimiqcircuits import *
>>> # a declared gate that holds a Bell-pair preparation
>>> bell = GateDecl("bell", (), Circuit().push(GateH(), 0).push(GateCX(), 0, 1))
>>> c = Circuit()
>>> c.push(bell(), 0, 1)
2-qubit circuit with 1 instruction:
└── bell() @ q[0:1]

>>> c.push(GateSWAP(), 0, 1)
2-qubit circuit with 2 instructions:
├── bell() @ q[0:1]
└── SWAP @ q[0:1]

>>> # the call is expanded; SWAP is a gate and is kept
>>> decompose(c, FlattenedBasis())
2-qubit circuit with 3 instructions:
├── H @ q[0]
├── CX @ q[0], q[1]
└── SWAP @ q[0:1]
isterminal(op)[source]

Check whether an operation is kept, that is not a container.

Parameters:

op (Operation) – The operation to check.

Returns:

False for the containers listed in the class description and for an IfStatement whose body is one, True otherwise.

Return type:

bool

decompose(op, qubits, bits, zvars)[source]

Expand one level of a container.

Parameters:
  • op (Operation) – The container, or the IfStatement of one, to expand.

  • qubits (Sequence[int]) – Qubit indices the operation acts on.

  • bits (Sequence[int]) – Classical bit indices the operation acts on.

  • zvars (Sequence[int]) – Z-variable indices the operation acts on.

Returns:

A new Circuit with the contents of op, each made conditional if op is an IfStatement.

Raises:

DecompositionError – If op is not a container.

Return type:

Circuit

class QASMBasis(borrow=False, max_ancillas=0, allow_measurement=False)[source]

Bases: DecompositionBasis

Decomposition basis targeting the OpenQASM 2.0 gate library.

The terminal gates are the OpenQASM 2.0 built-ins and the gates of the qelib1.inc include file that have a direct MIMIQ counterpart, so a decomposed circuit can be written as OpenQASM 2.0 and read back by any parser that ships the standard qelib1.inc.

The terminal operations are:

  • the OpenQASM 2.0 built-ins GateU and GateCX;

  • the single-qubit gates of qelib1.inc: GateU3, GateU2, GateU1, GateID, GateX, GateY, GateZ, GateH, GateS, GateSDG, GateT, GateTDG, GateRX, GateRY and GateRZ;

  • the two-qubit gates of qelib1.inc: GateCY, GateCZ, GateCH, GateCRX, GateCRY, GateCRZ, GateSWAP, GateRXX and GateRZZ;

  • the three- and four-qubit gates of qelib1.inc: GateCCX, GateCSWAP and GateC3X;

  • Measure, Reset and Barrier, but not the X and Y variants of Measure and Reset;

  • annotations, such as AncillaAlloc, which the OpenQASM writer drops;

  • an IfStatement whose body is terminal;

  • a GateCall whose declaration holds only terminal operations.

Every other operation is decomposed through CanonicalRewrite. Operations that OpenQASM 2.0 cannot express and that have no decomposition into the gates above (noise channels, classical operations, Z-register operations, …) raise DecompositionError.

MeasureReset decomposes into Measure followed by Reset. This leaves the same state and bit as its canonical decomposition, a measurement and an X conditioned on its outcome, and unlike that conditional it can be written for a circuit of any number of bits. OpenQASM 2.0 has no loops, so WhileStatement raises DecompositionError.

Parameters:
  • borrow (bool) – Let decompositions borrow qubits of the circuit that the operation does not act on. A borrowed qubit can be in any state; the decomposition leaves it as it found it.

  • max_ancillas (int) – Let decompositions add up to this many clean ancillas, numbered after the qubits of the circuit and marked with AncillaAlloc and AncillaFree. Ancillas freed by one operation are reused by the next.

  • allow_measurement (bool) – With max_ancillas, let decompositions undo steps by measuring an ancilla into one extra bit, numbered after the bits of the circuit. A circuit without bits is refused with a ValueError.

The three ancilla options are off by default, and only change how multi-controlled X gates are decomposed. Circuits whose width is unknown, such as a lone operation, get no ancillas.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(GateCCX(), 0, 1, 2)
3-qubit circuit with 1 instruction:
└── C₂X @ q[0:1], q[2]

>>> c.push(GateSX(), 0)
3-qubit circuit with 2 instructions:
├── C₂X @ q[0:1], q[2]
└── SX @ q[0]

>>> c.push(MeasureReset(), 0, 0)
3-qubit, 1-bit circuit with 3 instructions:
├── C₂X @ q[0:1], q[2]
├── SX @ q[0]
└── MR @ q[0], c[0]

>>> # CCX is in qelib1.inc and is kept; SX is not and is rewritten;
>>> # MeasureReset becomes a measurement and a reset
>>> decompose(c, QASMBasis())
3-qubit, 1-bit circuit with 7 instructions:
├── C₂X @ q[0:1], q[2]
├── S† @ q[0]
├── H @ q[0]
├── S† @ q[0]
├── U(0, 0, 0, (1/4)*pi) @ q[0]
├── M @ q[0], c[0]
└── Reset @ q[0]
isterminal(op)[source]

Check whether an operation is terminal in the OpenQASM 2.0 basis.

Parameters:

op (Operation) – The operation to check.

Returns:

True if op is one of the terminal operations listed in the class description.

Return type:

bool

decompose(op, qubits, bits, zvars)[source]

Rewrite a non-terminal operation one step toward OpenQASM 2.0.

MeasureReset becomes Measure and Reset; every other operation goes through CanonicalRewrite.

Parameters:
  • op (Operation) – The operation to rewrite.

  • qubits (Sequence[int]) – Qubit indices the operation acts on.

  • bits (Sequence[int]) – Classical bit indices the operation acts on.

  • zvars (Sequence[int]) – Z-variable indices the operation acts on.

Returns:

A new Circuit with the rewrite.

Raises:

DecompositionError – If op is a WhileStatement or has no built-in decomposition.

Return type:

Circuit

decompose_ctx(op, qubits, bits, zvars, ctx)[source]

Decompose with a context, which only some operations use.

Operations without a rule that uses the context go to decompose(), so an override of it keeps being called.

class RuleBasis(rule)[source]

Bases: DecompositionBasis

Decomposition basis that applies one rewrite rule until it no longer matches.

An operation is terminal when the rule does not match it. When the rule does not match an IfStatement, it is applied to the body, which stays conditional. decompose() and eachdecomposed() wrap a rule passed in place of a basis in a RuleBasis.

Parameters:

rule (RewriteRule) – The rewrite rule to apply.

Examples

>>> from mimiqcircuits import *
>>> from symengine import pi
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]

>>> c.push(GateRX(pi/2), 0)
1-qubit circuit with 2 instructions:
├── H @ q[0]
└── RX((1/2)*pi) @ q[0]

>>> # rewrite every X and Y rotation into Z rotations; H is kept
>>> decompose(c, RuleBasis(ToZRotationRewrite()))
1-qubit circuit with 4 instructions:
├── H @ q[0]
├── H @ q[0]
├── RZ((1/2)*pi) @ q[0]
└── H @ q[0]
isterminal(op)[source]

Check whether the rule leaves an operation alone.

Parameters:

op (Operation) – The operation to check.

Returns:

True if the rule does not match op. For an IfStatement the rule does not match, the answer for its body.

Return type:

bool

decompose(op, qubits, bits, zvars)[source]

Apply the rule once to an operation.

Parameters:
  • op (Operation) – The operation to rewrite.

  • qubits (Sequence[int]) – Qubit indices the operation acts on.

  • bits (Sequence[int]) – Classical bit indices the operation acts on.

  • zvars (Sequence[int]) – Z-variable indices the operation acts on.

Returns:

A new Circuit with the rewrite. For an IfStatement the rule does not match, the rewrite of its body, with each instruction made conditional.

Raises:

DecompositionError – If the rule cannot rewrite op.

Return type:

Circuit

decompose_ctx(op, qubits, bits, zvars, ctx)[source]

Apply the rule once, with a context, as decompose() does.

class StimBasis[source]

Bases: DecompositionBasis

Decomposition basis targeting the gate set of the Stim stabilizer simulator.

Stim simulates stabilizer circuits: Clifford gates, Pauli measurements and resets, Pauli noise and quantum error correction annotations. Gates are rewritten toward that set by the first rule that matches, in this order:

  1. A GateU whose angles are all zero (a pure global phase) is dropped.

  2. ZYZRewrite: GateU to RZ*RY*RZ, and GateRX to GateRY between S and S†.

  3. SpecialAngleRewrite with only_cliffords=True: rotations by multiples of pi/2 to Clifford gates.

  4. GateECR to S, SX, CX and X, equal up to a global phase. Stim has no ECR instruction, and the canonical decomposition goes through non-Clifford RZX(+-pi/4).

  5. CanonicalRewrite: any other operation.

A GateRX, GateRY or GateRZ by any other angle is not a Clifford gate and raises DecompositionError; so does any non-Clifford gate that reduces to one, such as GateT. Use CliffordTBasis for such circuits.

The terminal operations are:

  • single-qubit Cliffords: GateID, GateX, GateY, GateZ, GateH, GateHXY, GateHYZ, GateS, GateSDG, GateSX, GateSXDG, GateSY and GateSYDG;

  • two-qubit Cliffords: GateCX, GateCY, GateCZ, GateSWAP, GateISWAP, GateISWAPDG and GateDCX;

  • Pauli rotations by +-pi/2: GateRXX, GateRYY, GateRZZ, and RPauli with a non-identity Pauli string. Angles are compared modulo 2*pi, since a rotation by 3*pi/2 equals one by -pi/2 up to a global phase. Other angles are decomposed;

  • measurements in any Pauli basis: Measure, MeasureX, MeasureY, MeasureXX, MeasureYY, MeasureZZ and MeasurePauli;

  • resets and measure-and-resets in the Z, X and Y bases: Reset, ResetX, ResetY, MeasureReset, MeasureResetX and MeasureResetY;

  • Pauli noise: PauliX, PauliY, PauliZ, Depolarizing1, Depolarizing2 and PauliNoise;

  • Barrier and annotations, including Detector, ObservableInclude and QubitCoordinates;

  • feedback: an IfStatement of GateX, GateY or GateZ conditioned on a single bit being 1.

The same Pauli conditioned on a bit being 0 becomes the Pauli followed by the Pauli conditioned on 1. Any other conditional operation has its body decomposed while staying conditional, and raises DecompositionError if that does not lead to conditional Paulis.

The terminal operations correspond to Stim instructions as follows.

MIMIQ Operation

Stim Operation

GateID

I

GateX

X

GateY

Y

GateZ

Z

GateH

H

GateHXY

H_XY

GateHYZ

H_YZ

GateS

S

GateSDG

S_DAG

GateSX

SQRT_X

GateSXDG

SQRT_X_DAG

GateSY

SQRT_Y

GateSYDG

SQRT_Y_DAG

GateCX

CNOT / CX

GateCY

CY

GateCZ

CZ

GateSWAP

SWAP

GateISWAP

ISWAP

GateISWAPDG

ISWAP_DAG

GateDCX

SWAPCX

GateRXX(+-pi/2)

SQRT_XX / SQRT_XX_DAG

GateRYY(+-pi/2)

SQRT_YY / SQRT_YY_DAG

GateRZZ(+-pi/2)

SQRT_ZZ / SQRT_ZZ_DAG

RPauli(P, +-pi/2)

SPP / SPP_DAG

IfStatement(GateX(), 1)

CX rec[-k] q

IfStatement(GateY(), 1)

CY rec[-k] q

IfStatement(GateZ(), 1)

CZ rec[-k] q

Measure

M

MeasureX

MX

MeasureY

MY

MeasureXX

MXX

MeasureYY

MYY

MeasureZZ

MZZ

MeasurePauli

MPP

Reset

R

ResetX

RX

ResetY

RY

MeasureReset

MR

MeasureResetX

MRX

MeasureResetY

MRY

PauliX

X_ERROR

PauliY

Y_ERROR

PauliZ

Z_ERROR

Depolarizing1

DEPOLARIZE1

Depolarizing2

DEPOLARIZE2

PauliNoise

PAULI_CHANNEL_1, PAULI_CHANNEL_2 or E / ELSE_CORRELATED_ERROR

Detector

DETECTOR

ObservableInclude

OBSERVABLE_INCLUDE

QubitCoordinates

QUBIT_COORDS

GateECR is terminal as a Clifford gate but has no Stim instruction of its own.

Examples

>>> from mimiqcircuits import *
>>> from symengine import pi
>>> c = Circuit()
>>> c.push(GateRY(pi/2), 0)
1-qubit circuit with 1 instruction:
└── RY((1/2)*pi) @ q[0]

>>> c.push(GateCX(), 0, 1)
2-qubit circuit with 2 instructions:
├── RY((1/2)*pi) @ q[0]
└── CX @ q[0], q[1]

>>> # RY(pi/2) is the Clifford SY; CX is already a Stim gate
>>> decompose(c, StimBasis())
2-qubit circuit with 2 instructions:
├── SY @ q[0]
└── CX @ q[0], q[1]
>>> # a T gate is not a Clifford gate and is refused
>>> c = Circuit()
>>> c.push(GateT(), 0)
1-qubit circuit with 1 instruction:
└── T @ q[0]

>>> decompose(c, StimBasis())
Traceback (most recent call last):
    ...
mimiqcircuits.decomposition.abstract.DecompositionError: Rotation RZ cannot be decomposed into the Stim basis. Only rotations with angles that are multiples of pi/2 are Clifford gates.
isterminal(op)[source]

Check whether an operation is terminal in the Stim basis.

Parameters:

op (Operation) – The operation to check.

Returns:

True if op is one of the terminal operations listed in the class description.

Return type:

bool

decompose(op, qubits, bits, zvars)[source]

Rewrite a non-terminal operation one step toward the Stim gate set.

Applies the first matching rule of the list in the class description. A conditional operation is handled as described there.

Parameters:
  • op (Operation) – The operation to rewrite.

  • qubits (Sequence[int]) – Qubit indices the operation acts on.

  • bits (Sequence[int]) – Classical bit indices the operation acts on.

  • zvars (Sequence[int]) – Z-variable indices the operation acts on.

Returns:

A new Circuit with the rewrite.

Raises:

DecompositionError – If op is a rotation by an angle that is not a multiple of pi/2, a conditional operation Stim cannot express, or has no built-in decomposition.

Return type:

Circuit

class CanonicalRewrite[source]

Bases: RewriteRule

Rewrite rule that applies the built-in decomposition of each operation.

Every operation class defines one decomposition step in terms of simpler operations; this rule applies it. Repeated, the steps end at GateU, GateCX and the non-unitary primitives, which is what CanonicalBasis does. One step can stop earlier: GateCCX, for example, becomes GateH, GateT, GateTDG and GateCX.

It is the default rule of decompose_step() and the fallback of the other bases.

Examples

>>> from mimiqcircuits import *
>>> rule = CanonicalRewrite()
>>> # H has a built-in decomposition into GateU
>>> rule.matches(GateH())
True
>>> rule.decompose_step(GateH(), [0], [], [])
1-qubit circuit with 1 instruction:
└── U((1/2)*pi, 0, pi, 0.0) @ q[0]

>>> # GateU is a primitive, so there is nothing to rewrite
>>> rule.matches(GateU(0.1, 0.2, 0.3))
False
matches(op)[source]

Check whether an operation has a built-in decomposition.

Matches every operation whose supports_canonical_rewrite() is true. The answer does not depend on any basis: an operation that CanonicalBasis keeps terminal (such as ResetX) still matches, so other bases can expand it. Primitives without a decomposition (GateU, GateCX, Measure, Reset, Barrier, …) do not match.

Parameters:

op (Operation) – The operation to check.

Returns:

True if op has a built-in decomposition.

Return type:

bool

decompose_step(op, qubits, bits, zvars)[source]

Apply one step of the built-in decomposition of an operation.

No check is made that matches() accepts op. A primitive returns a circuit holding just itself.

Parameters:
  • op (Operation) – The operation to decompose.

  • qubits (Sequence[int]) – Qubit indices the operation acts on.

  • bits (Sequence[int]) – Classical bit indices the operation acts on.

  • zvars (Sequence[int]) – Z-variable indices the operation acts on.

Returns:

A new Circuit with the decomposition.

Return type:

Circuit

decompose_step_ctx(op, qubits, bits, zvars, ctx)[source]

Apply this rule with a DecompositionContext.

Rules that use the context, for example to borrow qubits, override this method. The default drops the context and calls decompose_step().

class FlattenContainers[source]

Bases: RewriteRule

Rewrite rule that expands container operations into their contents.

Matches GateCall, Block, BlockCall, and the Inverse of a GateCall, and replaces each by the instructions it holds (inverted for an Inverse), remapped onto the targets. One step expands one level: nested containers stay as they are. Gates are never decomposed. FlattenedBasis repeats this rule until no container is left.

Examples

>>> from mimiqcircuits import *
>>> # declare a gate that prepares a Bell pair, and call it
>>> bell = GateDecl("bell", (), Circuit().push(GateH(), 0).push(GateCX(), 0, 1))
>>> c = Circuit()
>>> c.push(bell(), 2, 3)
4-qubit circuit with 1 instruction:
└── bell() @ q[2:3]

>>> # the call is replaced by its body, on qubits 2 and 3
>>> decompose_step(c, FlattenContainers())
4-qubit circuit with 2 instructions:
├── H @ q[2]
└── CX @ q[2], q[3]
matches(op)[source]

Check whether an operation is a container this rule expands.

Parameters:

op (Operation) – The operation to check.

Returns:

True for GateCall, Block, BlockCall, and the Inverse of a GateCall.

Return type:

bool

decompose_step(op, qubits, bits, zvars)[source]

Expand one level of a container operation.

Parameters:
  • op (Operation) – The container to expand.

  • qubits (Sequence[int]) – Qubit indices the container acts on.

  • bits (Sequence[int]) – Classical bit indices the container acts on.

  • zvars (Sequence[int]) – Z-variable indices the container acts on.

Returns:

A new Circuit with the contents of op on those indices.

Raises:

DecompositionError – If op is not a container this rule matches.

Return type:

Circuit

class ZYZRewrite[source]

Bases: RewriteRule

Rewrite rule for the ZYZ Euler decomposition of single-qubit gates.

Writes a single-qubit gate as Z and Y rotations, the Euler form \(R_Z(\phi) R_Y(\theta) R_Z(\lambda)\).

Supported Operations

  • GateU(theta, phi, lambda, gamma), except the identity (all of theta, phi and lambda zero), to RZ(lambda), RY(theta), RZ(phi) in circuit order, followed by GateU(0, 0, 0, gamma) for the phase gamma. Rotations by a zero angle are left out. The result equals the gate up to a global phase.

  • GateRX(theta) to S, RY(theta), S† in circuit order, which is exact.

Examples

>>> from mimiqcircuits import *
>>> from symengine import pi
>>> rule = ZYZRewrite()
>>> # the Euler angles of GateU become Z and Y rotations
>>> rule.decompose_step(GateU(pi/2, pi/4, pi/3), [0], [], [])
1-qubit circuit with 3 instructions:
├── RZ((1/3)*pi) @ q[0]
├── RY((1/2)*pi) @ q[0]
└── RZ((1/4)*pi) @ q[0]
matches(op)[source]

Check whether an operation is a GateU or GateRX.

A GateU whose theta, phi and lambda are all zero is not matched, since it is only a phase.

Parameters:

op (Operation) – The operation to check.

Returns:

True for GateRX and for a non-identity GateU.

Return type:

bool

decompose_step(op, qubits, bits, zvars)[source]

Rewrite a GateU or GateRX as Z and Y rotations.

Parameters:
  • op (Operation) – The GateU or GateRX to rewrite.

  • qubits (Sequence[int]) – Qubit index the gate acts on.

  • bits (Sequence[int]) – Classical bit indices (unused).

  • zvars (Sequence[int]) – Z-variable indices (unused).

Returns:

A new Circuit with the rewrite.

Raises:

DecompositionError – If matches() rejects op.

Return type:

Circuit

class SpecialAngleRewrite(only_cliffords=False)[source]

Bases: RewriteRule

Rewrite rule that turns rotations by multiples of pi/4 into Clifford+T gates.

A rotation by k*pi/4 equals, up to a global phase, a short product of Clifford gates and at most one T (T†, or T conjugated into the X or Y axis). This rule writes that product out exactly. For example RZ(pi/4) becomes T, RZ(pi/2) becomes S and RX(pi) becomes X. Angles are compared to a multiple of pi/4 with a relative tolerance of 1e-9 (absolute 1e-10 near zero), modulo 2*pi. Other angles are not matched.

Parameters:

only_cliffords (bool) – If True, match only angles k*pi/2, whose rewrite uses Clifford gates only. Defaults to False, which matches every k*pi/4.

Supported Operations

  • GateRX(theta) with theta = k*pi/4

  • GateRY(theta) with theta = k*pi/4

  • GateRZ(lambda) with lambda = k*pi/4

Examples

>>> from mimiqcircuits import *
>>> from symengine import pi
>>> rule = SpecialAngleRewrite()
>>> # 3*pi/4 is a special angle: RZ(3*pi/4) is S followed by T
>>> rule.decompose_step(GateRZ(3*pi/4), [0], [], [])
1-qubit circuit with 2 instructions:
├── S @ q[0]
└── T @ q[0]

>>> # an arbitrary angle is not matched
>>> rule.matches(GateRZ(0.123))
False
>>> # pi/4 needs a T gate, which the Clifford-only mode refuses
>>> SpecialAngleRewrite(only_cliffords=True).matches(GateRZ(pi/4))
False
matches(op)[source]

Check whether an operation is a rotation by a special angle.

Parameters:

op (Operation) – The operation to check.

Returns:

True for a GateRX, GateRY or GateRZ whose angle is a multiple of pi/4, or of pi/2 when only_cliffords is set.

Return type:

bool

decompose_step(op, qubits, bits, zvars)[source]

Rewrite a rotation by a multiple of pi/4 as Clifford+T gates.

The result equals the rotation up to a global phase, and is empty for a multiple of 2*pi.

Parameters:
  • op (Operation) – The GateRX, GateRY or GateRZ to rewrite.

  • qubits (Sequence[int]) – Qubit index the rotation acts on.

  • bits (Sequence[int]) – Classical bit indices (unused).

  • zvars (Sequence[int]) – Z-variable indices (unused).

Returns:

A new Circuit with the rewrite.

Raises:

DecompositionError – If matches() refuses op.

Return type:

Circuit

class ToZRotationRewrite[source]

Bases: RewriteRule

Rewrite rule that turns GateRX and GateRY into GateRZ and Cliffords.

Use it for gate sets whose only parametric rotation is GateRZ. The rewrite is exact, keeps the angle as it is (symbolic angles included), and listed in circuit order is:

  • GateRX(theta) to H, RZ(theta), H;

  • GateRY(theta) to S†, H, RZ(theta), H, S.

Examples

>>> from mimiqcircuits import *
>>> from symengine import pi
>>> rule = ToZRotationRewrite()
>>> # an X rotation is a Z rotation conjugated by Hadamard gates
>>> rule.decompose_step(GateRX(pi/3), [0], [], [])
1-qubit circuit with 3 instructions:
├── H @ q[0]
├── RZ((1/3)*pi) @ q[0]
└── H @ q[0]
matches(op)[source]

Check whether an operation is an X or Y rotation.

Parameters:

op (Operation) – The operation to check.

Returns:

True for GateRX and GateRY.

Return type:

bool

decompose_step(op, qubits, bits, zvars)[source]

Rewrite an X or Y rotation as a Z rotation between Cliffords.

Parameters:
  • op (Operation) – The GateRX or GateRY to rewrite.

  • qubits (Sequence[int]) – Qubit index the rotation acts on.

  • bits (Sequence[int]) – Classical bit indices (unused).

  • zvars (Sequence[int]) – Z-variable indices (unused).

Returns:

A new Circuit with the rewrite.

Raises:

DecompositionError – If op is not a GateRX or GateRY.

Return type:

Circuit

class ToffoliToCliffordTRewrite[source]

Bases: RewriteRule

Rewrite rule that turns a Toffoli gate into Clifford+T gates.

Replaces GateCCX by the standard exact circuit of 15 gates: 7 T or T†, 2 H and 6 CX. No ancilla is used.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(GateCCX(), 0, 1, 2)
3-qubit circuit with 1 instruction:
└── C₂X @ q[0:1], q[2]

>>> # count the T and T† gates of the rewrite
>>> ct = decompose_step(c, ToffoliToCliffordTRewrite())
>>> sum(isinstance(inst.operation, (GateT, GateTDG)) for inst in ct)
7
matches(op)[source]

Check whether an operation is a Toffoli gate.

Parameters:

op (Operation) – The operation to check.

Returns:

True for GateCCX.

Return type:

bool

decompose_step(op, qubits, bits, zvars)[source]

Rewrite a Toffoli gate as 15 Clifford+T gates.

Parameters:
  • op (Operation) – The GateCCX to rewrite.

  • qubits (Sequence[int]) – The two control qubits, then the target.

  • bits (Sequence[int]) – Classical bit indices (unused).

  • zvars (Sequence[int]) – Z-variable indices (unused).

Returns:

A new Circuit with the rewrite.

Raises:

DecompositionError – If op is not a GateCCX or qubits does not hold exactly 3 indices.

Return type:

Circuit

class SolovayKitaevRewrite(depth=3, simplify=True, net_max_depth=10, net_max_points=50000, net_min_dist=0.02)[source]

Bases: RewriteRule

Rewrite rule that approximates single-qubit gates with Clifford+T by Solovay-Kitaev.

The rule starts from the closest entry of a precomputed table (an epsilon-net) of short sequences of H, T, T†, S, S†, X, Y and Z, and refines it depth times with group commutators. Refinements lower the error on average, not at every step, and each multiplies the length of the sequence by about 5. The approximation holds up to a global phase. For Z-rotations, GridSynthRewrite gives much shorter sequences for the same error.

Parameters:
  • depth (int) – Number of refinements, at least 0 (default 3). With 0 the closest table entry is used as it is.

  • simplify (bool) – Cancel and merge adjacent gates of the result, such as T followed by T† or two S (default True).

  • net_max_depth (int) – Longest sequence in the table (default 10).

  • net_max_points (int) – Largest number of table entries (default 50000).

  • net_min_dist (float) – Smallest distance between two table entries (default 0.02).

Raises:

ValueError – If depth is negative.

Supported Operations

  • GateRZ(λ), GateRY(θ) and GateRX(θ)

  • GateU(θ, φ, λ, γ)

Only numeric parameters are matched; symbolic ones are not.

Examples

>>> from mimiqcircuits import *
>>> # one refinement of the closest table entry
>>> rule = SolovayKitaevRewrite(depth=1)
>>> circ = rule.decompose_step(GateRZ(0.123), [0], [], [])
>>> # the result only uses Clifford+T gates
>>> {type(inst.operation) for inst in circ} <= {GateH, GateT, GateTDG, GateS, GateSDG, GateX, GateY, GateZ}
True

Note

The table is built on first use, which takes a few seconds, and is then kept for later calls with the same net_* settings.

matches(op)[source]

Check whether an operation is a numeric single-qubit rotation.

Parameters:

op (Operation) – The operation to check.

Returns:

True for a GateRX, GateRY, GateRZ or GateU with numeric parameters.

Return type:

bool

decompose_step(op, qubits, bits, zvars)[source]

Approximate a single-qubit gate with Clifford+T gates.

Parameters:
  • op (Operation) – The rotation or GateU to approximate.

  • qubits (Sequence[int]) – Qubit index the gate acts on.

  • bits (Sequence[int]) – Classical bit indices (unused).

  • zvars (Sequence[int]) – Z-variable indices (unused).

Returns:

A new Circuit with the Clifford+T approximation. It can be empty when the gate is close to the identity.

Raises:

DecompositionError – If matches() rejects op.

Return type:

Circuit

class GridSynthRewrite(epsilon=1e-10, seed=0)[source]

Bases: RewriteRule

Rewrite rule that approximates GateRZ with Clifford+T gates by gridsynth.

It implements the Ross–Selinger gridsynth algorithm. For GateRZ(λ) the rule emits a sequence of GateH, GateS, GateSDG, GateZ, GateT and GateX whose unitary V satisfies min_φ ‖RZ(λ) − e^{iφ}V‖ ≤ epsilon in operator norm. The approximation holds up to a global phase, which is dropped. The T-count is about 3·log₂(1/epsilon) and, except for rare failures of the integer factoring step, optimal among ancilla-free Clifford+T circuits with this error. Angles that are multiples of π/4 give their exact short decomposition.

The factoring step is randomized. For a fixed seed, the same angle and tolerance always give the same sequence. Results are cached per angle, since circuits often repeat the same rotation.

The synthesis runs in the compiled mimiqcircuits._core extension without holding the GIL, so several threads can synthesize in parallel.

Parameters:
  • epsilon (float) – Operator-norm tolerance, with 1e-100 <= epsilon < 1 (default 1e-10). A rotation takes a few milliseconds at 1e-10 and up to about a second at 1e-100.

  • seed (int) – Seed of the randomized factoring step, an integer in [0, 2**64) (default 0).

Raises:
  • ValueError – If epsilon or seed is out of range.

  • TypeError – If epsilon is not a real number or seed is not an integer.

Supported Operations

  • GateRZ(λ) with a numeric angle λ.

Symbolic angles are not matched. GateRX, GateRY and GateU must first be reduced to Z-rotations, for example with ZYZRewrite and ToZRotationRewrite. CliffordTBasis does this and uses this rule by default.

Examples

>>> from mimiqcircuits import *
>>> def tcount(c):
...     return sum(isinstance(i.operation, GateT) for i in c)
>>> # Approximate one rotation to the default tolerance 1e-10
>>> circ = GridSynthRewrite().decompose_step(GateRZ(0.123), [0], [], [])
>>> # A coarser tolerance gives fewer T gates
>>> coarse = GridSynthRewrite(epsilon=1e-4).decompose_step(GateRZ(0.123), [0], [], [])
>>> tcount(coarse) < tcount(circ)
True

References

N. J. Ross and P. Selinger, “Optimal ancilla-free Clifford+T approximation of z-rotations”, Quantum Inf. Comput. 16, 901 (2016), arXiv:1403.2975.

matches(op)[source]

Check if this rule can decompose the operation.

Parameters:

op (Operation) – The operation to check.

Returns:

True if the operation is a GateRZ with a numeric angle.

Return type:

bool

decompose_step(op, qubits, bits, zvars)[source]

Decompose the Z-rotation into Clifford+T gates.

Parameters:
  • op (Operation) – The GateRZ to decompose.

  • qubits (Sequence[int]) – Qubit indices for the operation.

  • bits (Sequence[int]) – Classical bit indices (unused).

  • zvars (Sequence[int]) – Z-variable indices (unused).

Returns:

A new Circuit with the Clifford+T approximation.

Raises:
Return type:

Circuit

decompose(source, basis=None, wrap=False)[source]

Recursively decompose a circuit to a target basis.

Rewrites every operation of source that is not terminal in basis, and repeats on the result, until only terminal operations are left. The source is not modified.

Parameters:
  • source (Circuit | Instruction | Operation) – The circuit, instruction or operation to decompose. A bare operation is placed on qubits, bits and z-variables 0, 1, ....

  • basis (DecompositionBasis | RewriteRule | None) – The target basis. A RewriteRule is wrapped in a RuleBasis, so it is applied until it no longer matches. Defaults to CanonicalBasis.

  • wrap (bool) – If False (default), the result holds only terminal operations. If True, each non-terminal gate becomes a GateCall to a GateDecl holding its decomposition, and each other non-terminal operation (such as MeasureReset) a Block holding its decomposition, both wrapped again at every level. Gates that differ only in their parameters share one GateDecl. A gate whose decomposition measures an ancilla (allow_measurement=True) becomes a BlockCall to a shared BlockDecl. This keeps the structure of the original circuit visible.

Returns:

A new Circuit of terminal operations, plus GateCall and Block operations when wrap=True.

Raises:
Return type:

Circuit

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]

>>> c.push(GateCCX(), 0, 1, 2)
3-qubit circuit with 2 instructions:
├── H @ q[0]
└── C₂X @ q[0:1], q[2]
>>> # the default basis leaves only GateU and GateCX
>>> sorted({type(inst.operation).__name__ for inst in decompose(c)})
['GateCX', 'GateU']
>>> # any other basis can be given
>>> sorted({type(inst.operation).__name__ for inst in decompose(c, CliffordTBasis())})
['GateCX', 'GateH', 'GateT', 'GateTDG']
>>> # with wrap=True each gate becomes a call to a declared gate,
>>> # so the two CH gates share one declaration
>>> c = Circuit()
>>> c.push(GateCH(), 0, 1)
2-qubit circuit with 1 instruction:
└── CH @ q[0], q[1]

>>> c.push(GateCH(), 1, 2)
3-qubit circuit with 2 instructions:
├── CH @ q[0], q[1]
└── CH @ q[1], q[2]

>>> decompose(c, wrap=True)
3-qubit circuit with 2 instructions:
├── mimiq_CH() @ q[0:1]
└── mimiq_CH() @ q[1:2]
decompose_step(source, rule=None)[source]

Apply a rewrite rule once to every instruction of a circuit.

Each instruction whose operation matches rule is replaced by the result of RewriteRule.decompose_step(); the others are copied unchanged. Unlike decompose(), the result is not rewritten again, so it can still hold operations that match rule.

Parameters:
Returns:

A new Circuit with the rule applied once.

Raises:

TypeError – If source is not a circuit, instruction or operation.

Return type:

Circuit

Examples

>>> from mimiqcircuits import *
>>> from symengine import pi
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]

>>> c.push(GateRX(pi/3), 0)
1-qubit circuit with 2 instructions:
├── H @ q[0]
└── RX((1/3)*pi) @ q[0]

>>> # ZYZRewrite matches RX but not H, so only RX is rewritten
>>> decompose_step(c, ZYZRewrite())
1-qubit circuit with 4 instructions:
├── H @ q[0]
├── S @ q[0]
├── RY((1/3)*pi) @ q[0]
└── S† @ q[0]
>>> # the default rule expands one level of the built-in decomposition
>>> decompose_step(GateSWAP())
2-qubit circuit with 3 instructions:
├── CX @ q[0], q[1]
├── CX @ q[1], q[0]
└── CX @ q[0], q[1]
eachdecomposed(source, basis=None, wrap=False)[source]

Iterate over the instructions of a recursive decomposition.

Yields the same instructions as decompose(), one at a time, without building the decomposed circuit. Use it to stream a large decomposition or to stop early.

Parameters:
Returns:

A DecomposeIterator over the decomposed instructions.

Raises:
  • TypeError – If source is not a circuit, instruction or operation.

  • DecompositionError – While iterating, if basis cannot decompose an operation.

Return type:

DecomposeIterator

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(GateCCX(), 0, 1, 2)
3-qubit circuit with 1 instruction:
└── C₂X @ q[0:1], q[2]

>>> # instructions are computed as they are requested
>>> it = eachdecomposed(c)
>>> next(it)
U((1/2)*pi, 0, pi, 0.0) @ q[2]
class DecomposeIterator(source, basis, wrap=False, cache=None, nqubits=0, ctx=None)[source]

Bases: Iterator[Instruction]

Iterator over the instructions of a recursive decomposition.

Decomposes depth-first and yields each terminal instruction as soon as it is reached, in circuit order, so the decomposed circuit is never held in memory at once. Each non-terminal operation is decomposed only when the iteration reaches it. eachdecomposed() builds one with the default basis, and decompose() collects one into a circuit.

Parameters:
  • source (Circuit | Instruction | Operation) – The circuit, instruction or operation to decompose. A bare operation is placed on qubits, bits and z-variables 0, 1, ....

  • basis (DecompositionBasis) – The target basis. Unlike decompose(), a rewrite rule is not accepted here; wrap it in a RuleBasis.

  • wrap (bool) – If False (default), yield only terminal operations. If True, yield each non-terminal gate as a GateCall to a GateDecl holding its decomposition, and each other non-terminal operation (such as MeasureReset) as a Block holding its decomposition, in both cases wrapped again at every level. A gate whose decomposition measures an ancilla becomes a BlockCall to a BlockDecl.

  • cache (dict | None) – Dictionary that maps operations to the declaration built for them when wrap=True, keyed by the (symbolic) operation, the numbers of borrowed and clean qubits its body was offered, and whether it may measure. Pass the same dictionary to several iterators to share declarations between them. A new one is used by default.

  • nqubits (int) – Width of the circuit, which bounds the qubits a basis with borrow=True may borrow. Defaults to source.num_qubits() for a Circuit and to 0 (borrow nothing) for anything else, so the result never depends on the values of the target indices alone.

  • ctx (DecompositionContext | None) – The DecompositionContext to use instead of the one built from basis and nqubits.

Raises:
  • ValueError – If the basis borrows qubits and source contains Loss or Reload: losses act on qubits a borrowing decomposition relies on. Resolve them first, for example with lower_losses.

  • TypeError – If source is not a circuit, instruction or operation.

  • DecompositionError – While iterating, if the basis cannot decompose an operation.

Examples

>>> from mimiqcircuits import *
>>> c = Circuit()
>>> c.push(GateH(), 0)
1-qubit circuit with 1 instruction:
└── H @ q[0]

>>> # instructions are produced one at a time
>>> for inst in DecomposeIterator(c, CanonicalBasis()):
...     print(inst)
U((1/2)*pi, 0, pi, 0.0) @ q[0]

Modules

abstract

Abstract base classes for the decomposition framework.

basis

Decomposition bases for quantum circuits.

decompose(source[, basis, wrap])

Recursively decompose a circuit to a target basis.

rules

Rewrite rules for quantum circuit decomposition.