mimiqcircuits.decomposition.basis

Decomposition bases for quantum circuits.

The available bases are:

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

Modules

canonical

Canonical decomposition basis targeting GateU and GateCX.

clifford_t

Clifford+T decomposition basis.

flattened

Flattened decomposition basis.

qasm

OpenQASM 2.0 decomposition basis.

rule_basis

RuleBasis: Wrapper to use a RewriteRule as a DecompositionBasis.

stim

Stim stabilizer simulator decomposition basis.