mimiqcircuits.decomposition.rules

Rewrite rules for quantum circuit decomposition.

The available rules are:

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

Modules

canonical

Canonical rewrite rule for decomposing operations to GateU and GateCX.

flatten_containers

Rewrite rule for flattening container operations.

gridsynth

Ross–Selinger gridsynth: Clifford+T approximation of Z-rotations.

solovay_kitaev

Solovay-Kitaev algorithm for approximating arbitrary unitaries with Clifford+T.

special_angle

Special angle rewrite rule for Clifford+T decomposition.

to_z_rotation

Rewrite rule for converting X and Y rotations to Z rotations.

toffoli_to_clifford_t

Rewrite rule for decomposing Toffoli into Clifford+T.

zyz

ZYZ Euler angle decomposition rewrite rule.