mimiqcircuits.decomposition.rules¶
Rewrite rules for quantum circuit decomposition.
The available rules are:
CanonicalRewrite: Uses built-in gate decomposition methodsFlattenContainers: Flattens GateCall/Block/BlockCall containersZYZRewrite: ZYZ Euler angle decompositionSpecialAngleRewrite: Decompose rotations with special angles to Clifford+TToZRotationRewrite: Convert RX/RY to RZ + Clifford gatesToffoliToCliffordTRewrite: Toffoli -> Clifford+T with 7 T gatesSolovayKitaevRewrite: Solovay-Kitaev approximation with Clifford+TGridSynthRewrite: Ross-Selinger approximation of RZ with Clifford+T
- class CanonicalRewrite[source]¶
Bases:
RewriteRuleRewrite 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,GateCXand the non-unitary primitives, which is whatCanonicalBasisdoes. One step can stop earlier:GateCCX, for example, becomesGateH,GateT,GateTDGandGateCX.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 thatCanonicalBasiskeeps terminal (such asResetX) still matches, so other bases can expand it. Primitives without a decomposition (GateU,GateCX,Measure,Reset,Barrier, …) do not match.
- decompose_step(op, qubits, bits, zvars)[source]¶
Apply one step of the built-in decomposition of an operation.
No check is made that
matches()acceptsop. A primitive returns a circuit holding just itself.- Parameters:
- Returns:
A new
Circuitwith the decomposition.- Return type:
- 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:
RewriteRuleRewrite rule that expands container operations into their contents.
Matches
GateCall,Block,BlockCall, and theInverseof aGateCall, and replaces each by the instructions it holds (inverted for anInverse), remapped onto the targets. One step expands one level: nested containers stay as they are. Gates are never decomposed.FlattenedBasisrepeats 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]
- decompose_step(op, qubits, bits, zvars)[source]¶
Expand one level of a container operation.
- Parameters:
- Returns:
A new
Circuitwith the contents ofopon those indices.- Raises:
DecompositionError – If
opis not a container this rule matches.- Return type:
- class ZYZRewrite[source]¶
Bases:
RewriteRuleRewrite 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 oftheta,phiandlambdazero), toRZ(lambda),RY(theta),RZ(phi)in circuit order, followed byGateU(0, 0, 0, gamma)for the phasegamma. Rotations by a zero angle are left out. The result equals the gate up to a global phase.GateRX(theta)toS,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
GateUorGateRX.A
GateUwhosetheta,phiandlambdaare all zero is not matched, since it is only a phase.
- decompose_step(op, qubits, bits, zvars)[source]¶
Rewrite a
GateUorGateRXas Z and Y rotations.- Parameters:
- Returns:
A new
Circuitwith the rewrite.- Raises:
DecompositionError – If
matches()rejectsop.- Return type:
- class SpecialAngleRewrite(only_cliffords=False)[source]¶
Bases:
RewriteRuleRewrite rule that turns rotations by multiples of
pi/4into Clifford+T gates.A rotation by
k*pi/4equals, up to a global phase, a short product of Clifford gates and at most oneT(T†, orTconjugated into the X or Y axis). This rule writes that product out exactly. For exampleRZ(pi/4)becomesT,RZ(pi/2)becomesSandRX(pi)becomesX. Angles are compared to a multiple ofpi/4with a relative tolerance of1e-9(absolute1e-10near zero), modulo2*pi. Other angles are not matched.- Parameters:
only_cliffords (bool) – If
True, match only anglesk*pi/2, whose rewrite uses Clifford gates only. Defaults toFalse, which matches everyk*pi/4.
Supported Operations
GateRX(theta)withtheta = k*pi/4GateRY(theta)withtheta = k*pi/4GateRZ(lambda)withlambda = 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
- decompose_step(op, qubits, bits, zvars)[source]¶
Rewrite a rotation by a multiple of
pi/4as Clifford+T gates.The result equals the rotation up to a global phase, and is empty for a multiple of
2*pi.- Parameters:
- Returns:
A new
Circuitwith the rewrite.- Raises:
DecompositionError – If
matches()refusesop.- Return type:
- class ToZRotationRewrite[source]¶
Bases:
RewriteRuleRewrite rule that turns
GateRXandGateRYintoGateRZand 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)toH,RZ(theta),H;GateRY(theta)toS†,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]
- decompose_step(op, qubits, bits, zvars)[source]¶
Rewrite an X or Y rotation as a Z rotation between Cliffords.
- Parameters:
- Returns:
A new
Circuitwith the rewrite.- Raises:
DecompositionError – If
opis not aGateRXorGateRY.- Return type:
- class ToffoliToCliffordTRewrite[source]¶
Bases:
RewriteRuleRewrite rule that turns a Toffoli gate into Clifford+T gates.
Replaces
GateCCXby the standard exact circuit of 15 gates: 7TorT†, 2Hand 6CX. 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
- decompose_step(op, qubits, bits, zvars)[source]¶
Rewrite a Toffoli gate as 15 Clifford+T gates.
- Parameters:
- Returns:
A new
Circuitwith the rewrite.- Raises:
DecompositionError – If
opis not aGateCCXorqubitsdoes not hold exactly 3 indices.- Return type:
- class SolovayKitaevRewrite(depth=3, simplify=True, net_max_depth=10, net_max_points=50000, net_min_dist=0.02)[source]¶
Bases:
RewriteRuleRewrite 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,YandZ, and refines itdepthtimes 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,GridSynthRewritegives much shorter sequences for the same error.- Parameters:
depth (int) – Number of refinements, at least 0 (default
3). With0the closest table entry is used as it is.simplify (bool) – Cancel and merge adjacent gates of the result, such as
Tfollowed byT†or twoS(defaultTrue).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
depthis negative.
Supported Operations
GateRZ(λ),GateRY(θ)andGateRX(θ)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.- decompose_step(op, qubits, bits, zvars)[source]¶
Approximate a single-qubit gate with Clifford+T gates.
- Parameters:
- Returns:
A new
Circuitwith the Clifford+T approximation. It can be empty when the gate is close to the identity.- Raises:
DecompositionError – If
matches()rejectsop.- Return type:
- class GridSynthRewrite(epsilon=1e-10, seed=0)[source]¶
Bases:
RewriteRuleRewrite rule that approximates
GateRZwith Clifford+T gates by gridsynth.It implements the Ross–Selinger gridsynth algorithm. For
GateRZ(λ)the rule emits a sequence ofGateH,GateS,GateSDG,GateZ,GateTandGateXwhose unitaryVsatisfiesmin_φ ‖RZ(λ) − e^{iφ}V‖ ≤ epsilonin operator norm. The approximation holds up to a global phase, which is dropped. The T-count is about3·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π/4give 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._coreextension without holding the GIL, so several threads can synthesize in parallel.- Parameters:
- Raises:
ValueError – If
epsilonorseedis out of range.TypeError – If
epsilonis not a real number orseedis not an integer.
Supported Operations
GateRZ(λ)with a numeric angleλ.
Symbolic angles are not matched.
GateRX,GateRYandGateUmust first be reduced to Z-rotations, for example withZYZRewriteandToZRotationRewrite.CliffordTBasisdoes 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.
- decompose_step(op, qubits, bits, zvars)[source]¶
Decompose the Z-rotation into Clifford+T gates.
- Parameters:
- Returns:
A new
Circuitwith the Clifford+T approximation.- Raises:
DecompositionError – If the operation is not a numeric
GateRZ.ValueError – If the angle is not finite.
- Return type:
Modules
Canonical rewrite rule for decomposing operations to GateU and GateCX. |
|
Rewrite rule for flattening container operations. |
|
Ross–Selinger gridsynth: Clifford+T approximation of Z-rotations. |
|
Solovay-Kitaev algorithm for approximating arbitrary unitaries with Clifford+T. |
|
Special angle rewrite rule for Clifford+T decomposition. |
|
Rewrite rule for converting X and Y rotations to Z rotations. |
|
Rewrite rule for decomposing Toffoli into Clifford+T. |
|
ZYZ Euler angle decomposition rewrite rule. |