Source code for pennylane.transforms.decompose

# Copyright 2018-2024 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.
"""
A transform for decomposing quantum circuits into user defined gate sets. Offers an alternative to the more device-focused decompose transform.
"""

from __future__ import annotations

import warnings
from collections.abc import Callable, Generator, Iterable, Sequence

from pennylane.allocation import Allocate, Deallocate
from pennylane.core import queuing
from pennylane.core.operator import Operator
from pennylane.decomposition import DecompositionGraph, GateSet, gate_sets
from pennylane.decomposition.decomposition_graph import DecompGraphSolution
from pennylane.decomposition.utils import _get_decomp_args
from pennylane.exceptions import DecompositionUndefinedError
from pennylane.ops import Conditional, GlobalPhase
from pennylane.templates import SubroutineOp
from pennylane.transforms.core import transform


def null_postprocessing(results):
    """A postprocessing function returned by a transform that only converts the batch of results
    into a result for a single ``QuantumTape``.
    """
    return results[0]


def _decompose_setup_inputs(
    gate_set: Iterable[type | str] | dict[type | str, float],
    fixed_decomps: dict | None = None,
    exclude_decomps: dict | None = None,
):
    """Validate and pack options for Catalyst's ``graph-decomposition`` pass.

    Wraps a single gate type or name into a set, and includes ``fixed_decomps`` /
    ``exclude_decomps`` in the options dict only when they are provided.

    Args:
        gate_set (Iterable[type | str] | dict[type | str, float]): Target gate set, or a
            single operator type/name that will be wrapped as a one-element set.
        fixed_decomps (dict | None): Optional map from operators to fixed decomposition
            rules. Omitted from the returned options when ``None``.
        exclude_decomps (dict | None): Optional map from operators to decomposition rules
            to exclude. Omitted from the returned options when ``None``.

    Returns:
        tuple[tuple, dict]: positional and keyword arguments forwarded to
        the Catalyst pass under capture.

    """
    if gate_set is None:
        raise TypeError("The gate_set argument is required.")

    if isinstance(gate_set, (type, str)):
        gate_set = {gate_set}

    # Only forward keys the user set. Under capture, Catalyst's from_plxpr handler
    # dispatches these onto ``catalyst.passes.graph_decomposition``.
    options = {"gate_set": gate_set}
    if fixed_decomps is not None:
        options["fixed_decomps"] = fixed_decomps
    if exclude_decomps is not None:
        options["exclude_decomps"] = exclude_decomps
    return (), options


# Public documentation for :func:`~.transforms.decompose` (assigned to ``__doc__`` below so that
# ``_decompose_setup_inputs`` can keep its own docstring).
decompose = transform(pass_name="graph-decomposition", setup_inputs=_decompose_setup_inputs)
decompose.__doc__ = """Decompose a quantum circuit toward a target gate set via Catalyst's graph-decomposition pass.

.. warning::

    This transform must be applied within a workflow compiled with :func:`~.qjit`.
    It is a frontend for Catalyst's ``graph_decomposition`` compilation pass.
    For tape-based (non-compiled) decomposition, use :func:`~.transforms._tape_decompose`.

Args:
    gate_set (Iterable[type | str] | dict[type | str, float]): Target gate set after
        decomposition. A mapping may supply relative costs used by the graph solver.
    fixed_decomps (dict | None): Map operators to specific decomposition rule names to guarantee a
        specific rule is used for each operator.
    exclude_decomps (dict | None): Map operators to lists of decomposition rule names to exclude
        from this pass's graph. Rules are specified by name. Excluded rules remain available
        to subsequent passes.

**Example**

.. code-block:: python

    @qp.qjit(capture=True)
    @qp.decompose(gate_set={"RX", "RY", "RZ", "CNOT", "GlobalPhase"})
    @qp.qnode(qp.device("lightning.qubit", wires=2))
    def circuit():
        qp.Hadamard(0)
        qp.CNOT([0, 1])
        return qp.expval(qp.Z(0))

To exclude a registered rule from this pass, supply its name or callable in
``exclude_decomps``, for example ``exclude_decomps={qp.CRX: ["to_h_crz"]}``.
Use :func:`~pennylane.decomposition.list_decomps` to inspect the available rules.

"""


[docs] @transform def _tape_decompose( # pylint: disable=too-many-arguments tape, *, gate_set: Iterable[type | str] | dict[type | str, float], stopping_condition=None, max_expansion=None, num_work_wires: int | None = 0, minimize_work_wires: bool = False, fixed_decomps: dict | None = None, alt_decomps: dict | None = None, strict: bool = True, ): """Tape-based decomposition of a quantum circuit into a user-specified gate set. This is the Python/tape execution path formerly provided by :func:`~.transforms.decompose`. :func:`~.transforms.decompose` now always dispatches to Catalyst's ``graph-decomposition`` pass under :func:`~.qjit`. .. seealso:: For more information on PennyLane's decomposition tools and features, check out the :doc:`Compiling Circuits page </introduction/compiling_circuits>`. For compiled workflows, use :func:`~.transforms.decompose` with :func:`~.qjit`. Args: tape (QuantumScript or QNode or Callable): A quantum circuit (QNode or quantum function). gate_set (Iterable[str or type], Dict[type or str, float]): The target gate set specified as either (1) a sequence of operator types and/or names, (2) a dictionary mapping operator types and/or names to their respective costs, in which case the total cost will be minimized. Operators in the target gate set are not decomposed. stopping_condition (Callable, optional): a function that returns ``True`` if the operator does not need to be decomposed. If ``None``, the default stopping condition is whether the operator is in the target gate set. See the "Gate Set vs. Stopping Condition" section below for more details. max_expansion (int, optional): The maximum depth of the decomposition. Defaults to ``None``. If ``None``, the circuit will be decomposed until the target gate set is reached. num_work_wires (int): The maximum number of work wires that can be simultaneously allocated. If ``None``, assume an infinite number of work wires. Defaults to ``0``. minimize_work_wires (bool): If ``True``, minimize the number of work wires simultaneously allocated throughout the circuit. Defaults to ``False``. fixed_decomps (Dict[Type[Operator], DecompositionRule or str]): a dictionary mapping operator types to custom decomposition rules. A decomposition rule is a quantum function decorated with :func:`~pennylane.register_resources`. The custom decomposition rules specified here will be used in place of the existing decomposition rules defined for this operator. A string selects a registered rule by its public name, for example ``fixed_decomps={qp.SWAP: "to_cnot"}``. alt_decomps (Dict[Type[Operator], List[DecompositionRule]]): a dictionary mapping operator types to lists of alternative custom decomposition rules. A decomposition rule is a quantum function decorated with :func:`~pennylane.register_resources`. The custom decomposition rules specified here will be considered as alternatives to the existing decomposition rules defined for this operator, and one of them may be chosen if they lead to a more resource-efficient decomposition. strict (bool): If ``False``, operators that do not define a decomposition will be treated as supported. Defaults to ``True`` Returns: qnode (QNode) or quantum function (Callable) or tuple[List[QuantumScript], function]: The decomposed circuit. The output type is explained in :func:`qp.transform <pennylane.transform>`. .. note:: An unsolved graph path can produce a ``DecompositionWarning``. The transform then attempts an existing operator decomposition as a fallback, so the result is not guaranteed to contain only operators in the target gate set. With ``strict=False``, operators without registered decomposition rules are treated as supported by the graph. A ``DecompositionError`` is raised if the graph's minimum work-wire requirement exceeds the available budget. .. seealso:: For decomposing into Clifford + T, check out :func:`~.pennylane.clifford_t_decomposition`. :func:`qp.devices.preprocess.decompose <.pennylane.devices.preprocess.decompose>` is a transform that is intended for device developers. This function will decompose a quantum circuit into a set of basis gates available on a specific device architecture. **Example** Consider the following tape: >>> ops = [qp.IsingXX(1.2, wires=(0,1))] >>> tape = qp.tape.QuantumScript(ops, measurements=[qp.expval(qp.Z(0))]) You can decompose the circuit into a set of gates: >>> batch, fn = qp.transforms._tape_decompose(tape, gate_set={qp.CNOT, qp.RX}) >>> batch[0].circuit [CNOT(wires=[0, 1]), RX(1.2, wires=[0]), CNOT(wires=[0, 1]), expval(Z(0))] You can also apply the transform directly on a :class:`~.pennylane.QNode`: .. code-block:: python @qp.transforms._tape_decompose(gate_set={qp.Toffoli, "RX", "RZ", "GlobalPhase"}) @qp.qnode(qp.device("default.qubit")) def circuit(): qp.Hadamard(wires=[0]) qp.Toffoli(wires=[0,1,2]) return qp.expval(qp.Z(0)) Since the Hadamard gate is not defined in our gate set, it will be decomposed into rotations: >>> print(qp.draw(circuit)()) 0: ──RZ(1.57)──RX(1.57)──RZ(1.57)─╭GlobalPhase(-1.57)─╭●─┤ <Z> 1: ───────────────────────────────├GlobalPhase(-1.57)─├●─┤ 2: ───────────────────────────────╰GlobalPhase(-1.57)─╰X─┤ You can also provide a function as the ``stopping_condition`` in addition to providing a ``gate_set``. In this case the operator decomposition will stop once either it is given in terms of the gates in the ``gate_set`` or the ``stopping_condition`` is satisfied. .. code-block:: python @qp.transforms._tape_decompose( gate_set={"H", "T", "Adjoint(T)", "CNOT", "GlobalPhase"}, stopping_condition=lambda op: len(op.wires) <= 2, ) @qp.qnode(qp.device("default.qubit")) def circuit(): qp.Hadamard(wires=[0]) qp.Toffoli(wires=[0,1,2]) return qp.expval(qp.Z(0)) The circuit will be decomposed into single or two-qubit operators, >>> print(qp.draw(circuit)()) 0: ──H────────╭●───────────╭●────╭●──T──╭●─┤ <Z> 1: ────╭●─────│─────╭●─────│───T─╰X──T†─╰X─┤ 2: ──H─╰X──T†─╰X──T─╰X──T†─╰X──T──H────────┤ You can use the ``max_expansion`` argument to control the number of decomposition stages applied to the circuit. By default, the function will decompose the circuit until the desired gate set is reached. The example below demonstrates how the user can visualize the decomposition in stages: .. code-block:: python from pennylane.decomposition.gate_sets import ROTATIONS_PLUS_CNOT phase = 1 target_wires = [0] unitary = qp.QubitUnitary(qp.RX(phase, wires=0).matrix(), wires=target_wires) n_estimation_wires = 3 estimation_wires = range(1, n_estimation_wires + 1) @qp.qnode(qp.device("default.qubit")) def circuit(): # Start in the |+> eigenstate of the unitary qp.Hadamard(wires=target_wires) qp.QuantumPhaseEstimation(unitary, estimation_wires=estimation_wires) >>> print(qp.draw(qp.transforms._tape_decompose(circuit, gate_set=ROTATIONS_PLUS_CNOT, max_expansion=0))()) 0: ──H─╭QuantumPhaseEstimation─┤ 1: ────├QuantumPhaseEstimation─┤ 2: ────├QuantumPhaseEstimation─┤ 3: ────╰QuantumPhaseEstimation─┤ >>> print(qp.draw(qp.transforms._tape_decompose(circuit, gate_set=ROTATIONS_PLUS_CNOT, max_expansion=1))()) 0: ──RZ(3.14)──RY(1.57)─╭GlobalPhase(-1.57)────╭U(M0)⁴─╭U(M0)²─╭U(M0)¹───────┤ 1: ─────────────────────├GlobalPhase(-1.57)──H─╰●──────│───────│───────╭QFT†─┤ 2: ─────────────────────├GlobalPhase(-1.57)──H─────────╰●──────│───────├QFT†─┤ 3: ─────────────────────╰GlobalPhase(-1.57)──H─────────────────╰●──────╰QFT†─┤ <BLANKLINE> M0 = [[0.87758256+0.j 0. -0.47942554j] [0. -0.47942554j 0.87758256+0.j ]] >>> print(qp.draw(qp.transforms._tape_decompose(circuit, gate_set=ROTATIONS_PLUS_CNOT, max_expansion=2))()) 0: ──RZ(3.14)──RY(1.57)─╭GlobalPhase(-1.57)─────────────────────╭GlobalPhase(-1.57)────────── ··· 1: ─────────────────────├GlobalPhase(-1.57)──RZ(3.14)──RY(1.57)─├GlobalPhase(-1.57)────────── ··· 2: ─────────────────────├GlobalPhase(-1.57)─────────────────────├GlobalPhase(-1.57)──RZ(3.14) ··· 3: ─────────────────────╰GlobalPhase(-1.57)─────────────────────╰GlobalPhase(-1.57)────────── ··· <BLANKLINE> 0: ··· ───────────╭GlobalPhase(-1.57)─────────────────────╭GlobalPhase(-1.57)─╭U(M0)─╭U(M1) ··· 1: ··· ───────────├GlobalPhase(-1.57)─────────────────────├GlobalPhase(-1.57)─╰●─────│───── ··· 2: ··· ──RY(1.57)─├GlobalPhase(-1.57)─────────────────────├GlobalPhase(-1.57)────────╰●──── ··· 3: ··· ───────────╰GlobalPhase(-1.57)──RZ(3.14)──RY(1.57)─╰GlobalPhase(-1.57)────────────── ··· <BLANKLINE> 0: ··· ─╭U(M2)───────────────────────────────────────────────────────────┤ 1: ··· ─│──────╭SWAP†──────────────────────╭(Rϕ(0.79))†─╭(Rϕ(1.57))†──H†─┤ 2: ··· ─│──────│──────────╭(Rϕ(1.57))†──H†─│────────────╰(Rϕ(1.57))†─────┤ 3: ··· ─╰●─────╰SWAP†──H†─╰(Rϕ(1.57))†─────╰(Rϕ(0.79))†──────────────────┤ <BLANKLINE> M0 = [[-0.41614684+0.j 0. -0.90929743j] [ 0. -0.90929743j -0.41614684+0.j ]] M1 = [[0.54030231+0.j 0. -0.84147098j] [0. -0.84147098j 0.54030231+0.j ]] M2 = [[0.87758256+0.j 0. -0.47942554j] [0. -0.47942554j 0.87758256+0.j ]] .. details:: :title: Decomposition Options .. code-block:: python import pennylane as qp with qp.queuing.AnnotatedQueue() as q: qp.CRX(0.5, wires=[0, 1]) tape = qp.tape.QuantumScript.from_queue(q) [new_tape], _ = qp.transforms._tape_decompose([tape], gate_set={"RX", "RY", "RZ", "CZ", "CNOT"}) >>> new_tape.operations [RX(0.25, wires=[1]), CZ(wires=[0, 1]), RX(-0.25, wires=[1]), CZ(wires=[0, 1])] **Weighted Gate Sets** Gate weights can be provided in the ``gate_set`` parameter. For example: .. code-block:: python @qp.transforms._tape_decompose( gate_set={qp.Toffoli: 1.23, qp.RX: 4.56, qp.CZ: 0.01, qp.H: 420, qp.CRZ: 100} ) @qp.qnode(qp.device("default.qubit")) def circuit(): qp.CRX(0.1, wires=[0, 1]) qp.Toffoli(wires=[0, 1, 2]) return qp.expval(qp.Z(0)) >>> print(qp.draw(circuit)()) 0: ───────────╭●────────────╭●─╭●─┤ <Z> 1: ──RX(0.05)─╰Z──RX(-0.05)─╰Z─├●─┤ 2: ────────────────────────────╰X─┤ .. code-block:: python @qp.transforms._tape_decompose( gate_set={qp.Toffoli: 1.23, qp.RX: 4.56, qp.CZ: 0.01, qp.H: 0.1, qp.CRZ: 0.1} ) @qp.qnode(qp.device("default.qubit")) def circuit(): qp.CRX(0.1, wires=[0, 1]) qp.Toffoli(wires=[0, 1, 2]) return qp.expval(qp.Z(0)) >>> print(qp.draw(circuit)()) 0: ────╭●───────────╭●─┤ <Z> 1: ──H─╰RZ(0.10)──H─├●─┤ 2: ─────────────────╰X─┤ Here, when the Hadamard and ``CRZ`` have relatively high weights, a decomposition involving them is considered *less* efficient. When they have relatively low weights, a decomposition involving them is considered *more* efficient. **Gate Set vs. Stopping Condition** The graph-based decomposition system distinguishes between a target gate set and a stopping condition. The ``gate_set`` is a collection of operator types and/or names that is required by the graph-based decomposition solver, which chooses a decomposition rule for each operator that ultimately minimizes the total number of gates in terms of the target gate set (or the total cost if weights are provided). On the other hand, the ``stopping_condition`` is a function that determines whether an operator instance needs to be decomposed. In short, the ``gate_set`` is specified in terms of operator types, whereas the ``stopping_condition`` is specified in terms of operator instances. Here is an example of using ``stopping_condition`` to not decompose a ``qp.QubitUnitary`` instance if it's equivalent to the identity matrix. .. code-block:: python import pennylane as qp # Prepare a unitary matrix that we want to decompose U = qp.matrix(qp.Rot(0.1, 0.2, 0.3, wires=0) @ qp.Identity(wires=1)) def stopping_condition(op): if isinstance(op, qp.QubitUnitary): identity = qp.math.eye(2 ** len(op.wires)) return qp.math.allclose(op.matrix(), identity) return False Note that the ``stopping_condition`` does not need to check whether the operator is in the target gate set. This will always be checked. .. code-block:: python @qp.transforms._tape_decompose( gate_set={qp.RZ, qp.RY, qp.GlobalPhase, qp.CNOT}, stopping_condition=stopping_condition, ) @qp.qnode(qp.device("default.qubit")) def circuit(): qp.QubitUnitary(U, wires=[0, 1]) return qp.expval(qp.PauliZ(0)) >>> print(qp.draw(circuit)()) 0: ──RZ(0.10)──RY(0.20)──RZ(0.30)─┤ <Z> 1: ──U(M0)────────────────────────┤ <BLANKLINE> M0 = [[1.+0.j 0.+0.j] [0.+0.j 1.+0.j]] We can see that the ``QubitUnitary`` on wire 1 is not decomposed due to the stopping condition, despite ``QubitUnitary`` not being in the target gate set. **Customizing Decompositions** This transform accepts custom decomposition rules through the keyword arguments ``fixed_decomps`` and ``alt_decomps``. The user can define custom decomposition rules as quantum functions decorated with ``@qp.register_resources``, and provide them to the transform via these arguments. .. seealso:: :func:`qp.register_resources <pennylane.register_resources>` The ``fixed_decomps`` forces the transform to use the specified decomposition rules for certain operators if they need to be decomposed (i.e., when they're not in the target gate set), whereas the ``alt_decomps`` is used to provide alternative decomposition rules for operators that may be chosen if they lead to a more resource-efficient decomposition. In the following example, ``isingxx_decomp`` will always be used to decompose ``qp.IsingXX`` gates; when it comes to ``qp.CNOT``, the system will choose the most efficient decomposition rule among ``my_cnot1``, ``my_cnot2``, and all existing decomposition rules defined for ``qp.CNOT``. .. code-block:: python import pennylane as qp @qp.register_resources({qp.CNOT: 2, qp.RX: 1}, name="isingxx_decomp") def isingxx_decomp(phi, wires, **__): qp.CNOT(wires=wires) qp.RX(phi, wires=[wires[0]]) qp.CNOT(wires=wires) @qp.register_resources({qp.H: 2, qp.CZ: 1}, name="my_cnot1") def my_cnot1(wires, **__): qp.H(wires=wires[1]) qp.CZ(wires=wires) qp.H(wires=wires[1]) @qp.register_resources({qp.RY: 2, qp.CZ: 1, qp.Z: 2}, name="my_cnot2") def my_cnot2(wires, **__): qp.RY(np.pi/2, wires[1]) qp.Z(wires[1]) qp.CZ(wires=wires) qp.RY(np.pi/2, wires[1]) qp.Z(wires[1]) @qp.transforms._tape_decompose( gate_set={"RX", "RZ", "CZ", "GlobalPhase"}, alt_decomps={qp.CNOT: [my_cnot1, my_cnot2]}, fixed_decomps={qp.IsingXX: isingxx_decomp}, ) @qp.qnode(qp.device("lightning.qubit", wires=2)) def circuit(): qp.CNOT(wires=[0, 1]) qp.IsingXX(0.5, wires=[0, 1]) return qp.state() >>> qp.specs(qp.qjit(circuit, capture=False))().resources.quantum_operations {'GlobalPhase': 6, 'CZ': 3, 'RX': 7, 'RZ': 12} **Degenerate Graph Solutions** There could be cases that arise where the decomposition graph solution is non-deterministic if there are intermediate gate decompositions that have the same overall costs. This is not normally an issue, except for in cases where graph decompositions are being used with ``qjit`` and intermediate gates include operations that are non-executable by Catalyst. An example of such a gate is the ``PauliRot`` operation. If an intermediate decomposition is chosen that includes a ``qp.PauliRot`` instance, Catalyst cannot execute the program. If this behaviour is encountered, this can be counteracted by adding a prohibitively large penalty to the graph solution should it encounter a ``qp.PauliRot`` instance (e.g., ``qp.transforms._tape_decompose(..., gate_set={..., qp.PauliRot: 100_000})``). """ if gate_set is None: raise TypeError("The gate_set argument is required.") gate_set, stopping_condition = _resolve_gate_set(gate_set, stopping_condition) if all(stopping_condition(op) for op in tape.operations): return (tape,), null_postprocessing unsupported_ops = [op for op in tape.operations if not stopping_condition(op)] decomp_graph_solution = _construct_and_solve_decomp_graph( unsupported_ops, gate_set, num_work_wires=num_work_wires, minimize_work_wires=minimize_work_wires, fixed_decomps=fixed_decomps, alt_decomps=alt_decomps, strict=strict, ) num_work_wires = decomp_graph_solution.num_work_wires try: new_ops = [ final_op for op in tape.operations for final_op in _operator_decomposition_gen( op, stopping_condition, max_expansion=max_expansion, num_work_wires=num_work_wires, graph_solution=decomp_graph_solution, ) ] except RecursionError as e: raise RecursionError( "Reached recursion limit trying to decompose operations. Operator decomposition may " "have entered an infinite loop. Setting max_expansion will terminate the decomposition " "at a fixed recursion depth." ) from e tape = tape.copy(operations=new_ops) return (tape,), null_postprocessing
def _operator_decomposition_gen( # pylint: disable=too-many-arguments,too-many-branches op: Operator, acceptance_function: Callable[[Operator], bool], max_expansion: int | None = None, current_depth: int = 0, num_work_wires: int | None = 0, graph_solution: DecompGraphSolution | None = None, custom_decomposer: Callable[[Operator], Sequence[Operator]] | None = None, strict: bool = False, ) -> Generator[Operator]: """A generator that yields the next operation that is accepted. Args: op: The operator to decompose acceptance_function: Returns True if the operator does not need further decomposition. max_expansion: The maximum level of expansion. current_depth: The current depth of expansion. num_work_wires: The number of available work wires at the top level. graph_solution: The solution to the decomposition graph. custom_decomposer: A custom function that decomposes an operator, used by ``preprocess.decompose``. strict: If True, an error will be raised when an operator does not provide a decomposition and does not meet the stopping criteria. Returns: A generator of Operators """ # NOTE: Prevents operators in the decomposition from getting queued if # we're in an active queuing context with queuing.QueuingManager.stop_recording(): max_depth_reached = False decomp = [] if max_expansion is not None and max_expansion <= current_depth: max_depth_reached = True if isinstance(op, (Allocate, Deallocate)): yield op elif isinstance(op, Conditional): if acceptance_function(op.base) or max_depth_reached: yield op else: yield from ( Conditional(op.meas_val, base_op) for base_op in _operator_decomposition_gen( op.base, acceptance_function, max_expansion=max_expansion, current_depth=current_depth, graph_solution=graph_solution, custom_decomposer=custom_decomposer, strict=strict, ) ) elif acceptance_function(op) or max_depth_reached: yield op elif isinstance(op, SubroutineOp): decomp = op.decomposition() elif graph_solution and graph_solution.is_solved_for(op, num_work_wires): op_rule = graph_solution.decomposition(op, num_work_wires) params, args, kwargs = _get_decomp_args(op) with queuing.AnnotatedQueue() as decomposed_ops: op_rule(*args, **kwargs) decomp = decomposed_ops.queue if num_work_wires is not None: num_work_wires -= op_rule.get_work_wire_spec(**params).total elif custom_decomposer is not None: try: decomp = custom_decomposer(op) except DecompositionUndefinedError as e: raise DecompositionUndefinedError( f"Operator {op} not supported and does not provide a decomposition." ) from e elif isinstance(op, GlobalPhase): warnings.warn( "GlobalPhase is not assumed to have a decomposition. " "To disable this warning, add GlobalPhase to the gate set, or " "assign a decomposition rule to GlobalPhase via the fixed_decomps keyword " "argument. To make GlobalPhase decompose to nothing, you can import null_decomp " "from pennylane.decomposition, and assign it to GlobalPhase." ) yield op elif op.has_decomposition: decomp = op.decomposition() elif strict: raise DecompositionUndefinedError( f"Operator {op} not supported and does not provide a decomposition." ) else: yield op current_depth += 1 for sub_op in decomp: yield from _operator_decomposition_gen( sub_op, acceptance_function, max_expansion=max_expansion, current_depth=current_depth, num_work_wires=num_work_wires, graph_solution=graph_solution, custom_decomposer=custom_decomposer, strict=strict, ) def _process_gate_set(gate_set) -> tuple[GateSet, Callable]: """Return a GateSet and a callable that returns True iff an operator is in the gate set.""" if gate_set is None: raise TypeError("The gate_set argument is required.") gate_set = gate_set or {} if isinstance(gate_set, Iterable): gate_set = GateSet(gate_set) return gate_set, lambda op: op in gate_set raise TypeError("Invalid gate_set type. Must be an iterable, dictionary, or function.") def _resolve_gate_set( gate_set: Iterable[type | str] | dict[type | str, float] | None = None, stopping_condition: Callable[[Operator], bool] | None = None, ) -> tuple[GateSet, Callable[[Operator], bool]]: """Resolve the gate set and the stopping condition from arguments. The ``gate_set`` can be provided in various forms, and the ``stopping_condition`` may or may not be provided. This function will resolve the gate set and the stopping condition to the following standardized form: - The ``gate_set`` is set of operator **types** and/or names, a dictionary mapping operator types and/or names to their respective costs. This is only used by the DecompositionGraph. - The ``stopping_condition`` is a function that takes an operator **instances** and returns ``True`` if the operator does not need to be decomposed. This is used during decomposition. """ # This is a special case when the decompose transform is called without a gate set or # a stopping condition. In this case, we assume all PennyLane operations are supported, # i.e., we only decompose templates and custom gates defined by the user. if gate_set is None and stopping_condition is None: gate_set = gate_sets.ALL_OPS return gate_set, lambda op: op.name in gate_set if isinstance(gate_set, (type, str)): # when a single gate is provided as the gate set gate_set = {gate_set} gate_set, gate_set_contains = _process_gate_set(gate_set) if stopping_condition: # Even when the user provides a stopping condition, we still need to check # whether an operator belongs to the target gate set. This is to prevent # the case of an operator missing the stopping condition but doesn't have # a decomposition assigned due to being in the target gate set. def _stopping_condition(op): return gate_set_contains(op) or stopping_condition(op) else: # If the stopping condition is not explicitly provided, the default is to simply check # whether an operator belongs to the target gate set. _stopping_condition = gate_set_contains return gate_set, _stopping_condition def _construct_and_solve_decomp_graph( # pylint: disable=too-many-arguments operations, target_gates, num_work_wires, minimize_work_wires, fixed_decomps, alt_decomps, strict, ): """Create and solve a DecompositionGraph instance to optimize the decomposition.""" # Create the decomposition graph graph = DecompositionGraph( operations, target_gates, fixed_decomps=fixed_decomps, alt_decomps=alt_decomps, strict=strict, ) # Find the efficient pathways to the target gate set return graph.solve(num_work_wires=num_work_wires, minimize_work_wires=minimize_work_wires)