# Copyright 2018-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.
"""
Stores classes and logic to aggregate all the resource information from a quantum workflow.
"""
from __future__ import annotations
from collections import defaultdict
from collections.abc import Generator
from dataclasses import asdict, dataclass, field, fields
from decimal import Decimal
from functools import lru_cache
from string import ascii_lowercase
from typing import Any
from pennylane.core.measurements import MeasurementProcess
from pennylane.core.qscript import QuantumScript
from pennylane.core.shots import Shots
from pennylane.ops.op_math import Controlled, ControlledOp
from pennylane.pytrees import flatten, unflatten
from .expression import Expression
from .extension import _RESOURCE_EXTENSIONS
# The threshold after which integers in the resource class are displayed in scientific notation.
# This is used in the __str__ and _repr_markdown_ methods of the Resources class.
_SCIENTIFIC_NOTATION_THRESHOLD = 100_000
def _count_to_str(
count: int | float | Expression, extra_compact: bool = False, markdown_safe: bool = False
) -> str:
"""
Helper for printing counts, converts large counts to scientific notation and standardizes printing of expressions.
Args:
count (int | float | Expression): the count to convert to a string
extra_compact (bool): whether to remove spaces from expressions for compactness
markdown_safe (bool): whether to escape asterisks for markdown tables
"""
if isinstance(count, Expression):
if count.vars:
retval = str(count)
if markdown_safe:
retval = retval.replace("*", "\\*") # Escape asterisks for markdown tables
if extra_compact:
retval = retval.replace(" ", "") # Remove spaces from expressions for compactness
return retval
count = float(count)
if isinstance(count, float) and not count.is_integer():
# NOTE: stringify the count in order to bypass Decimal precision issues
return f"{Decimal(str(count)):.3E}"
if count >= _SCIENTIFIC_NOTATION_THRESHOLD:
return f"{Decimal(count):.3E}"
return f"{int(count):,}" # Return as integer if count is small
def _flatten_dict(data: dict, prefix: str = "", sep: str = ".") -> dict:
"""Recursively flatten a (possibly nested) dictionary into a single-level dictionary.
Nested dictionaries are collapsed into dotted keys of arbitrary depth. Only nested
``dict`` values are recursed into; all other value types are left untouched.
Args:
data (dict): The dictionary to flatten.
prefix (str): The key prefix to prepend to each key (used internally for recursion).
sep (str): The separator to use when joining nested keys.
Returns:
dict: A flattened dictionary mapping dotted keys to their (non-dict) values.
**Example**
>>> _flatten_dict({"a": 1, "b": {"c": 2, "d": {"e": 3}}})
{'a': 1, 'b.c': 2, 'b.d.e': 3}
"""
flattened = {}
for key, value in data.items():
full_key = f"{prefix}{sep}{key}" if prefix else str(key)
if isinstance(value, dict):
flattened.update(_flatten_dict(value, prefix=full_key, sep=sep))
else:
flattened[full_key] = value
return flattened
def _extra_resource_rows(resources):
"""Align registered display rows across resource columns, retaining group headings."""
groups = {}
def add_rows(values, column, rows):
for label, value in values.items():
is_group = isinstance(value, dict)
_, entries = rows.setdefault(label, (is_group, {}))
if is_group:
add_rows(value, column, entries)
else:
entries[column] = value
def flatten_rows(rows):
for label, (is_group, entries) in rows.items():
yield label, None if is_group else entries
if is_group:
yield from flatten_rows(entries)
for column, resource in resources.items():
for name, data in resource.extra.items():
if handler := _RESOURCE_EXTENSIONS.get(name):
add_rows({handler.display_name: data}, column, groups.setdefault(name, {}))
return [row for rows in groups.values() for row in flatten_rows(rows)]
def _format_extra_value(value, *, extra_compact=False, markdown_safe=False):
"""Format extension counts with the standard formatter and preserve other values as text."""
if isinstance(value, (int, float, Expression)):
return _count_to_str(value, extra_compact=extra_compact, markdown_safe=markdown_safe)
return str(value)
def _collect_vars(obj: Any) -> Generator[str]:
"""Collect the symbolic variables of every :class:`~.resource.Expression` within an arbitrary pytree.
Uses :func:`~pennylane.pytrees.flatten` to traverse any registered container type (``dict``,
``list``, ``tuple``, ...) to arbitrary depth, yielding the variables of every :class:`~.resource.Expression`
leaf. Non-``Expression`` leaves are ignored.
Args:
obj (Any): The (possibly nested) object to search.
Yields:
str: Each symbolic variable found across every :class:`~.resource.Expression` leaf.
"""
leaves, _ = flatten(obj)
for leaf_val in leaves:
if isinstance(leaf_val, Expression):
yield from leaf_val.vars
def _subs_pytree(obj: Any, substitutions: dict) -> Any:
"""Substitute symbolic variables within every :class:`~.resource.Expression` leaf of an arbitrary pytree.
Uses :func:`~pennylane.pytrees.flatten`/:func:`~pennylane.pytrees.unflatten` to traverse any
registered container type (``dict``, ``list``, ``tuple``, ...) to arbitrary depth, substituting
into every :class:`~.resource.Expression` leaf while preserving the original structure. Non-``Expression``
leaves are left untouched.
Args:
obj (Any): The (possibly nested) object to substitute into.
substitutions (dict): A mapping from variable names to their concrete values.
Returns:
Any: A new object of the same structure with substitutions applied.
"""
leaves, struct = flatten(obj)
new_leaves = (
leaf_val.subs(substitutions) if isinstance(leaf_val, Expression) else leaf_val
for leaf_val in leaves
)
return unflatten(new_leaves, struct)
@lru_cache
def num_to_letters(num: int) -> str:
"""Helper for assigning labels to numbered data, such as batches for circuit resources.
Converts 0 to 'a', 1 to 'b', etc.
Example:
>>> num_to_letters(0)
'a'
>>> num_to_letters(25)
'z'
>>> num_to_letters(26)
'aa'
>>> num_to_letters(27)
'ab'
"""
if num < 26:
return ascii_lowercase[num]
return num_to_letters(num // 26 - 1) + ascii_lowercase[num % 26]
[docs]
@dataclass(frozen=True, slots=True, kw_only=True)
class Resources:
"""
Base class for storing resource information.
.. warning::
This class is intended to be immutable. Modifying the attributes after creation may lead to
unexpected behaviour.
Args:
counts (dict[str, int]): A dictionary mapping resources to their counts.
extra (dict[int, int]): A dictionary for storing any extra fields that need to be tracked.
.. details::
:title: Symbolic Resource Information
Attributes in this class can be of type :class:`~.resource.Expression`, allowing for symbolic
manipulation and substitution of variables. When variables of type :class:`~.resource.Expression` are
present as top-level fields or as values within (possibly nested) dictionaries of arbitrary
depth, the :attr:`vars` attribute will contain the set of all symbolic variables used in the
resource counts. This includes fields introduced in derived classes. Similarly, the
:meth:`subs` method can be used to substitute symbolic variables with concrete values.
"""
counts: dict
extra: dict = field(repr=False, default_factory=dict)
vars: frozenset[str] = field(
init=False,
repr=False,
default_factory=frozenset,
metadata={"display_name": "Symbolic variables"},
)
def __post_init__(self):
all_vars = set()
# Iterate over all fields of the dataclass to find any Expression instances and collect
# their variables. Each field value is treated as a pytree, so Expressions nested to any
# depth within dicts/lists/tuples are found automatically.
for obj_field in fields(self):
if obj_field.name == "vars":
continue
all_vars.update(_collect_vars(getattr(self, obj_field.name)))
object.__setattr__(self, "vars", frozenset(all_vars))
[docs]
def to_pretty_str(self, preindent: int = 0) -> str:
"""Convert a :class:`~.resource.Resources` object into a human-readable string representation.
Automatically iterates over all fields of the dataclass and formats them into a string,
including any nested dictionaries.
.. note::
This method does not have to be implemented by derived classes, but may be overridden
if a different formatting is desired.
Args:
preindent (int, optional): The number of spaces to insert before each line. Defaults to 0.
Returns:
str: A human-readable string representation of this object.
"""
prefix = " " * preindent
lines = []
if self.is_symbolic:
lines.append(f"{prefix}Symbolic variables: {', '.join(sorted(self.vars))}")
for obj_field in fields(self):
if obj_field.repr is False:
# Skip fields that are not meant to be included in the representation
continue
field_name = obj_field.metadata.get("display_name", obj_field.name)
if isinstance(getattr(self, obj_field.name), dict):
lines.append(f"{prefix}{field_name}:")
# Flatten nested dictionaries into dotted keys of arbitrary depth
dict_items = _flatten_dict(getattr(self, obj_field.name))
for k, v in dict_items.items():
value_str = (
_count_to_str(v) if isinstance(v, (int, float, Expression)) else str(v)
)
lines.append(f"{prefix}- {k}: {value_str}")
if len(dict_items) == 0:
lines.append(f"{prefix}- None present.")
else:
value = getattr(self, obj_field.name)
value_str = (
_count_to_str(value)
if isinstance(value, (int, float, Expression))
else str(value)
)
lines.append(f"{prefix}{field_name}: {value_str}")
if self.extra:
lines.append(f"{prefix}Extra fields:")
for k, v in _flatten_dict(self.extra).items():
value_str = _count_to_str(v) if isinstance(v, (int, float, Expression)) else str(v)
lines.append(f"{prefix}- {k}: {value_str}")
return "\n".join(lines)
def __str__(self):
"""Convert this object to its string representation by calling :meth:`to_pretty_str`.
Automatically iterates over all fields of the dataclass and formats them into a string,
including any nested dictionaries.
Returns:
str: A human-readable string representation of this object.
"""
return self.to_pretty_str()
def _repr_markdown_(self) -> str:
"""
Return a Markdown table representation of this object for Jupyter notebook display.
.. seealso::
https://ipython.readthedocs.io/en/stable/config/integrating.html#custom-methods
"""
lines = []
lines.append("| **Metric** | **Value** |")
lines.append("| :--- | ---: |")
for obj_field in fields(self):
if obj_field.repr is False:
# Skip fields that are not meant to be included in the representation
continue
field_name = obj_field.metadata.get("display_name", obj_field.name)
if isinstance(getattr(self, obj_field.name), dict):
lines.append(f"| **{field_name}** | |")
# Flatten nested dictionaries into dotted keys of arbitrary depth
dict_items = _flatten_dict(getattr(self, obj_field.name))
for k, v in dict_items.items():
value_str = (
_count_to_str(v) if isinstance(v, (int, float, Expression)) else str(v)
)
lines.append(f"| {k} | {value_str} |")
if len(dict_items) == 0:
lines.append("| *None present* | |")
else:
value = getattr(self, obj_field.name)
value_str = (
_count_to_str(value)
if isinstance(value, (int, float, Expression))
else str(value)
)
lines.append(f"| **{field_name}** | {value_str} |")
if self.extra:
lines.append("| **Extra Fields** | |")
for k, v in _flatten_dict(self.extra).items():
value_str = _count_to_str(v) if isinstance(v, (int, float, Expression)) else str(v)
lines.append(f"| {k} | {value_str} |")
return "\n".join(lines)
def __getitem__(self, key):
if key in (obj_field.name for obj_field in fields(self)):
return getattr(self, key)
raise KeyError(
f"key '{key}' not available. Options are {[obj_field.name for obj_field in fields(self)]}"
)
[docs]
def subs(self, substitutions: dict[str, int | float] | None = None, **kwargs) -> Resources:
"""
Substitute symbolic variables in the object with concrete values.
Automatically iterates over all fields of the dataclass and applies substitutions to any
Expression instances, so derived classes do not have to explicitly implement this method
unless they want to customize the behaviour.
.. note::
Every :class:`~.resource.Expression` leaf is substituted, including those nested to arbitrary
depth within registered pytree containers (``dict``, ``list``, ``tuple``, ...). The
original container structure is preserved.
Args:
substitutions (dict[str, int | float] | None): A dictionary mapping variable names to their values.
If None, an empty dictionary is used. Additional keyword arguments can also be provided.
.. details::
**Example**
>>> from pennylane.resource import SpecsResources, Expression
>>> res = SpecsResources(
... counts={"CNOT": Expression({("x",): 1})},
... measurement_processes={"expval(PauliX)": 1},
... num_wires=2,
... circuit_depth=1,
... )
Calling this method will return a new instance of the same type which has the same
structure but with the symbolic variables substituted with the provided values.
A substitution may either use a dictionary or keyword arguments:
>>> res.subs({"x": 3})
SpecsResources(counts={'CNOT': 3}, measurement_processes={'expval(PauliX)': 1}, num_wires=2, circuit_depth=1, total_quantum_operations=3)
>>> res.subs(x=3)
SpecsResources(counts={'CNOT': 3}, measurement_processes={'expval(PauliX)': 1}, num_wires=2, circuit_depth=1, total_quantum_operations=3)
"""
if substitutions is None:
substitutions = {}
# NOTE: don't mutate incoming dict
substitutions_copy = {**substitutions, **kwargs}
subs_vars = set(substitutions_copy.keys())
if extra_vars := subs_vars - self.vars:
raise ValueError(
f"Substitutions contain variables {extra_vars} which are not in the expression's variables {self.vars}."
)
new_values = {}
for obj_field in fields(self):
if obj_field.init is False:
continue
# Each field value is treated as a pytree, so Expressions nested to any depth within
# dicts/lists/tuples are substituted automatically while preserving the structure.
new_values[obj_field.name] = _subs_pytree(
getattr(self, obj_field.name), substitutions_copy
)
return type(self)(**new_values)
@property
def is_symbolic(self) -> bool:
"""Returns True if this object contains any symbolic variables, False otherwise."""
return bool(self.vars)
[docs]
@dataclass(frozen=True, slots=True, kw_only=True)
class SpecsResources(Resources):
"""
Class for storing resource information for a quantum circuit. Contains attributes which store
key resources such as gate counts, total wires, measurement processes, and
circuit depth.
Note that this class is intended to be immutable. Modifying the attributes after creation may
lead to unexpected behaviour.
Args:
counts (dict[str, int]): A dictionary mapping gate names to their counts.
measurement_processes (dict[str, int]): A dictionary mapping measurement processes to their counts.
num_wires (int): The number of unique wires. For circuits that do not use
dynamic wires, this should be equal to the number of device wires.
circuit_depth (int | None): The depth of the circuit, or None if not computed. Defaults to ``None``.
.. seealso::
:class:`~.resource.Resources` for the base class and its fields.
.. warning::
This class is intended to be immutable. Modifying the attributes after creation may
lead to unexpected behaviour.
.. details::
Methods have been provided to allow pretty-printing, as well as
indexing into the object as a dictionary. See examples below.
**Example**
>>> from pennylane.resource import SpecsResources
>>> res = SpecsResources(
... counts={'Hadamard': 1, 'CNOT': 1},
... measurement_processes={'expval(PauliZ)': 1},
... num_wires=2,
... circuit_depth=2
... )
>>> print(res.total_quantum_operations)
2
>>> print(res["total_quantum_operations"])
2
>>> print(res)
Quantum operations:
- Total: 2
- Hadamard: 1
- CNOT: 1
Measurement processes:
- expval(PauliZ): 1
Total wires: 2
Circuit Depth: 2
"""
measurement_processes: dict[str, int | Expression] = field(
metadata={"display_name": "Measurement processes"}
)
num_wires: int | Expression = field(metadata={"display_name": "Total wires"})
circuit_depth: int | Expression | None = field(
default=None, metadata={"display_name": "Circuit depth"}
)
# Automatically generated
total_quantum_operations: int | Expression = field(
init=False, metadata={"display_name": "Total quantum operations"}
)
def __post_init__(self):
# Sum over flattened leaf values so nested operation dicts are counted correctly
object.__setattr__(
self,
"total_quantum_operations",
sum(_flatten_dict(self.quantum_operations).values()),
)
# NOTE: Have to use explicit class arguments in super calls due to a bug with slots in
# dataclasses in Python 3.12 and earlier (https://github.com/python/cpython/issues/90562)
# pylint: disable-next=super-with-arguments
super(SpecsResources, self).__post_init__() # Fall through to parent post init
def __getitem__(self, key):
# Need to match
match key:
# Properties need to be handled manually unlike true fields
case "quantum_operations":
return self.quantum_operations
case "depth":
return self.depth
# NOTE: Have to use explicit class arguments in super calls due to a bug with slots in
# dataclasses in Python 3.12 and earlier (https://github.com/python/cpython/issues/90562)
return super(SpecsResources, self).__getitem__(key) # pylint: disable=super-with-arguments
@property
def quantum_operations(self):
"""A dictionary mapping quantum operations to their counts (alias for ``counts``)."""
return self.counts
@property
def depth(self):
"""The circuit depth (alias for ``circuit_depth``)."""
return self.circuit_depth
[docs]
def to_pretty_str(self, preindent: int = 0) -> str:
"""
Pretty string representation of this :class:`~.resource.SpecsResources` object.
Args:
preindent (int): Number of spaces to prepend to each line.
Returns:
str: A pretty representation of this object.
"""
prefix = " " * preindent
lines = []
if self.is_symbolic:
lines.append(f"{prefix}Symbolic Variables: {', '.join(sorted(self.vars))}")
lines.append(f"{prefix}Quantum operations:")
if not self.quantum_operations:
lines.append(prefix + "- No operations.")
else:
lines.append(f"{prefix}- Total: {_count_to_str(self.total_quantum_operations)}")
for gate, count in _flatten_dict(self.quantum_operations).items():
lines.append(f"{prefix} - {gate}: {_count_to_str(count)}")
lines.append(f"{prefix}Measurement processes:")
if not self.measurement_processes:
lines.append(prefix + "- No measurement processes.")
else:
for meas, count in _flatten_dict(self.measurement_processes).items():
lines.append(f"{prefix}- {meas}: {_count_to_str(count)}")
lines.append(f"{prefix}Total wires: {_count_to_str(self.num_wires)}")
# pylint: disable-next=unidiomatic-typecheck
if self.circuit_depth is not None or type(self) == SpecsResources:
# Do not include circuit depth in the output for derived classes
depth_str = (
_count_to_str(self.circuit_depth)
if self.circuit_depth is not None
else "Not computed"
)
lines.append(f"{prefix}Circuit Depth: {depth_str}")
for label, values in _extra_resource_rows({0: self}):
if values is None:
lines.append(f"{prefix}{label}:")
else:
value_str = (
_format_extra_value(values[0]) if values[0] is not None else "Not computed"
)
lines.append(f"{prefix}- {label}: {value_str}")
return "\n".join(lines)
def _repr_markdown_(self) -> str:
"""
Return a Markdown table representation of the :class:`~.resource.SpecsResources` for Jupyter notebook display.
.. seealso::
https://ipython.readthedocs.io/en/stable/config/integrating.html#custom-methods
"""
lines = []
lines.append("| **Metric** | **Value** |")
lines.append("| :--- | ---: |")
lines.append("| **Quantum operations:** | |")
if not self.quantum_operations:
lines.append("| *No operations* | |")
else:
lines.append(
f"| *Total* | {_count_to_str(self.total_quantum_operations, markdown_safe=True)} |"
)
for gate, count in _flatten_dict(self.quantum_operations).items():
lines.append(f"| {gate} | {_count_to_str(count, markdown_safe=True)} |")
lines.append("| **Measurement processes:** | |")
if not self.measurement_processes:
lines.append("| *No measurement processes* | |")
else:
for meas, count in _flatten_dict(self.measurement_processes).items():
lines.append(f"| {meas} | {_count_to_str(count, markdown_safe=True)} |")
lines.append(f"| **Total wires** | {_count_to_str(self.num_wires, markdown_safe=True)} |")
# pylint: disable-next=unidiomatic-typecheck
if self.circuit_depth is not None or type(self) == SpecsResources:
# Do not include circuit depth in the output for derived classes
depth_str = (
_count_to_str(self.depth, markdown_safe=True)
if self.depth is not None
else "Not computed"
)
lines.append(f"| **Circuit depth** | {depth_str} |")
for label, values in _extra_resource_rows({0: self}):
if values is None:
lines.append(f"| **{label}** | |")
else:
value_str = (
_format_extra_value(values[0], markdown_safe=True)
if values[0] is not None
else "Not computed"
)
lines.append(f"| {label} | {value_str} |")
return "\n".join(lines)
[docs]
def to_dict(self) -> dict[str, Any]:
"""Convert this :class:`~.resource.SpecsResources` to a dictionary."""
# Need to explicitly include properties
d = asdict(self)
d["total_quantum_operations"] = self.total_quantum_operations
d["num_wires"] = self.num_wires
d["quantum_operations"] = d["counts"]
del d["counts"]
return d
[docs]
@dataclass(frozen=True, slots=True, kw_only=True)
class PBCSpecsResources(SpecsResources):
"""
Class for storing resource information for a quantum circuit with additional
PBC (Pauli-Based Computation) information.
.. seealso::
:class:`~.resource.SpecsResources` for the base class and its fields.
.. warning::
This class is intended to be immutable. Modifying the attributes after creation may
lead to unexpected behaviour.
Args:
any_commuting_depth (int | Expression | None): The any commuting depth of the circuit.
qubit_disjoint_depth (int | Expression | None): The qubit disjoint depth of the circuit.
"""
any_commuting_depth: int | Expression = field(metadata={"display_name": "Any commuting depth"})
qubit_disjoint_depth: int | Expression = field(
metadata={"display_name": "Qubit disjoint depth"}
)
[docs]
def to_pretty_str(self, preindent: int = 0) -> str:
"""
Pretty string representation of this :class:`~.resource.PBCSpecsResources` object.
Args:
preindent (int): Number of spaces to prepend to each line.
Returns:
str: A pretty representation of this object.
"""
# NOTE: Have to use explicit class arguments in super calls due to a bug with slots in
# dataclasses in Python 3.12 and earlier (https://github.com/python/cpython/issues/90562)
# pylint: disable-next=super-with-arguments
s = super(PBCSpecsResources, self).to_pretty_str(preindent=preindent)
s += (
"\nPBC Depths:\n"
f"{' ' * preindent}- Any commuting depth: {_count_to_str(self.any_commuting_depth)}\n"
f"{' ' * preindent}- Qubit disjoint depth: {_count_to_str(self.qubit_disjoint_depth)}"
)
return s
def _repr_markdown_(self) -> str:
"""
Return a Markdown table representation of the :class:`~.resource.PBCSpecsResources` for Jupyter notebook display.
.. seealso::
https://ipython.readthedocs.io/en/stable/config/integrating.html#custom-methods
"""
# NOTE: Have to use explicit class arguments in super calls due to a bug with slots in
# dataclasses in Python 3.12 and earlier (https://github.com/python/cpython/issues/90562)
s = super(PBCSpecsResources, self)._repr_markdown_() # pylint: disable=super-with-arguments
s += (
"\n"
"| **PBC Depths** | |\n"
f"| Any commuting depth | {_count_to_str(self.any_commuting_depth, markdown_safe=True)} |\n"
f"| Qubit disjoint depth | {_count_to_str(self.qubit_disjoint_depth, markdown_safe=True)} |"
)
return s
[docs]
@dataclass(frozen=True)
class CircuitSpecs:
"""
Class for storing specifications of a qnode. Contains resource information as well as additional
data such as the device, number of shots, and level of the requested specs.
Args:
device_name (str): The name of the device used.
num_device_wires (int): The number of wires on the device.
shots (Shots): The shots configuration used.
level (Any): The level of the specs (see :func:`~pennylane.specs` for more details).
resources (SpecsResources | list[SpecsResources] | \
dict[int | str, SpecsResources | list[SpecsResources]]): The resource specifications.
Depending on the ``level`` chosen, this may be a single :class:`~.resource.SpecsResources` object,
a list of :class:`~.resource.SpecsResources` objects, or a dictionary mapping levels to their
corresponding outputs.
.. details::
Some helpful methods have been added to this data class to allow pretty-printing, as well as
indexing into it as a dictionary. See examples below.
**Example**
>>> from pennylane.resource import SpecsResources, CircuitSpecs
>>> specs = CircuitSpecs(
... device_name="default.qubit",
... num_device_wires=2,
... shots=Shots(1000),
... level="device",
... resources=SpecsResources(
... counts={"RX": 2, "CNOT": 1},
... measurement_processes={"expval(PauliZ)": 1},
... num_wires=2,
... circuit_depth=3,
... ),
... )
>>> print(specs.num_device_wires)
2
>>> print(specs["num_device_wires"])
2
>>> print(specs)
Device: default.qubit
Device wires: 2
Shots: Shots(total=1000)
Level: device
<BLANKLINE>
Quantum operations:
- Total: 3
- RX: 2
- CNOT: 1
Measurement processes:
- expval(PauliZ): 1
Total wires: 2
Circuit Depth: 3
"""
device_name: str | None = None
num_device_wires: int | None = None
shots: Shots | None = None
level: Any = None
resources: (
SpecsResources
| list[SpecsResources]
| dict[int | str, SpecsResources | list[SpecsResources]]
| None
) = None
[docs]
def to_dict(self) -> dict[str, Any]:
"""Convert the CircuitSpecs to a dictionary."""
d = asdict(self)
# Replace Resources objects with their dict representations
if isinstance(self.resources, SpecsResources):
d["resources"] = self.resources.to_dict()
elif isinstance(self.resources, list):
d["resources"] = [r.to_dict() for r in self.resources]
elif isinstance(self.resources, dict):
d["resources"] = {
k: (v.to_dict() if isinstance(v, SpecsResources) else [r.to_dict() for r in v])
for k, v in self.resources.items()
}
return d
def __getitem__(self, key):
if key in (obj_field.name for obj_field in fields(self)):
return getattr(self, key)
raise KeyError(
f"key '{key}' not available. Options are {[obj_field.name for obj_field in fields(self)]}"
)
def _get_specs_header(self) -> list[str]:
"""Helper for main ``to_pretty_str`` method, gathers the header information about the specs such as device and level."""
lines = []
lines.append(f"Device: {self.device_name}")
lines.append(f"Device wires: {self.num_device_wires}")
lines.append(f"Shots: {self.shots}")
if isinstance(self.level, dict):
lines.append("Levels:")
for level, level_name in self.level.items():
lines.append(f"- {level}: {level_name}")
else:
lines.append(f"Level: {self.level}")
lines.append("") # Blank line
return lines
def _resources_to_str(self, res, preindent=0) -> str:
"""Helper for printing resources, prints list or single SpecsResources."""
lines = []
if isinstance(res, SpecsResources):
lines.append(res.to_pretty_str(preindent))
elif isinstance(res, list):
prefix = preindent * " "
for i, r in enumerate(res):
lines.append(f"{prefix}Batched qnode {num_to_letters(i)}:")
lines.append(r.to_pretty_str(preindent=preindent + 4))
lines.append("") # Blank line
else:
raise ValueError(
"Resources must be either a SpecsResources object or a list of SpecsResources objects."
) # pragma: no cover
return "\n".join(lines)
def _flattened_resources(self) -> dict[str, SpecsResources]:
"""Helper for printing tabular format, flattens all resources across levels into a single
dictionary with string keys."""
flat_resources = {}
for level, res in zip(self.level.keys(), self.resources.values(), strict=True):
if isinstance(res, SpecsResources):
flat_resources[str(level)] = res
elif isinstance(res, list):
for i, r in enumerate(res):
flat_resources[f"{level}-{num_to_letters(i)}"] = r
else:
raise ValueError(
"Resources must be either a SpecsResources object or a list of SpecsResources objects."
) # pragma: no cover
return flat_resources
def _get_table_format(
self, flat_resources: dict[str, SpecsResources]
) -> tuple[int, int, dict[str, None], dict[str, None]]:
"""Helper for printing tabular format, determines column widths and all gate and measurement
types across levels."""
# This is the length of the longest metric name (currently "Measurement processes") plus padding
max_metric_length = 22
max_column_size = max(len(level) for level in flat_resources) + 2
# Use dict for these since they are sorted by default unlike a set
all_quantum_operations = {}
all_meas_types = {}
# This iteration order will present the gates in the order in which they appear
for res in flat_resources.values():
# Flatten nested operation/measurement dicts into dotted keys of arbitrary depth
for gate, count in _flatten_dict(res.quantum_operations).items():
all_quantum_operations[gate] = True
# Gate rows are indented by 2 extra spaces (e.g. " - {gate}")
max_metric_length = max(max_metric_length, len(gate) + 4)
max_column_size = max(
max_column_size, len(_count_to_str(count, extra_compact=True)) + 1
)
for meas, count in _flatten_dict(res.measurement_processes).items():
all_meas_types[meas] = True
max_metric_length = max(max_metric_length, len(meas) + 2)
max_column_size = max(
max_column_size, len(_count_to_str(count, extra_compact=True)) + 1
)
max_column_size = max(
max_column_size,
len(_count_to_str(res.num_wires, extra_compact=True)) + 1,
len(_count_to_str(res.total_quantum_operations, extra_compact=True)) + 1,
)
for label, values in _extra_resource_rows(flat_resources):
max_metric_length = max(max_metric_length, len(label) + 2)
if values is not None:
for value in values.values():
if value is not None:
max_column_size = max(
max_column_size,
len(_format_extra_value(value, extra_compact=True)) + 1,
)
return max_metric_length, max_column_size, all_quantum_operations, all_meas_types
def _to_pretty_str_tabular(self) -> str:
"""Helper for main ``to_pretty_str`` for tabular format, which is more compact when there
are many levels to display."""
lines = self._get_specs_header()
flat_resources = self._flattened_resources()
max_metric_length, max_column_size, all_quantum_operations, all_meas_types = (
self._get_table_format(flat_resources)
)
num_cols = len(flat_resources)
lines.append(
"↓Metric".ljust(max_metric_length - 6)
+ "Level→"
+ " |"
+ " |".join(level.rjust(max_column_size) for level in flat_resources)
)
lines.append("-" * (max_metric_length + num_cols * (max_column_size + 2)))
lines.append("Quantum operations:".ljust(max_metric_length) + " |")
lines.append(
"- Total".ljust(max_metric_length)
+ " |"
+ " |".join(
_count_to_str(res.total_quantum_operations, extra_compact=True).rjust(
max_column_size
)
for res in flat_resources.values()
)
)
for gate in all_quantum_operations:
lines.append(
f" - {gate}".ljust(max_metric_length)
+ " |"
+ " |".join(
_count_to_str(
_flatten_dict(res.quantum_operations).get(gate, 0), extra_compact=True
).rjust(max_column_size)
for res in flat_resources.values()
)
)
lines.append("Measurement processes:".ljust(max_metric_length) + " |")
for meas in all_meas_types:
lines.append(
f"- {meas}".ljust(max_metric_length)
+ " |"
+ " |".join(
_count_to_str(
_flatten_dict(res.measurement_processes).get(meas, 0), extra_compact=True
).rjust(max_column_size)
for res in flat_resources.values()
)
)
lines.append(
"Total wires".ljust(max_metric_length)
+ " |"
+ " |".join(
_count_to_str(res.num_wires, extra_compact=True).rjust(max_column_size)
for res in flat_resources.values()
)
)
if any(r.circuit_depth is not None for r in flat_resources.values()):
lines.append(
"Circuit depth".ljust(max_metric_length)
+ " |"
+ " |".join(
(
_count_to_str(res.circuit_depth, extra_compact=True).rjust(max_column_size)
if res.circuit_depth is not None
else "-".rjust(max_column_size)
)
for res in flat_resources.values()
)
)
if any(isinstance(r, PBCSpecsResources) for r in flat_resources.values()):
lines.append("PBC Depths:".ljust(max_metric_length) + " |")
lines.append(
"- Any commuting depth".ljust(max_metric_length)
+ " |"
+ " |".join(
(
_count_to_str(r.any_commuting_depth, extra_compact=True)
if isinstance(r, PBCSpecsResources)
else "-"
).rjust(max_column_size)
for r in flat_resources.values()
)
)
lines.append(
"- Qubit disjoint depth".ljust(max_metric_length)
+ " |"
+ " |".join(
(
_count_to_str(r.qubit_disjoint_depth, extra_compact=True)
if isinstance(r, PBCSpecsResources)
else "-"
).rjust(max_column_size)
for r in flat_resources.values()
)
)
for label, values in _extra_resource_rows(flat_resources):
if values is None:
lines.append(f"{label}:".ljust(max_metric_length) + " |")
else:
lines.append(
f"- {label}".ljust(max_metric_length)
+ " |"
+ " |".join(
(
_format_extra_value(values[column], extra_compact=True)
if values.get(column) is not None
else "-"
).rjust(max_column_size)
for column in flat_resources
)
)
return "\n".join(lines).rstrip("\n")
[docs]
def to_pretty_str(self, tabular: bool = True) -> str:
"""
Pretty string representation of the :class:`~.resource.CircuitSpecs` object.
Args:
tabular (bool): Whether to display the resources in a tabular format.
Returns:
str: A pretty representation of this object.
"""
if tabular and isinstance(self.resources, dict):
return self._to_pretty_str_tabular()
lines = self._get_specs_header()
if isinstance(self.resources, dict):
lines.append("") # Blank line before levels
for level, res in self.resources.items():
lines.append(f"Level = {level}:")
lines.append(self._resources_to_str(res, preindent=4))
lines.append("\n" + "-" * 60 + "\n") # Separator between levels
else:
lines.append(self._resources_to_str(self.resources))
return "\n".join(lines).rstrip("\n-")
# Separate str and repr methods for simple and pretty printing
def __str__(self) -> str:
return self.to_pretty_str()
def _to_markdown_tabular(self) -> str:
"""Return a Markdown table for dict-type resources."""
flat_resources = self._flattened_resources()
levels = list(flat_resources.keys())
all_quantum_operations: dict[str, None] = {}
all_meas_types: dict[str, None] = {}
for res in flat_resources.values():
# Flatten nested operation/measurement dicts into dotted keys of arbitrary depth
for gate in _flatten_dict(res.quantum_operations):
all_quantum_operations[gate] = None
for meas in _flatten_dict(res.measurement_processes):
all_meas_types[meas] = None
def data_row(label, values):
return f"| {label} | " + " | ".join(str(v) for v in values) + " |"
lines = []
lines.append("| ↓Metric / Level→ | " + " | ".join(str(lvl) for lvl in levels) + " |")
lines.append("| :--- |" + " ---: |" * len(levels))
lines.append(data_row("**Quantum operations**", [""] * len(levels)))
lines.append(
data_row(
"*Total*",
[
_count_to_str(r.total_quantum_operations, markdown_safe=True)
for r in flat_resources.values()
],
)
)
for gate in all_quantum_operations:
lines.append(
data_row(
gate,
[
_count_to_str(
_flatten_dict(r.quantum_operations).get(gate, 0), markdown_safe=True
)
for r in flat_resources.values()
],
)
)
lines.append(data_row("**Measurement processes**", [""] * len(levels)))
for meas in all_meas_types:
lines.append(
data_row(
meas,
[
_count_to_str(
_flatten_dict(r.measurement_processes).get(meas, 0), markdown_safe=True
)
for r in flat_resources.values()
],
)
)
lines.append(
data_row(
"**Total wires**",
[_count_to_str(r.num_wires, markdown_safe=True) for r in flat_resources.values()],
)
)
if any(r.circuit_depth is not None for r in flat_resources.values()):
lines.append(
data_row(
"**Circuit depth**",
[
(
_count_to_str(res.circuit_depth, markdown_safe=True)
if res.circuit_depth is not None
else "N/A"
)
for res in flat_resources.values()
],
)
)
if any(isinstance(r, PBCSpecsResources) for r in flat_resources.values()):
lines.append(data_row("**PBC Depths**", [""] * len(levels)))
lines.append(
data_row(
"Any commuting depth",
[
(
_count_to_str(r.any_commuting_depth, markdown_safe=True)
if isinstance(r, PBCSpecsResources)
else "N/A"
)
for r in flat_resources.values()
],
)
)
lines.append(
data_row(
"Qubit disjoint depth",
[
(
_count_to_str(r.qubit_disjoint_depth, markdown_safe=True)
if isinstance(r, PBCSpecsResources)
else "N/A"
)
for r in flat_resources.values()
],
)
)
for label, values in _extra_resource_rows(flat_resources):
lines.append(
data_row(f"**{label}**", [""] * len(levels))
if values is None
else data_row(
label,
[
(
_format_extra_value(values[column], markdown_safe=True)
if values.get(column) is not None
else "N/A"
)
for column in levels
],
)
)
return "\n".join(lines)
def _repr_markdown_(self, collapsible: bool = True) -> str: # pylint: disable=too-many-branches
"""
Return a Markdown representation of the :class:`~.resource.CircuitSpecs` for Jupyter notebook display.
Args:
collapsible (bool): Whether to display the resources in collapsible sections.
Returns:
str: A Markdown representation of this object for Jupyter notebooks.
.. seealso::
https://ipython.readthedocs.io/en/stable/config/integrating.html#custom-methods
"""
# Ignore pylint on this one, this is not better served by splitting into even
# smaller functions than it already has
lines = []
if collapsible:
lines.append("<details open>")
lines.append("<summary>Circuit Specs</summary>")
else:
lines.append("**Circuit Specs:**")
lines.append("")
lines.append("| Metric | Value |")
lines.append("| :--- | ---: |")
lines.append(f"| **Device** | {self.device_name} |")
lines.append(f"| **Device wires** | {self.num_device_wires} |")
lines.append(f"| **Shots** | {self.shots} |")
if isinstance(self.level, dict):
lines.append("| **Levels** | |")
for k, v in self.level.items():
lines.append(f"| {k} | {v} |")
else:
lines.append(f"| **Level** | {self.level} |")
lines.append("")
if collapsible:
lines.append("</details>")
lines.append("<details open>")
lines.append("<summary>Resources</summary>")
else:
lines.append("**Resources:**")
lines.append("")
if isinstance(self.resources, SpecsResources):
lines.append(self.resources._repr_markdown_()) # pylint: disable=protected-access
elif isinstance(self.resources, list):
for i, r in enumerate(self.resources):
if collapsible:
lines.append("<details open>")
lines.append(f"<summary>Batched qnode {num_to_letters(i)}</summary>")
else:
lines.append(f"**Batched qnode {num_to_letters(i)}:**")
lines.append("")
lines.append(r._repr_markdown_()) # pylint: disable=protected-access
lines.append("")
if collapsible:
lines.append("</details>")
elif isinstance(self.resources, dict):
lines.append(self._to_markdown_tabular())
if collapsible:
lines.append("")
lines.append("</details>")
return "\n".join(lines)
# TODO: Everything below this line can be removed once tape-based functionality is removed.
[docs]
def resources_from_tape(tape: QuantumScript, compute_depth: bool = True) -> SpecsResources:
"""
Extracts the resource information from a quantum circuit (tape).
The depth of the circuit is computed by default, but can be set to None
by setting the `compute_depth` argument to False.
This is useful when the depth is not needed, for example, in some
resource counting scenarios or heavy circuits where computing depth is expensive.
Args:
tape (.QuantumScript): The quantum circuit for which we extract resources
compute_depth (bool): If True, the depth of the circuit is computed and included in the resources.
If False, the depth is set to None.
Returns:
SpecsResources: The resources associated with this tape.
**Example**
.. code-block:: python
import pennylane as qp
from pennylane.resource import resources_from_tape
dev = qp.device("default.qubit", wires=2)
@qp.qnode(dev)
def circuit(theta):
qp.RX(theta, wires=0)
qp.CNOT(wires=[0, 1])
return qp.expval(qp.PauliZ(0))
tape = qp.workflow.construct_tape(circuit)(3)
resources = resources_from_tape(tape)
>>> print(resources)
Quantum operations:
- Total: 2
- RX: 1
- CNOT: 1
Measurement processes:
- expval(PauliZ): 1
Total wires: 2
Circuit Depth: 2
"""
resources = _count_resources(tape, compute_depth=compute_depth)
return resources
def _obs_to_str(obs) -> str:
"""Convert an Observable to a string representation for resource counting."""
name = obs.name
match name:
case "Hamiltonian" | "LinearCombination" | "Sum" | "Prod":
if name == "LinearCombination":
name = "Hamiltonian"
return f"{name}(num_wires={obs.num_wires}, num_terms={len(obs.operands)})"
case "SProd":
return _obs_to_str(obs.base)
case "Exp":
return f"Exp({_obs_to_str(obs.base)})"
case _:
return name
def _mp_to_str(mp: MeasurementProcess, num_wires: int) -> str:
"""Convert a MeasurementProcess to a string representation for resource counting."""
meas_name = mp._shortname # pylint: disable=protected-access
if mp.mv is not None:
meas_name += "(mcm)"
elif mp.obs is None:
meas_wires = len(mp.wires)
if meas_wires in (None, 0, num_wires):
meas_name += "(all wires)"
else:
meas_name += f"({meas_wires} wires)"
else:
meas_name += f"({_obs_to_str(mp.obs)})"
return meas_name
def _count_resources(tape: QuantumScript, compute_depth: bool = True) -> SpecsResources:
"""Given a quantum tape, this function counts the resources used by standard PennyLane operations.
Args:
tape (.QuantumScript): The quantum circuit for which we count resources
compute_depth (bool): If True, the depth of the circuit is computed and included in the resources.
If False, the depth is set to None.
Returns:
(.SpecsResources): The total resources used in the workflow
"""
num_wires = len(tape.wires)
depth = tape.graph.get_depth() if compute_depth else None
quantum_operations = defaultdict(int)
measurement_processes = defaultdict(int)
for op in tape.operations:
gate_name = op.name
if type(op) in (Controlled, ControlledOp):
n_ctrls = len(op.control_wires)
if n_ctrls > 1:
gate_name = f"{n_ctrls}{gate_name}"
quantum_operations[gate_name] += 1
for meas in tape.measurements:
measurement_processes[_mp_to_str(meas, num_wires)] += 1
return SpecsResources(
counts=dict(quantum_operations),
measurement_processes=dict(measurement_processes),
num_wires=num_wires,
circuit_depth=depth,
)