Source code for pennylane.transforms.decompositions.crz_phase_gradient

# Copyright 2026 Xanadu Quantum Technologies Inc.

# 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.
r"""
Factory that produces a decomposition rule for CRZ in terms of
`phase gradient states <https://pennylane.ai/compilation/phase-gradient/c-control-rotations>`__
"""

import numpy as np

import pennylane as qp
from pennylane.ops.op_math import ChangeOpBasis2
from pennylane.ops.subcircuit import subcircuit
from pennylane.typing import Bool, Wire

from .rz_phase_gradient import _precision_dispatcher, validate_phase_gradient_wires


def _crz_phase_gradient_compute_resources(bitstrings, wires, angle_wires, phase_grad_wires):
    """Resources for loading a controlled angle and flipping the phase-gradient register."""
    angle_fanout = qp.ctrl(qp.MultiX(bitstrings, angle_wires), control=wires[:1])
    phase_fanout = qp.ctrl(
        qp.MultiX(Bool[len(phase_grad_wires)], phase_grad_wires), control=wires[1:]
    )
    resources = {angle_fanout: 1}
    resources[phase_fanout] = resources.get(phase_fanout, 0) + 1
    return resources


@subcircuit(
    dynamic_argnames=("bitstrings",),
    wire_argnames=("wires", "angle_wires", "phase_grad_wires"),
    arg_specs={
        "bitstrings": Bool[-1],
        "wires": Wire[2],
        "angle_wires": Wire[-1],
        "phase_grad_wires": Wire[-1],
    },
    grad_method=None,
)
@qp.register_resources(_crz_phase_gradient_compute_resources)
def _CRZPhaseGradientCompute(bitstrings, wires, angle_wires, phase_grad_wires) -> None:
    """Load a controlled angle and flip phase-gradient wires when the target is zero."""
    qp.ctrl(qp.MultiX(bitstrings, angle_wires), control=wires[0])
    qp.ctrl(
        qp.MultiX([1] * len(phase_grad_wires), phase_grad_wires),
        control=wires[1],
        control_values=[0],
    )


def _crz_phase_gradient(phi, wires, angle_wires, phase_grad_wires, work_wires):
    """Apply the phase gradient circuit for CRZ. The precision is implicitly defined by the
    length of ``angle_wires``."""
    binary_int = qp.math.cast(qp.math.binary_decimals(phi, len(angle_wires), unit=4 * np.pi), bool)
    compute_op = _CRZPhaseGradientCompute(binary_int, wires, angle_wires, phase_grad_wires)
    target_op = qp.SemiAdder(angle_wires, phase_grad_wires, work_wires=work_wires)
    qp.change_op_basis(compute_op, target_op, compute_op)


[docs] def make_crz_to_phase_gradient_decomp( angle_wires, phase_grad_wires, work_wires, precision_stats=None ): r""" Create a custom decomposition rule for :class:`~.CRZ` gates. Here, the necessary auxiliary wires for the `phase gradient decomposition of CRZ <https://pennylane.ai/compilation/phase-gradient/c-control-rotations>`__ are taken as inputs and bound into the created decomposition rule. This way, this function can be used in a workflow context that explicitly uses those wires to generate this decomposition rule, which can then be registered with :func:`~pennylane.decomposition.add_decomps`. Parameters: angle_wires (Wires): wires that encode the binary representation of the rotation angle phase_grad_wires (Wires): wires that carry a phase gradient state. Should have the same length as ``angle_wires``. work_wires (Wires): additional work wires for :class:`~.SemiAdder` decomposition. At least ``len(angle_wires)-1`` work wires are required. precision_stats (dict[int, int] | None): Optional statistics of the number of bits required by the rotation angles. Defaults to ``None``. Returns: func: decomposition rule to be used within :func:`~.pennylane.decompose`. .. seealso:: :func:`~.make_rz_to_phase_gradient_decomp`, :func:`~.make_selectpaulirot_to_phase_gradient_decomp` **Example** In this example we decompose a circuit containing only a single :class:`~.CRZ` gate using the custom decomposition rule that we generate from within the context of the example, where all auxiliary wires exist. .. code-block:: python import pennylane as qp from pennylane.transforms.decompositions import make_crz_to_phase_gradient_decomp import numpy as np prec = 3 phi = (1/2 + 1/4 + 1/8) * 4 * np.pi # binary rep is (111) angle_wires = qp.wires.Wires([f"aux_{i}" for i in range(prec)]) phase_grad_wires = qp.wires.Wires([f"phg_{i}" for i in range(prec)]) work_wires = qp.wires.Wires([f"work_{i}" for i in range(prec - 1)]) custom_decomp = make_crz_to_phase_gradient_decomp( angle_wires, phase_grad_wires, work_wires ) @qp.transforms._tape_decompose( gate_set={"CNOT", "SemiAdder", "PauliX"}, fixed_decomps={qp.CRZ: custom_decomp} ) @qp.qnode(qp.device("null.qubit")) def circuit(): qp.CRZ(phi, [0, 1]) return qp.state() The resulting circuit corresponds to the phase gradient decomposition of ``CRZ``. The compute and uncompute fanouts load the binary representation of the angle (111 in this case) onto the ``angle_wires`` with a :class:`~.MultiX` controlled by the control wire (rendering as ``CNOT``, since the control is always on |1>), and flip all of the ``phase_grad_wires`` with a single :class:`~.MultiX` controlled by the target wire on |0> (rendering as a ``PauliX`` flip of that control wire, ``CNOT``\\ s to the ``phase_grad_wires``, and a ``PauliX`` flip back), and enclose the :class:`~.SemiAdder`. >>> wire_order = [0, 1] + angle_wires + phase_grad_wires + work_wires >>> print(qp.draw(circuit, wire_order=wire_order)()) 0: ─╭●─╭●─╭●────────────────────────╭●─╭●─╭●────────────────┤ ╭State 1: ─│──│──│───X─╭●─╭●─╭●──X─────────│──│──│───X─╭●─╭●─╭●──X─┤ ├State aux_0: ─╰X─│──│─────│──│──│──╭SemiAdder─╰X─│──│─────│──│──│─────┤ ├State aux_1: ────╰X─│─────│──│──│──├SemiAdder────╰X─│─────│──│──│─────┤ ├State aux_2: ───────╰X────│──│──│──├SemiAdder───────╰X────│──│──│─────┤ ├State phg_0: ─────────────╰X─│──│──├SemiAdder─────────────╰X─│──│─────┤ ├State phg_1: ────────────────╰X─│──├SemiAdder────────────────╰X─│─────┤ ├State phg_2: ───────────────────╰X─├SemiAdder───────────────────╰X────┤ ├State work_0: ──────────────────────├SemiAdder─────────────────────────┤ ├State work_1: ──────────────────────╰SemiAdder─────────────────────────┤ ╰State .. details:: :title: Usage details **Adaptive precision via ``precision_stats``** For angles that do not require the full precision determined by the angle encoding and phase gradient wires, we may use smaller fanouts and adder, reducing the cost of the phase gradient rotation. However, as rotation angles are not known statically in general, this adaptive precision is only supported if additional information about the distribution of rotation angles is provided via ``precision_stats``, a dictionary mapping a number of bits to the number of rotations requiring that many bits. The bits required by an angle :math:`\phi` are the position of the last set bit in ``qp.math.binary_decimals(phi, len(angle_wires), unit=4 * np.pi)``, i.e., the precision without trailing zeros. If provided, the fanouts and the :class:`~.SemiAdder` are truncated to the smallest number of bits in ``precision_stats`` that suffices for a given angle, using :func:`~.cond` branches that are hinted with the corresponding probabilities via :func:`~.hint`. If no number of bits in ``precision_stats`` suffices, the full precision is used. Keys must lie between ``0`` and ``len(angle_wires)``. Zero counts are ignored, and a dictionary without non-zero counts is treated like ``None``. Use :func:`~.phase_gradient_precision_stats` to compute the statistics from the angles. **Example** .. code-block:: python from pennylane.transforms.decompositions import phase_gradient_precision_stats angles = np.array([1/4, 1/2 + 1/8]) * 4 * np.pi # (010) and (101) precision_stats = phase_gradient_precision_stats(angles, prec, qp.CRZ) truncating_decomp = make_crz_to_phase_gradient_decomp( angle_wires, phase_grad_wires, work_wires, precision_stats=precision_stats ) @qp.transforms._tape_decompose( gate_set={"CNOT", "SemiAdder", "PauliX"}, fixed_decomps={qp.CRZ: truncating_decomp} ) @qp.qnode(qp.device("null.qubit")) def truncated_circuit(phi): qp.CRZ(phi, [0, 1]) return qp.state() The rotation by the first angle only uses two angle wires and phase gradient wires: >>> precision_stats {2: 1, 3: 1} >>> print(qp.draw(truncated_circuit, wire_order=wire_order)(angles[0])) 0: ─╭●─────────────────────╭●─────────────┤ ╭State 1: ─│───X─╭●─╭●──X─────────│───X─╭●─╭●──X─┤ ├State aux_0: ─│─────│──│──╭SemiAdder─│─────│──│─────┤ ├State aux_1: ─╰X────│──│──├SemiAdder─╰X────│──│─────┤ ├State phg_0: ───────╰X─│──├SemiAdder───────╰X─│─────┤ ├State phg_1: ──────────╰X─├SemiAdder──────────╰X────┤ ├State work_0: ─────────────├SemiAdder────────────────┤ ├State work_1: ─────────────╰SemiAdder────────────────┤ ╰State Finally, keep the following in mind when using ``precision_stats``: * The resource function of the rule adds up the cost of all supported precisions, so that the graph-based decomposition system accounts for the operators in all conditional branches. This over-reports the cost of the rule, so that the decomposition graph may prefer another rule over this one when it is registered with :func:`~pennylane.decomposition.add_decomps`. Use ``fixed_decomps`` to enforce this rule. * Angles that require more bits than the largest key in ``precision_stats`` fall back to the full precision. Unless ``len(angle_wires)`` is a key in ``precision_stats``, this fallback branch is hinted with probability ``0``, so that resource estimates based on the hints do not account for these angles. """ angle_wires, phase_grad_wires, work_wires = validate_phase_gradient_wires( angle_wires, phase_grad_wires, work_wires ) precisions, dispatch = _precision_dispatcher(precision_stats, len(angle_wires), "CRZ") def _crz_phase_gradient_standard_resources(phi, wires): # pylint: disable=unused-argument # Cost from the wires in the outer scope, counting each non-zero precision that may be # applied once. The angle-load fanout emits one gate per *set* bit of the (concrete) angle, # so this is an upper bound (exact=False below). resources = {} for p in precisions - {0}: target_op = qp.SemiAdder(Wire[p], Wire[p], Wire[len(work_wires)]) compute_op = _CRZPhaseGradientCompute(Bool[p], Wire[2], Wire[p], Wire[p]) resources[ChangeOpBasis2(compute_op, target_op, compute_op)] = 1 return resources @qp.register_resources( _crz_phase_gradient_standard_resources, exact=False, name="phase_gradient" ) def _crz_phase_gradient_standard(phi, wires): dispatch( phi, lambda p: _crz_phase_gradient( phi, wires, angle_wires[:p], phase_grad_wires[:p], work_wires ), ) return _crz_phase_gradient_standard