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
decompose(): recursively decompose a circuit, instruction or operation to a basis, and return a new circuit.eachdecomposed(): the same, as a lazy iterator over the resulting instructions.decompose_step(): apply a rewrite rule once, without recursion.DecomposeIterator: the iterator behinddecompose()andeachdecomposed().
A function that takes a basis also accepts a rewrite rule, wrapped in a
RuleBasis.
Bases
CanonicalBasis:GateUandGateCX, 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: expandsGateCall,BlockandBlockCallcontainers and keeps everything else.RuleBasis: applies one rewrite rule until it no longer matches.
Rules
CanonicalRewrite: the built-in decomposition of each operation.FlattenContainers: expands one level ofGateCall,BlockandBlockCall.ZYZRewrite:GateUandGateRXto Z and Y rotations.ToZRotationRewrite:GateRXandGateRYtoGateRZand Clifford gates.SpecialAngleRewrite: rotations by multiples ofpi/4to exact Clifford+T gates.ToffoliToCliffordTRewrite:GateCCXto Clifford+T with 7 T gates.GridSynthRewrite:GateRZapproximated with Clifford+T by the Ross-Selinger algorithm.SolovayKitaevRewrite: single-qubit rotations approximated with Clifford+T by the Solovay-Kitaev algorithm.
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:
ABCAbstract 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 withdecompose(), which wraps it in aRuleBasisand rewrites until nothing matches. For a target gate set, seeDecompositionBasis.A subclass implements
matches()anddecompose_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:
Trueifdecompose_step()acceptsop.- Return type:
- 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:
- Returns:
A new
Circuitthat implementsopon those indices.- Raises:
DecompositionError – If the rule cannot rewrite
op.- 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 DecompositionBasis[source]¶
Bases:
ABCAbstract 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 withdecompose()and repeats on the result until only terminal operations are left.A subclass implements
isterminal()anddecompose().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.
- abstract decompose(op, qubits, bits, zvars)[source]¶
Rewrite a non-terminal operation one step.
Called by
decompose()only for operations thatisterminal()rejects. The result does not need to be terminal:decompose()keeps rewriting it.- Parameters:
- Returns:
A new
Circuitthat implementsopon those indices.- Raises:
DecompositionError – If the basis has no rewrite for
op.- Return type:
- 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 callsdecompose().
- class DecompositionContext(nqubits=0, borrow=False, unitary_only=False, allocator=None, bit=None)[source]¶
Bases:
objectState that
decompose()hands to a basis and its rules.The context goes next to the operation and its targets, through
DecompositionBasis.decompose_ctx()andRewriteRule.decompose_step_ctx().- Parameters:
nqubits (int) – Width of the circuit being decomposed. Qubits
0, ..., nqubits - 1that are not targets of the operation may be borrowed.0means 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
GateDeclor of anIfStatement.
decompose()also hands out clean ancillas through the context when the basis hasmax_ancillas > 0. A rule that takes them brackets their use withAncillaAllocandAncillaFreeand returns them in|0>. Withallow_measurement=Trueon 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
*_ctxmethods, which drop it and call the method without it.
- exception DecompositionError[source]¶
Bases:
ExceptionRaised 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 fromRewriteRule.decompose_step()for an operation they do not match.
- class CanonicalBasis(borrow=False, max_ancillas=0, allow_measurement=False)[source]¶
Bases:
DecompositionBasisDecomposition basis targeting
GateUandGateCX.Every gate is rewritten into
GateU(an arbitrary single-qubit gate) andGateCX, 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 ofdecompose().- 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
AncillaAllocandAncillaFree. 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 aValueError.
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
GateUandGateCX;Measure;Reset,ResetXandResetY;Loss,Reload,CheckandMeasureCheck;BarrierandDelay; classical operations and annotations; noise channels andReadoutErr;ExpectationValue,Amplitude,SchmidtRank,VonNeumannEntropyandBondDim; and the z-register operationsAdd,MultiplyandPow. AnIfStatementorWhileStatementis terminal when its body is.
- decompose(op, qubits, bits, zvars)[source]¶
Rewrite a non-terminal operation with its built-in decomposition.
- Parameters:
- Returns:
A new
Circuitwith one decomposition step.- Raises:
DecompositionError – If
ophas no built-in decomposition.- Return type:
- 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:
DecompositionBasisDecomposition 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
StimBasisplusGateTandGateTDG, 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, andRPauliwith a non-identity Pauli string;the non-Clifford
GateTandGateTDG;measurements, resets and measure-and-resets in the X, Y and Z bases,
MeasureXX,MeasureYY,MeasureZZandMeasurePauli;Pauli noise:
PauliX,PauliY,PauliZ,Depolarizing1,Depolarizing2andPauliNoise;barriers and annotations;
classical operations, which
StimBasisdoes not keep;an
IfStatementwhose body is terminal in this basis, with any condition.StimBasisonly keeps a conditionalGateX,GateYorGateZon a single bit.
Non-terminal operations are rewritten by the first rule that matches, in this order:
SpecialAngleRewrite: rotations by multiples ofpi/4to exact Clifford+T.GateECRtoS,SX,CXandX, as inStimBasis, with no T gate.ToffoliToCliffordTRewrite:GateCCXto Clifford+T with 7 T gates.A
GateUwhose angles are all zero (a pure global phase) is dropped.ZYZRewrite:GateUtoRZ*RY*RZ, andGateRXtoGateRYbetweenSandS†.ToZRotationRewrite:GateRYtoGateRZand Cliffords.The
rotationsrule (defaultGridSynthRewrite): remainingGateRZto an approximate Clifford+T sequence.CanonicalRewrite: any other operation, towardGateUandGateCX. AGateRX,GateRYorGateRZthat reaches this point has a symbolic angle and raisesDecompositionError.
The
rotationsrule only sees angles that step 1 could not decompose exactly. The body of anIfStatementgoes through the same pipeline and stays conditional. No T-count optimization is performed on the result.- Parameters:
sk_depth (int | None) – Use
SolovayKitaevRewritewith this recursion depth as therotationsrule.rotations (RewriteRule) – Rule that synthesizes the remaining Z-rotations. The default
GridSynthRewrite()approximates each rotation to operator-norm error1e-10. The rule must matchGateRZwith 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
AncillaAllocandAncillaFree. 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 aValueError. With a clean ancilla, aGateCCXthen 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_depthandrotationsare given, or ifrotationsdoes not matchGateRZ.
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))
- 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:
- Returns:
A new
Circuitwith the rewrite.- Raises:
DecompositionError – If no rule applies to
op.- Return type:
- 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:
DecompositionBasisDecomposition basis that expands containers and keeps every other operation.
GateCall,BlockandBlockCall, and theInverseof aGateCall, are expanded withFlattenContainersuntil none is left, at any depth. AnIfStatementwhose body is a container becomes one conditional instruction per instruction of the body. Gates are not decomposed, and that includes aGateCallwrapped inControl,Power,ParallelorRepeat, 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]
- decompose(op, qubits, bits, zvars)[source]¶
Expand one level of a container.
- Parameters:
- Returns:
A new
Circuitwith the contents ofop, each made conditional ifopis anIfStatement.- Raises:
DecompositionError – If
opis not a container.- Return type:
- class QASMBasis(borrow=False, max_ancillas=0, allow_measurement=False)[source]¶
Bases:
DecompositionBasisDecomposition basis targeting the OpenQASM 2.0 gate library.
The terminal gates are the OpenQASM 2.0 built-ins and the gates of the
qelib1.incinclude 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 standardqelib1.inc.The terminal operations are:
the OpenQASM 2.0 built-ins
GateUandGateCX;the single-qubit gates of
qelib1.inc:GateU3,GateU2,GateU1,GateID,GateX,GateY,GateZ,GateH,GateS,GateSDG,GateT,GateTDG,GateRX,GateRYandGateRZ;the two-qubit gates of
qelib1.inc:GateCY,GateCZ,GateCH,GateCRX,GateCRY,GateCRZ,GateSWAP,GateRXXandGateRZZ;the three- and four-qubit gates of
qelib1.inc:GateCCX,GateCSWAPandGateC3X;Measure,ResetandBarrier, but not the X and Y variants ofMeasureandReset;annotations, such as
AncillaAlloc, which the OpenQASM writer drops;an
IfStatementwhose body is terminal;a
GateCallwhose 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, …) raiseDecompositionError.MeasureResetdecomposes intoMeasurefollowed byReset. This leaves the same state and bit as its canonical decomposition, a measurement and anXconditioned 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, soWhileStatementraisesDecompositionError.- 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
AncillaAllocandAncillaFree. 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 aValueError.
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]
See also
- decompose(op, qubits, bits, zvars)[source]¶
Rewrite a non-terminal operation one step toward OpenQASM 2.0.
MeasureResetbecomesMeasureandReset; every other operation goes throughCanonicalRewrite.- Parameters:
- Returns:
A new
Circuitwith the rewrite.- Raises:
DecompositionError – If
opis aWhileStatementor has no built-in decomposition.- Return type:
- 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:
DecompositionBasisDecomposition 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()andeachdecomposed()wrap a rule passed in place of a basis in aRuleBasis.- 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]
- decompose(op, qubits, bits, zvars)[source]¶
Apply the rule once to an operation.
- Parameters:
- Returns:
A new
Circuitwith the rewrite. For anIfStatementthe rule does not match, the rewrite of its body, with each instruction made conditional.- Raises:
DecompositionError – If the rule cannot rewrite
op.- Return type:
- decompose_ctx(op, qubits, bits, zvars, ctx)[source]¶
Apply the rule once, with a context, as
decompose()does.
- class StimBasis[source]¶
Bases:
DecompositionBasisDecomposition 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:
A
GateUwhose angles are all zero (a pure global phase) is dropped.ZYZRewrite:GateUtoRZ*RY*RZ, andGateRXtoGateRYbetweenSandS†.SpecialAngleRewritewithonly_cliffords=True: rotations by multiples ofpi/2to Clifford gates.GateECRtoS,SX,CXandX, equal up to a global phase. Stim has no ECR instruction, and the canonical decomposition goes through non-CliffordRZX(+-pi/4).CanonicalRewrite: any other operation.
A
GateRX,GateRYorGateRZby any other angle is not a Clifford gate and raisesDecompositionError; so does any non-Clifford gate that reduces to one, such asGateT. UseCliffordTBasisfor such circuits.The terminal operations are:
single-qubit Cliffords:
GateID,GateX,GateY,GateZ,GateH,GateHXY,GateHYZ,GateS,GateSDG,GateSX,GateSXDG,GateSYandGateSYDG;two-qubit Cliffords:
GateCX,GateCY,GateCZ,GateSWAP,GateISWAP,GateISWAPDGandGateDCX;Pauli rotations by
+-pi/2:GateRXX,GateRYY,GateRZZ, andRPauliwith a non-identity Pauli string. Angles are compared modulo2*pi, since a rotation by3*pi/2equals one by-pi/2up to a global phase. Other angles are decomposed;measurements in any Pauli basis:
Measure,MeasureX,MeasureY,MeasureXX,MeasureYY,MeasureZZandMeasurePauli;resets and measure-and-resets in the Z, X and Y bases:
Reset,ResetX,ResetY,MeasureReset,MeasureResetXandMeasureResetY;Pauli noise:
PauliX,PauliY,PauliZ,Depolarizing1,Depolarizing2andPauliNoise;Barrierand annotations, includingDetector,ObservableIncludeandQubitCoordinates;feedback: an
IfStatementofGateX,GateYorGateZconditioned on a single bit being1.
The same Pauli conditioned on a bit being
0becomes the Pauli followed by the Pauli conditioned on1. Any other conditional operation has its body decomposed while staying conditional, and raisesDecompositionErrorif that does not lead to conditional Paulis.The terminal operations correspond to Stim instructions as follows.
MIMIQ Operation
Stim Operation
GateIDIGateXXGateYYGateZZGateHHGateHXYH_XYGateHYZH_YZGateSSGateSDGS_DAGGateSXSQRT_XGateSXDGSQRT_X_DAGGateSYSQRT_YGateSYDGSQRT_Y_DAGGateCXCNOT/CXGateCYCYGateCZCZGateSWAPSWAPGateISWAPISWAPGateISWAPDGISWAP_DAGGateDCXSWAPCXGateRXX(+-pi/2)SQRT_XX/SQRT_XX_DAGGateRYY(+-pi/2)SQRT_YY/SQRT_YY_DAGGateRZZ(+-pi/2)SQRT_ZZ/SQRT_ZZ_DAGRPauli(P, +-pi/2)SPP/SPP_DAGIfStatement(GateX(), 1)CX rec[-k] qIfStatement(GateY(), 1)CY rec[-k] qIfStatement(GateZ(), 1)CZ rec[-k] qMeasureMMeasureXMXMeasureYMYMeasureXXMXXMeasureYYMYYMeasureZZMZZMeasurePauliMPPResetRResetXRXResetYRYMeasureResetMRMeasureResetXMRXMeasureResetYMRYPauliXX_ERRORPauliYY_ERRORPauliZZ_ERRORDepolarizing1DEPOLARIZE1Depolarizing2DEPOLARIZE2PauliNoisePAULI_CHANNEL_1,PAULI_CHANNEL_2orE/ELSE_CORRELATED_ERRORDetectorDETECTORObservableIncludeOBSERVABLE_INCLUDEQubitCoordinatesQUBIT_COORDSGateECRis 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.
See also
- 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:
- Returns:
A new
Circuitwith the rewrite.- Raises:
DecompositionError – If
opis a rotation by an angle that is not a multiple ofpi/2, a conditional operation Stim cannot express, or has no built-in decomposition.- Return type:
- 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:
- decompose(source, basis=None, wrap=False)[source]¶
Recursively decompose a circuit to a target basis.
Rewrites every operation of
sourcethat is not terminal inbasis, 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
RewriteRuleis wrapped in aRuleBasis, so it is applied until it no longer matches. Defaults toCanonicalBasis.wrap (bool) – If
False(default), the result holds only terminal operations. IfTrue, each non-terminal gate becomes aGateCallto aGateDeclholding its decomposition, and each other non-terminal operation (such asMeasureReset) aBlockholding its decomposition, both wrapped again at every level. Gates that differ only in their parameters share oneGateDecl. A gate whose decomposition measures an ancilla (allow_measurement=True) becomes aBlockCallto a sharedBlockDecl. This keeps the structure of the original circuit visible.
- Returns:
A new
Circuitof terminal operations, plusGateCallandBlockoperations whenwrap=True.- Raises:
TypeError – If
sourceis not a circuit, instruction or operation.DecompositionError – If
basiscannot decompose an operation, for example aGateTinStimBasis.
- Return type:
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
ruleis replaced by the result ofRewriteRule.decompose_step(); the others are copied unchanged. Unlikedecompose(), the result is not rewritten again, so it can still hold operations that matchrule.- Parameters:
source (Circuit | Instruction | Operation) – The circuit, instruction or operation to rewrite. A bare operation is placed on qubits, bits and z-variables
0, 1, ....rule (RewriteRule | None) – The rewrite rule to apply. Defaults to
CanonicalRewrite. ADecompositionBasisis not accepted.
- Returns:
A new
Circuitwith the rule applied once.- Raises:
TypeError – If
sourceis not a circuit, instruction or operation.- Return type:
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:
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
RewriteRuleis wrapped in aRuleBasis. Defaults toCanonicalBasis.wrap (bool) – Wrap non-terminal operations instead of expanding them, as in
decompose(). Defaults toFalse.
- Returns:
A
DecomposeIteratorover the decomposed instructions.- Raises:
TypeError – If
sourceis not a circuit, instruction or operation.DecompositionError – While iterating, if
basiscannot decompose an operation.
- Return type:
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, anddecompose()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 aRuleBasis.wrap (bool) – If
False(default), yield only terminal operations. IfTrue, yield each non-terminal gate as aGateCallto aGateDeclholding its decomposition, and each other non-terminal operation (such asMeasureReset) as aBlockholding its decomposition, in both cases wrapped again at every level. A gate whose decomposition measures an ancilla becomes aBlockCallto aBlockDecl.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=Truemay borrow. Defaults tosource.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
DecompositionContextto use instead of the one built frombasisandnqubits.
- Raises:
ValueError – If the basis borrows qubits and
sourcecontainsLossorReload: losses act on qubits a borrowing decomposition relies on. Resolve them first, for example withlower_losses.TypeError – If
sourceis 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