# Copyright 2025 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.
"""Defines the data structure that stores resource estimates for each decomposition."""
from __future__ import annotations
from collections.abc import Set
from dataclasses import dataclass, field
from functools import cached_property
import pennylane as qp
from pennylane.core.operator import Operator, Operator2, abstractify
from .utils import to_name
[docs]
class CompressedResourceOp:
"""A lightweight representation of an operator to be decomposed.
The ``CompressedResourceOp`` is a lightweight data structure that contains an operator type
and a set of parameters that affects the resource requirement of this operator. If the
decomposition of an operator is independent of its parameters, e.g., ``Rot`` can be decomposed
into two ``RZ`` gates and an ``RY`` regardless of the angles, then every occurrence of this
operator in the circuit is represented by the same ``CompressedResourceOp`` which only
specifies the operator type, i.e., ``Rot``.
On the other hand, for some operators such as ``MultiRZ``, for which the number of ``CNOT``
gates in its decomposition depends on the number of wires, the resource representation of
a ``MultiRZ`` must include this information. To create a ``CompressedResourceOp`` object for
an operator, use the :func:`~pennylane.resource_rep` function.
Args:
op_type: the operator type
params (dict): the parameters of the operator relevant to the resource estimation of
its decompositions. This should only include parameters that affect the gate counts.
.. seealso:: :func:`~pennylane.resource_rep`
"""
def __init__(self, op_type: type[Operator], params: dict | None = None):
if not isinstance(op_type, type):
raise TypeError(f"op_type must be an Operator type, got {type(op_type)}")
if not issubclass(op_type, qp.operation.Operator):
raise TypeError(f"op_type must be a subclass of Operator, got {op_type}")
self.op_type = op_type
self.params = params or {}
self._hashable_params = _make_hashable(params) if params else ()
@property
def name(self) -> str:
"""The name of the operator type."""
if issubclass(self.op_type, (qp.ops.Adjoint, qp.ops.Pow)):
base_rep = resource_rep(self.params["base_class"], **self.params["base_params"])
return f"{self.op_type.__name__}({base_rep.name})"
if self.op_type in (qp.ops.Controlled, qp.ops.ControlledOp):
base_rep = resource_rep(self.params["base_class"], **self.params["base_params"])
return f"C({base_rep.name})"
return self.op_type.__name__
def __hash__(self) -> int:
return hash((self.op_type, self._hashable_params))
def __eq__(self, other) -> bool:
return (
isinstance(other, CompressedResourceOp)
and self.op_type == other.op_type
and self._hashable_params == other._hashable_params
)
def __repr__(self):
if issubclass(self.op_type, qp.ops.Adjoint):
base_rep = resource_rep(self.params["base_class"], **self.params["base_params"])
return f"Adjoint({repr(base_rep)})"
if issubclass(self.op_type, qp.ops.Pow):
base_rep = resource_rep(self.params["base_class"], **self.params["base_params"])
return f"Pow({repr(base_rep)}, z={self.params['z']})"
if self.op_type in (qp.ops.Controlled, qp.ops.ControlledOp):
params = self.params.copy()
base_rep = resource_rep(params.pop("base_class"), **params.pop("base_params"))
param_str = ", " + ", ".join(f"{k}={v}" for k, v in sorted(params.items()))
return f"Controlled({repr(base_rep)}{param_str})"
params = ", ".join(f"{k}={v}" for k, v in sorted(self.params.items()))
return f"{self.op_type.__name__}({params})" if self.params else self.op_type.__name__
AbstractOperatorLike = CompressedResourceOp | Operator2
@abstractify.register(CompressedResourceOp)
def _abstractify_resource_rep(op_rep: CompressedResourceOp):
return op_rep
[docs]
@dataclass(frozen=False)
class Resources:
r"""Stores resource estimates.
Args:
gate_counts (dict): dictionary mapping operator types to their number of occurrences.
weighted_cost (float): the cumulative weight of the gates.
"""
gate_counts: dict[AbstractOperatorLike, int] = field(default_factory=dict)
weighted_cost: float = field(default=None)
def __post_init__(self):
"""Verify that all gate counts are non-zero."""
assert all(v > 0 for v in self.gate_counts.values())
if self.weighted_cost is None:
self.weighted_cost = sum(count for _, count in self.gate_counts.items())
assert self.weighted_cost >= 0.0
@cached_property
def num_gates(self) -> int:
"""The total number of gates."""
return sum(self.gate_counts.values())
def __add__(self, other: Resources):
return Resources(
_combine_dict(self.gate_counts, other.gate_counts),
weighted_cost=self.weighted_cost + other.weighted_cost,
)
def __mul__(self, scalar: int):
return Resources(
_scale_dict(self.gate_counts, scalar), weighted_cost=self.weighted_cost * scalar
)
__rmul__ = __mul__
def __repr__(self):
gate_counts = _gate_count_dict_to_str(self.gate_counts)
return f"<num_gates={self.num_gates}, gate_counts={gate_counts}, weighted_cost={self.weighted_cost}>"
def _combine_dict(dict1: dict, dict2: dict):
r"""Combines two dictionaries and adds values of common keys."""
combined_dict = dict1.copy()
for k, v in dict2.items():
combined_dict[k] = combined_dict.get(k, 0) + v
return combined_dict
def _gate_count_dict_to_str(gate_counts):
str_op = ((str(op), count) for op, count in gate_counts.items())
inner = ", ".join(f"{op}: {count}" for op, count in sorted(str_op))
return f"{{{inner}}}"
def _scale_dict(dict1: dict, scalar: int):
r"""Scales the values in a dictionary with a scalar."""
return {key: scalar * value for key, value in dict1.items()}
def _make_hashable(d):
if isinstance(d, dict):
return tuple(
sorted(
((_make_hashable(k), _make_hashable(v)) for k, v in d.items()),
key=lambda x: repr(x[0]),
)
)
if isinstance(d, CompressedResourceOp):
# Since the params are guaranteed to be hashable, we can use them here
return (d.op_type.__name__, d._hashable_params) # pylint: disable=protected-access
if isinstance(d, type):
return d.__name__
if hasattr(d, "tolist"):
d = d.tolist()
if isinstance(d, list):
return tuple(_make_hashable(v) for v in d)
return d
def _validate_resource_rep(op_type, params):
"""Validates the resource representation of an operator."""
if not issubclass(op_type, qp.operation.Operator):
raise TypeError(f"op_type must be a type of Operator, got {op_type}")
if not isinstance(op_type.resource_keys, Set):
raise TypeError(
f"{op_type.__name__}.resource_keys must be a set, not a {type(op_type.resource_keys)}"
)
unexpected_arguments = set(params.keys()) - op_type.resource_keys
if unexpected_arguments:
raise TypeError(
f"Unexpected keyword arguments for resource_rep({op_type.__name__}): "
f"{list(unexpected_arguments)}). Expected: {list(op_type.resource_keys)}"
)
missing_arguments = op_type.resource_keys - set(params.keys())
if missing_arguments:
raise TypeError(
f"Missing keyword arguments for resource_rep({op_type.__name__}): "
f"{list(missing_arguments)}. Expected: {list(op_type.resource_keys)}"
)
[docs]
def resource_rep(op_type: type[Operator], **params) -> CompressedResourceOp:
"""Binds an operator type with additional resource parameters.
Args:
op_type: the operator class to create a resource representation for.
**params: parameters relevant to the resource estimate of the operator's decompositions.
This should be consistent with ``op_type.resource_keys``.
Returns:
pennylane.decomposition.resources.CompressedResourceOp: a lightweight representation of the operator.
.. seealso:: :func:`~pennylane.decomposition.controlled_resource_rep`, :func:`~pennylane.decomposition.adjoint_resource_rep`, :func:`~pennylane.decomposition.pow_resource_rep`
"""
_validate_resource_rep(op_type, params)
if issubclass(op_type, qp.ops.Adjoint):
return adjoint_resource_rep(**params)
if issubclass(op_type, qp.ops.Pow):
return pow_resource_rep(**params)
if op_type is qp.ops.ControlledOp:
op_type = qp.ops.Controlled
if op_type is qp.ops.Controlled:
base_rep = resource_rep(params["base_class"], **params["base_params"])
params["base_class"] = base_rep.op_type
params["base_params"] = base_rep.params
return CompressedResourceOp(op_type, params)
[docs]
def controlled_resource_rep( # pylint: disable=too-many-arguments
base_class: type[Operator],
base_params: dict,
num_control_wires: int,
num_zero_control_values: int = 0,
num_work_wires: int = 0,
work_wire_type="borrowed",
):
"""Creates a ``CompressedResourceOp`` representation of a controlled operator.
This function mirrors ``qp.ctrl``, including flattening nested controlled operations.
Args:
base_class: the base operator type
base_params (dict): the resource params of the base operator
num_control_wires (int): the number of control wires
num_zero_control_values (int): the number of control values that are 0
num_work_wires (int): the number of work wires
work_wire_type (str): the type of work wire
"""
_validate_resource_rep(base_class, base_params)
# Flattens nested controlled structures.
if base_class in (qp.ops.Controlled, qp.ops.ControlledOp):
num_control_wires += base_params["num_control_wires"]
num_zero_control_values += base_params["num_zero_control_values"]
num_work_wires += base_params["num_work_wires"]
return controlled_resource_rep(
base_class=base_params["base_class"],
base_params=base_params["base_params"],
num_control_wires=num_control_wires,
num_zero_control_values=num_zero_control_values,
num_work_wires=num_work_wires,
work_wire_type=work_wire_type,
)
return CompressedResourceOp(
qp.ops.Controlled,
{
"base_class": base_class,
"base_params": base_params,
"num_control_wires": num_control_wires,
"num_zero_control_values": num_zero_control_values,
"num_work_wires": num_work_wires,
"work_wire_type": work_wire_type,
},
)
[docs]
def adjoint_resource_rep(base_class: type[Operator], base_params: dict | None = None):
"""Creates a ``CompressedResourceOp`` representation of the adjoint of an operator.
Args:
base_class: the base operator type
base_params (dict): the resource params of the base operator
"""
base_params = base_params or {}
base_resource_rep = resource_rep(base_class, **base_params) # flattens any nested structures
return CompressedResourceOp(
qp.ops.Adjoint,
{"base_class": base_resource_rep.op_type, "base_params": base_resource_rep.params},
)
[docs]
def change_op_basis_resource_rep(
compute_op: type[Operator] | CompressedResourceOp,
target_op: type[Operator] | CompressedResourceOp,
uncompute_op: type[Operator] | CompressedResourceOp | None = None,
):
"""Creates a ``CompressedResourceOp`` representation of the compute-uncompute pattern
:class:`~.ChangeOpBasis` of operators.
Args:
compute_op: the compressed resource representation of the compute operator
target_op: the compressed resource representation of target operator
uncompute_op: the compressed resource representation of the uncompute operator
"""
# pylint: disable-next=import-outside-toplevel
from pennylane.ops.op_math.adjoint2 import _adjoint_abstract
compute_op = abstractify(compute_op)
target_op = abstractify(target_op)
uncompute_op = uncompute_op or _adjoint_abstract(compute_op)
uncompute_op = abstractify(uncompute_op)
return CompressedResourceOp(
qp.ops.ChangeOpBasis,
{
"compute_op": compute_op,
"target_op": target_op,
"uncompute_op": uncompute_op,
},
)
[docs]
def pow_resource_rep(base_class, base_params, z):
"""Creates a ``CompressedResourceOp`` representation of the power of an operator.
Args:
base_class: the base operator type
base_params (dict): the resource params of the base operator
z (int or float): the power
"""
base_resource_rep = resource_rep(base_class, **base_params)
return CompressedResourceOp(
qp.ops.Pow,
{"base_class": base_resource_rep.op_type, "base_params": base_resource_rep.params, "z": z},
)
def resolve_work_wire_type(base_work_wires, base_work_wire_type, work_wires, work_wire_type):
"""Resolves the overall work wire type when the base op comes with work wires.
A side with no work wires has no opinion, so its ``work_wire_type`` is ignored. If any
side that does have work wires is "borrowed", the merged result is "borrowed" (we can be
more flexible in the future with dynamic qubit management, but for now we're just going
to live with this).
"""
def _exists(wire_arg):
return wire_arg is not None and len(wire_arg) > 0
if _exists(base_work_wires) and base_work_wire_type == "borrowed":
return "borrowed"
if _exists(work_wires) and work_wire_type == "borrowed":
return "borrowed"
if not _exists(base_work_wires):
return work_wire_type
if not _exists(work_wires):
return base_work_wire_type
return "zeroed"
@to_name.register
def _compressed_op_to_name(op: CompressedResourceOp):
return to_name(op.name)