#
# Copyright © 2023-2025 QPerfect. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Decomposition bases targeting two rotation axes and GateCZ."""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Sequence
from symengine import pi
from mimiqcircuits.decomposition.abstract import (
DecompositionBasis,
DecompositionError,
_AncillaOptions,
)
if TYPE_CHECKING:
from mimiqcircuits.circuit import Circuit
from mimiqcircuits.operations.operation import Operation
@dataclass(frozen=True, init=False)
class _RotationCZBasis(DecompositionBasis):
"""Shared terminals and pipeline of :class:`RXRZCZBasis` and :class:`RXRYCZBasis`."""
ancillas: _AncillaOptions
def __init__(
self,
borrow: bool = False,
max_ancillas: int = 0,
allow_measurement: bool = False,
):
object.__setattr__(
self,
"ancillas",
_AncillaOptions(
borrow=borrow,
max_ancillas=max_ancillas,
allow_measurement=allow_measurement,
),
)
def _ancillaoptions(self):
return self.ancillas
def _axis(self) -> type:
"""The rotation gate kept besides ``GateRX``."""
raise NotImplementedError
def isterminal(self, op: Operation) -> bool:
"""Check whether an operation is terminal in this basis.
``GateRX``, ``GateCZ`` and the second rotation are terminal with any
angle. ``GateID`` is terminal too, so a circuit padded with it keeps
its width. Non-gate operations that are terminal in
:class:`CanonicalBasis` are terminal here too. An ``IfStatement`` or
``WhileStatement`` is terminal when its body is.
Args:
op: The operation to check.
Returns:
``True`` if ``op`` is terminal.
"""
from mimiqcircuits.decomposition.basis.canonical import CanonicalBasis
from mimiqcircuits.operations.gates.standard.cpauli import GateCX, GateCZ
from mimiqcircuits.operations.gates.standard.id import GateID
from mimiqcircuits.operations.gates.standard.rotations import GateRX
from mimiqcircuits.operations.gates.standard.u import GateU
from mimiqcircuits.operations.ifstatement import IfStatement
from mimiqcircuits.operations.whilestatement import WhileStatement
# CanonicalBasis checks the body against itself, so recurse here.
if isinstance(op, (IfStatement, WhileStatement)):
return self.isterminal(op.get_operation())
if isinstance(op, (GateRX, GateCZ, GateID, self._axis())):
return True
# Non-gate terminals follow CanonicalBasis; its two gates are not ours.
if isinstance(op, (GateU, GateCX)):
return False
return CanonicalBasis().isterminal(op)
def decompose(
self,
op: Operation,
qubits: Sequence[int],
bits: Sequence[int],
zvars: Sequence[int],
) -> Circuit:
"""Rewrite a non-terminal operation one step toward this basis.
``GateU``, ``GateCX`` and ``MeasureReset`` are rewritten as the class
description says; every other operation goes through
:class:`CanonicalRewrite`.
Args:
op: The operation to rewrite.
qubits: Qubit indices the operation acts on.
bits: Classical bit indices the operation acts on.
zvars: Z-variable indices the operation acts on.
Returns:
A new :class:`~mimiqcircuits.Circuit` with one decomposition step.
Raises:
DecompositionError: If ``op`` has no built-in decomposition.
"""
from mimiqcircuits.circuit import Circuit
from mimiqcircuits.decomposition.rules import CanonicalRewrite
from mimiqcircuits.operations.gates.standard.cpauli import GateCX
from mimiqcircuits.operations.gates.standard.u import GateU
from mimiqcircuits.operations.ifstatement import (
IfStatement,
_decompose_ifstatement,
)
from mimiqcircuits.operations.measure import Measure
from mimiqcircuits.operations.measurereset import MeasureReset
from mimiqcircuits.operations.reset import Reset
if isinstance(op, IfStatement):
return _decompose_ifstatement(self, op, qubits, bits, zvars)
if isinstance(op, GateU):
return self._decompose_u(op.theta, op.phi, op.lmbda, qubits[0])
if isinstance(op, GateCX):
return self._decompose_cx(*qubits)
# The canonical conditional X would cost several conditional rotations.
if type(op) is MeasureReset:
c = Circuit()
c.push(Measure(), qubits[0], bits[0])
c.push(Reset(), qubits[0])
return c
# CanonicalRewrite never returns GateU or GateCX unchanged, so this ends.
rule = CanonicalRewrite()
if rule.matches(op):
return rule.decompose_step(op, qubits, bits, zvars)
raise DecompositionError(
f"Operation {op.name} cannot be decomposed into {type(self).__name__}."
)
def decompose_ctx(
self,
op: Operation,
qubits: Sequence[int],
bits: Sequence[int],
zvars: Sequence[int],
ctx,
) -> Circuit:
"""Decompose with a context, which only some operations use.
The context carries the borrowed qubits, the clean ancillas and the
measurement bit. Operations without a rule that uses it go to
:meth:`decompose`.
"""
from mimiqcircuits.decomposition.abstract import _uses_context
from mimiqcircuits.decomposition.rules import CanonicalRewrite
from mimiqcircuits.operations.ifstatement import (
IfStatement,
_decompose_ifstatement,
)
if isinstance(op, IfStatement):
return _decompose_ifstatement(self, op, qubits, bits, zvars, ctx)
# GateCX is a Control that CanonicalRewrite refuses; it takes the
# plain path.
rule = CanonicalRewrite()
if _uses_context(op) and rule.matches(op):
return rule.decompose_step_ctx(op, qubits, bits, zvars, ctx)
return self.decompose(op, qubits, bits, zvars)
[docs]
@dataclass(frozen=True, init=False)
class RXRZCZBasis(_RotationCZBasis):
"""Decomposition basis targeting ``GateRX``, ``GateRZ`` and ``GateCZ``.
Rotations keep any angle, including symbolic ones. ``GateID`` is kept, so
a circuit padded with it keeps its width. Non-gate operations
that are terminal in :class:`CanonicalBasis` (measurements, resets,
barriers, noise, annotations, classical operations, ...) are terminal
here too. An ``IfStatement`` is terminal when its body is; otherwise its
body is decomposed into this basis and stays conditional.
Every other operation is first rewritten by :class:`CanonicalRewrite`
into ``GateU`` and ``GateCX``. Then:
- ``GateU(theta, phi, lmbda)`` becomes ``RZ(lmbda - pi/2)``,
``RX(theta)``, ``RZ(phi + pi/2)`` (circuit order), or a single
``RZ(phi + lmbda)`` when ``theta = 0``;
- ``GateCX`` becomes ``CZ`` with the target conjugated by
``RZ(pi/2)``, ``RX(pi/2)``;
- ``MeasureReset`` becomes ``Measure`` followed by ``Reset``, which
leaves the same state and bit as the canonical measurement and
conditional ``X``.
Global phases are dropped. Adjacent rotations are not merged; run
:func:`merge_rotations` on the result for that.
Args:
borrow: 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: Let decompositions add up to this many clean ancillas,
numbered after the qubits of the circuit and marked with
:class:`AncillaAlloc` and :class:`AncillaFree`. Ancillas freed by
one operation are reused by the next.
allow_measurement: 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, as in :class:`CanonicalBasis`.
Circuits whose width is unknown, such as a lone operation, get no
ancillas.
Examples:
>>> from mimiqcircuits import *
>>> c = Circuit().push(GateH(), 0)
>>> decompose(c, RXRZCZBasis())
1-qubit circuit with 3 instructions:
├── RZ((1/2)*pi) @ q[0]
├── RX((1/2)*pi) @ q[0]
└── RZ((1/2)*pi) @ q[0]
<BLANKLINE>
>>> # up to 2 clean ancillas, after the qubits of the circuit
>>> c = Circuit().push(Control(4, GateX()), 0, 1, 2, 3, 4)
>>> d = decompose(c, RXRZCZBasis(max_ancillas=2))
>>> ancillas(d)
[5, 6]
"""
def _axis(self):
from mimiqcircuits.operations.gates.standard.rotations import GateRZ
return GateRZ
# GateU(theta, phi, lmbda) = RZ(phi)·RY(theta)·RZ(lmbda) up to a global
# phase, which is dropped. RY(theta) = RZ(pi/2)·RX(theta)·RZ(-pi/2).
def _decompose_u(self, theta, phi, lmbda, q):
from mimiqcircuits.circuit import Circuit
from mimiqcircuits.decomposition.rules.zyz import _iszero
from mimiqcircuits.operations.gates.standard.rotations import GateRX, GateRZ
c = Circuit()
if _iszero(theta):
if not _iszero(phi + lmbda):
c.push(GateRZ(phi + lmbda), q)
return c
if not _iszero(lmbda - pi / 2):
c.push(GateRZ(lmbda - pi / 2), q)
c.push(GateRX(theta), q)
if not _iszero(phi + pi / 2):
c.push(GateRZ(phi + pi / 2), q)
return c
# CX = (I⊗V)·CZ·(I⊗V†) with V = RZ(-pi/2)·RX(-pi/2), which maps Z to X.
# Written with RY(pi/2) instead, the extra RZs would only commute through
# CZ and cancel.
def _decompose_cx(self, control, target):
from mimiqcircuits.circuit import Circuit
from mimiqcircuits.operations.gates.standard.cpauli import GateCZ
from mimiqcircuits.operations.gates.standard.rotations import GateRX, GateRZ
c = Circuit()
c.push(GateRZ(pi / 2), target)
c.push(GateRX(pi / 2), target)
c.push(GateCZ(), control, target)
c.push(GateRX(-pi / 2), target)
c.push(GateRZ(-pi / 2), target)
return c
[docs]
@dataclass(frozen=True, init=False)
class RXRYCZBasis(_RotationCZBasis):
"""Decomposition basis targeting ``GateRX``, ``GateRY`` and ``GateCZ``.
Rotations keep any angle, including symbolic ones. ``GateID`` is kept, so
a circuit padded with it keeps its width. Non-gate operations
that are terminal in :class:`CanonicalBasis` (measurements, resets,
barriers, noise, annotations, classical operations, ...) are terminal
here too. An ``IfStatement`` is terminal when its body is; otherwise its
body is decomposed into this basis and stays conditional.
Every other operation is first rewritten by :class:`CanonicalRewrite`
into ``GateU`` and ``GateCX``. Then:
- ``GateU(theta, phi, lmbda)`` becomes ``RY(pi/2)``, ``RX(lmbda)``,
``RY(theta)``, ``RX(phi)``, ``RY(-pi/2)`` (circuit order), omitting
rotations by zero;
- ``GateCX`` becomes ``CZ`` with the target conjugated by ``RY(-pi/2)``;
- ``MeasureReset`` becomes ``Measure`` followed by ``Reset``, which
leaves the same state and bit as the canonical measurement and
conditional ``X``.
Global phases are dropped. Adjacent rotations are not merged; run
:func:`merge_rotations` on the result for that.
Args:
borrow: 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: Let decompositions add up to this many clean ancillas,
numbered after the qubits of the circuit and marked with
:class:`AncillaAlloc` and :class:`AncillaFree`. Ancillas freed by
one operation are reused by the next.
allow_measurement: 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, as in :class:`CanonicalBasis`.
Circuits whose width is unknown, such as a lone operation, get no
ancillas.
Examples:
>>> from mimiqcircuits import *
>>> c = Circuit().push(GateCX(), 0, 1)
>>> decompose(c, RXRYCZBasis())
2-qubit circuit with 3 instructions:
├── RY((-1/2)*pi) @ q[1]
├── CZ @ q[0], q[1]
└── RY((1/2)*pi) @ q[1]
<BLANKLINE>
>>> # up to 2 clean ancillas, after the qubits of the circuit
>>> c = Circuit().push(Control(4, GateX()), 0, 1, 2, 3, 4)
>>> d = decompose(c, RXRYCZBasis(max_ancillas=2))
>>> ancillas(d)
[5, 6]
"""
def _axis(self):
from mimiqcircuits.operations.gates.standard.rotations import GateRY
return GateRY
# shortcut: 5 rotations per GateU where an XYX Euler form needs 3; the
# XYX angles are nonlinear in (theta, phi, lmbda), so upgrade with a
# numeric-only path if gate count matters.
# GateU(theta, phi, lmbda) = RZ(phi)·RY(theta)·RZ(lmbda) up to a global
# phase, which is dropped. RZ(a) = RY(-pi/2)·RX(a)·RY(pi/2).
def _decompose_u(self, theta, phi, lmbda, q):
from mimiqcircuits.circuit import Circuit
from mimiqcircuits.decomposition.rules.zyz import _iszero
from mimiqcircuits.operations.gates.standard.rotations import GateRX, GateRY
c = Circuit()
if _iszero(theta) and _iszero(phi + lmbda):
return c
c.push(GateRY(pi / 2), q)
if not _iszero(lmbda):
c.push(GateRX(lmbda), q)
if not _iszero(theta):
c.push(GateRY(theta), q)
if not _iszero(phi):
c.push(GateRX(phi), q)
c.push(GateRY(-pi / 2), q)
return c
# CX = (I⊗V)·CZ·(I⊗V†) with V = RY(pi/2), which maps Z to X.
def _decompose_cx(self, control, target):
from mimiqcircuits.circuit import Circuit
from mimiqcircuits.operations.gates.standard.cpauli import GateCZ
from mimiqcircuits.operations.gates.standard.rotations import GateRY
c = Circuit()
c.push(GateRY(-pi / 2), target)
c.push(GateCZ(), control, target)
c.push(GateRY(pi / 2), target)
return c
__all__ = ["RXRZCZBasis", "RXRYCZBasis"]