Algorithmic symbolic resource estimation for Qamomile circuits.
The default clean-ancilla Toffoli control-decomposition model includes reusable
clean ancillas and body-wide shared control ladders when concrete structure
permits them. The abstract control model represents each controlled source
primitive as one logical operation. The physical (surface-code) conversion in
:mod:qamomile.circuit.estimator.physical remains experimental and
intentionally is not re-exported here, keeping algorithmic estimation and
physical assumptions clearly separated. Measurements and resets are reported
independently from gates, while depth retains both the complete critical path
and per-operation-class layers.
Overview¶
| Function | Description |
|---|---|
estimate_resources | Estimate algorithmic resources using the default estimator facade. |
| Class | Description |
|---|---|
ApproximationStatus | Describe whether the selected circuit approximates an ideal operation. |
CallResources | Track opaque callable and oracle query resources. |
ControlDecomposition | Select how coherent controls are represented in resource estimates. |
DepthResources | Track logical depth resources. |
EstimateDerivation | Describe how the estimator obtained the reported resource counts. |
EstimateQuality | Describe the directional quality of reported resource counts. |
GateResources | Track logical gate resources. |
MeasurementResources | Track logical measurement resources. |
ResetResources | Track logical reset resources. |
ResourceAssumption | Record a premise needed to interpret a resource estimate. |
ResourceEstimator | Estimate algorithmic resources for qkernels and IR blocks. |
ResourceTraceNode | Represent one node in the resource-estimation explanation tree. |
WidthResources | Track logical width and ancilla resources. |
Functions¶
estimate_resources [source]¶
def estimate_resources(
kernel: 'QKernel[Any, Any] | Block | Sequence[Operation]',
*,
inputs: dict[str, Any] | None = None,
strategies: dict[str, str] | None = None,
trace: bool = False,
unknown_policy: str | UnknownResourcePolicy = UnknownResourcePolicy.ERROR,
control_decomposition: str | ControlDecomposition = _DEFAULT_CONTROL_DECOMPOSITION,
) -> ResourceEstimateEstimate algorithmic resources using the default estimator facade.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernel[Any, Any] | Block | Sequence[Operation] | QKernel, block, or operation sequence to estimate. |
inputs | dict[str, Any] | None | QKernel input values used to specialize the symbolic estimate without building a problem-sized circuit. Exact one-dimensional root quantum-port widths declared by callable resource metadata are inferred when omitted. Defaults to None. |
strategies | dict[str, str] | None | Strategy overrides by callable name. Defaults to None. |
trace | bool | Whether to retain the explanation tree. Defaults to False. |
unknown_policy | str | UnknownResourcePolicy | Unknown callable handling. Defaults to ERROR. |
control_decomposition | str | ControlDecomposition | Coherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI. |
Returns:
ResourceEstimate — Algorithmic resource estimate.
Raises:
RuntimeError— If a fixed or callback-provided opaque cost contains public metrics or metadata that disagree with retained canonical provenance.ValueError— If the input specialization, estimator configuration, callable resource contract, or structural requirements are invalid.TypeError— Ifkernelis not a supported estimator input.NotImplementedError— If the input IR contains a construct not supported by resource estimation.
Example:
>>> import qamomile.circuit as qmc
>>> @qmc.qkernel
... def repeated_h(n: qmc.UInt) -> qmc.Qubit:
... q = qmc.qubit("q")
... for _ in qmc.range(n):
... q = qmc.h(q)
... return q
>>> symbolic = estimate_resources(repeated_h)
>>> str(symbolic.gates.total)
'n'
>>> estimate_resources(repeated_h, inputs={"n": 8}).gates.total
8Classes¶
ApproximationStatus [source]¶
class ApproximationStatus(enum.StrEnum)Describe whether the selected circuit approximates an ideal operation.
Values:
EXACT: No mathematical approximation is known to the estimator. APPROXIMATE: At least one selected circuit construction approximates its ideal mathematical operation.
Attributes¶
APPROXIMATEEXACT
CallResources [source]¶
class CallResourcesTrack opaque callable and oracle query resources.
Body-backed qkernel calls are recursively expanded into their primitive resources and therefore do not appear here. These maps retain only calls whose body is intentionally opaque under the selected policy or model.
Parameters:
| Name | Type | Description |
|---|---|---|
calls_by_name | dict[str, ResourceExpr] | Opaque invocation count by callable name. |
queries_by_name | dict[str, ResourceExpr] | Opaque query complexity by callable name. |
Constructor¶
def __init__(
self,
calls_by_name: dict[str, ResourceExpr] = dict(),
queries_by_name: dict[str, ResourceExpr] = dict(),
) -> NoneAttributes¶
calls_by_name: dict[str, ResourceExpr]oracle_calls: dict[str, ResourceExpr] Return oracle-call compatible aliases.oracle_queries: dict[str, ResourceExpr] Return oracle-query compatible aliases.queries_by_name: dict[str, ResourceExpr]
Methods¶
simplify¶
def simplify(self) -> CallResourcesSimplify all call expressions.
Returns:
CallResources — Simplified copy.
zero¶
@staticmethod
def zero() -> CallResourcesReturn a zero call estimate.
Returns:
CallResources — Empty call resources.
ControlDecomposition [source]¶
class ControlDecomposition(enum.StrEnum)Select how coherent controls are represented in resource estimates.
Values:
ABSTRACT: Keep each controlled primitive as one abstract logical operation, independently of its control arity. CLEAN_ANCILLA_TOFFOLI: Use the fixed clean-ancilla Toffoli-ladder resource model, including its body-wide sharing rule. This algorithmic model is independent of any engine’s native or fallback emission policy.
Attributes¶
ABSTRACTCLEAN_ANCILLA_TOFFOLI
DepthResources [source]¶
class DepthResourcesTrack logical depth resources.
Parameters:
| Name | Type | Description |
|---|---|---|
depth | ResourceExpr | Total logical depth. |
clifford_depth | ResourceExpr | Clifford-layer depth. |
rotation_depth | ResourceExpr | Rotation-layer depth. |
t_depth | ResourceExpr | T-layer depth. |
toffoli_depth | ResourceExpr | Toffoli-layer depth. |
non_clifford_depth | ResourceExpr | Non-Clifford-layer depth. |
measurement_depth | ResourceExpr | Measurement-layer depth. |
gate_depth | ResourceExpr | Gate-only logical depth. |
reset_depth | ResourceExpr | Reset-layer depth. |
Constructor¶
def __init__(
self,
depth: ResourceExpr = _ZERO,
clifford_depth: ResourceExpr = _ZERO,
rotation_depth: ResourceExpr = _ZERO,
t_depth: ResourceExpr = _ZERO,
toffoli_depth: ResourceExpr = _ZERO,
non_clifford_depth: ResourceExpr = _ZERO,
measurement_depth: ResourceExpr = _ZERO,
gate_depth: ResourceExpr = _ZERO,
reset_depth: ResourceExpr = _ZERO,
) -> NoneAttributes¶
clifford_depth: ResourceExprdepth: ResourceExprgate_depth: ResourceExprmeasurement_depth: ResourceExprnon_clifford_depth: ResourceExprreset_depth: ResourceExprrotation_depth: ResourceExprt_depth: ResourceExprtoffoli_depth: ResourceExpr
Methods¶
simplify¶
def simplify(self) -> DepthResourcesSimplify all depth expressions.
Returns:
DepthResources — Simplified copy.
zero¶
@staticmethod
def zero() -> DepthResourcesReturn a zero depth estimate.
Returns:
DepthResources — Empty depth resources.
EstimateDerivation [source]¶
class EstimateDerivation(enum.StrEnum)Describe how the estimator obtained the reported resource counts.
Values:
STRUCTURAL: Derive counts recursively from visible IR and the selected estimator decomposition rules. MODELED: Use a declared, callback-provided, or fallback resource model for at least one part of the estimate.
Attributes¶
MODELEDSTRUCTURAL
EstimateQuality [source]¶
class EstimateQuality(enum.StrEnum)Describe the directional quality of reported resource counts.
This axis is independent of both count derivation and mathematical
approximation. A modeled estimate can therefore be exact, conservative,
or unknown with respect to the selected resource model. Every active
non-exact quality contributes its explanation to the estimate’s public
assumptions; unrelated assumptions may also accompany exact quality.
Values:
EXACT: Reported counts exactly follow the selected circuit model. CONSERVATIVE: Reported counts may overestimate but do not underestimate the selected circuit model. UNKNOWN: No exact or conservative relation is available.
Attributes¶
CONSERVATIVEEXACTUNKNOWN
GateResources [source]¶
class GateResourcesTrack logical gate resources.
Parameters:
| Name | Type | Description |
|---|---|---|
total | ResourceExpr | Total logical gate count. |
single_qubit | ResourceExpr | Single-qubit gate count. |
two_qubit | ResourceExpr | Two-qubit gate count. |
multi_qubit | ResourceExpr | Three-or-more-qubit gate count. |
clifford | ResourceExpr | Clifford gate count. |
rotation | ResourceExpr | Parametric rotation gate count. |
t | ResourceExpr | T/T-dagger gate count. |
toffoli | ResourceExpr | Toffoli gate count. |
non_clifford | ResourceExpr | Non-Clifford gate count. |
Constructor¶
def __init__(
self,
total: ResourceExpr = _ZERO,
single_qubit: ResourceExpr = _ZERO,
two_qubit: ResourceExpr = _ZERO,
multi_qubit: ResourceExpr = _ZERO,
clifford: ResourceExpr = _ZERO,
rotation: ResourceExpr = _ZERO,
t: ResourceExpr = _ZERO,
toffoli: ResourceExpr = _ZERO,
non_clifford: ResourceExpr = _ZERO,
) -> NoneAttributes¶
clifford: ResourceExprclifford_gates: ResourceExpr Return the Clifford-gate count alias.multi_qubit: ResourceExprnon_clifford: ResourceExprrotation: ResourceExprrotation_gates: ResourceExpr Return the rotation-gate count alias.single_qubit: ResourceExprt: ResourceExprt_gates: ResourceExpr Return the T-gate count alias.toffoli: ResourceExprtotal: ResourceExprtwo_qubit: ResourceExpr
Methods¶
simplify¶
def simplify(self) -> GateResourcesSimplify all gate expressions.
Returns:
GateResources — Simplified copy.
zero¶
@staticmethod
def zero() -> GateResourcesReturn a zero gate estimate.
Returns:
GateResources — Empty gate resources.
MeasurementResources [source]¶
class MeasurementResourcesTrack logical measurement resources.
Parameters:
| Name | Type | Description |
|---|---|---|
total | ResourceExpr | Number of per-qubit measurement events. Measuring an N-qubit vector contributes N, independently of how many source-level or IR operations express the measurement. |
Raises:
ValueError— Iftotalis a concrete value that is not a nonnegative integer.
Constructor¶
def __init__(self, total: ResourceExpr = _ZERO) -> NoneAttributes¶
total: ResourceExpr
Methods¶
simplify¶
def simplify(self) -> MeasurementResourcesSimplify all measurement expressions.
Returns:
MeasurementResources — Simplified copy.
zero¶
@staticmethod
def zero() -> MeasurementResourcesReturn a zero measurement estimate.
Returns:
MeasurementResources — Empty measurement resources.
ResetResources [source]¶
class ResetResourcesTrack logical reset resources.
Parameters:
| Name | Type | Description |
|---|---|---|
total | ResourceExpr | Number of per-qubit reset events. |
Raises:
ValueError— Iftotalis a concrete value that is not a nonnegative integer.
Constructor¶
def __init__(self, total: ResourceExpr = _ZERO) -> NoneAttributes¶
total: ResourceExpr
Methods¶
simplify¶
def simplify(self) -> ResetResourcesSimplify all reset expressions.
Returns:
ResetResources — Simplified copy.
zero¶
@staticmethod
def zero() -> ResetResourcesReturn a zero reset estimate.
Returns:
ResetResources — Empty reset resources.
ResourceAssumption [source]¶
class ResourceAssumptionRecord a premise needed to interpret a resource estimate.
Assumptions disclose modeling choices, recognized approximations, and any
still-symbolic valid-input condition consumed while simplifying a resource
formula. A valid-input premise limits where the formula applies; by itself
it does not make an otherwise exact count conservative. Every active
CONSERVATIVE or UNKNOWN quality fact also contributes its reason
as an assumption, while exact estimates may still have other assumptions.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable premise or qualification. |
source | str | None | Optional callable or operation that caused the premise. Domain-derived entries use "qkernel input domain". Defaults to None. |
Constructor¶
def __init__(self, message: str, source: str | None = None) -> NoneAttributes¶
message: strsource: str | None
ResourceEstimator [source]¶
class ResourceEstimatorEstimate algorithmic resources for qkernels and IR blocks.
Parameters:
| Name | Type | Description |
|---|---|---|
strategies | dict[str, str] | None | Strategy overrides by callable name. Defaults to None. |
trace | bool | Whether to keep explanation traces. Defaults to False. |
simplify | bool | Whether to simplify final expressions, including simplification over valid qkernel input conditions. Defaults to True. |
unknown_policy | str | UnknownResourcePolicy | Handling for unknown bodyless callables. Defaults to ERROR. |
control_decomposition | str | ControlDecomposition | Coherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI. |
Raises:
ValueError— Ifunknown_policyorcontrol_decompositionis unknown.
Constructor¶
def __init__(
self,
*,
strategies: dict[str, str] | None = None,
trace: bool = False,
simplify: bool = True,
unknown_policy: str | UnknownResourcePolicy = UnknownResourcePolicy.ERROR,
control_decomposition: str | ControlDecomposition = _DEFAULT_CONTROL_DECOMPOSITION,
) -> NoneInitialize a resource estimator.
Parameters:
| Name | Type | Description |
|---|---|---|
strategies | dict[str, str] | None | Strategy overrides by callable name. Defaults to None. |
trace | bool | Whether to keep explanation traces. Defaults to False. |
simplify | bool | Whether to simplify the final estimate, including simplification under valid qkernel input conditions. Consumed conditions remain visible in ResourceEstimate.assumptions. Set to False to preserve the unconditional symbolic formulas; calling ResourceEstimate.simplify() later explicitly enables the domain-aware pass. Defaults to True. |
unknown_policy | str | UnknownResourcePolicy | Handling for unknown bodyless callables. Defaults to ERROR. |
control_decomposition | str | ControlDecomposition | Coherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI. |
Raises:
ValueError— Ifunknown_policyorcontrol_decompositionis unknown.
Attributes¶
config
Methods¶
estimate¶
def estimate(
self,
kernel: 'QKernel[Any, Any] | Block | Sequence[Operation]',
*,
inputs: dict[str, Any] | None = None,
strategies: dict[str, str] | None = None,
) -> ResourceEstimateEstimate algorithmic resources for a qkernel, block, or operations.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernel[Any, Any] | Block | Sequence[Operation] | Object to estimate. QKernel-like objects are built before traversal. |
inputs | dict[str, Any] | None | QKernel input values used to specialize the symbolic estimate without constructing a problem-sized circuit. Exact one-dimensional root quantum-port widths declared by callable resource metadata are inferred when omitted. Defaults to None. |
strategies | dict[str, str] | None | Per-call override merged over estimator-level strategies. Defaults to None. |
Returns:
ResourceEstimate — Algorithmic resource estimate.
Raises:
RuntimeError— If a fixed or callback-provided opaque cost contains public metrics or metadata that disagree with retained canonical provenance.ValueError— If an input name is unknown, a callable resource contract is malformed or violated, or a structural resource requirement fails.TypeError— Ifkernelis not a supported estimator input.NotImplementedError— If the input IR contains a construct not supported by resource estimation.
ResourceTraceNode [source]¶
class ResourceTraceNodeRepresent one node in the resource-estimation explanation tree.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Operation or callable name. |
source_kind | str | Source type such as "primitive", "body", "opaque_cost", or "opaque". |
strategy | str | None | Selected resource strategy. Defaults to None. |
summary | str | Short expression summary. Defaults to an empty string. |
assumptions | tuple[ResourceAssumption, ...] | Assumptions local to the node. Defaults to an empty tuple. |
children | tuple[ResourceTraceNode, ...] | Nested trace nodes. Defaults to an empty tuple. |
active_when | sp.Basic | Symbolic activation condition. Defaults to true. |
Constructor¶
def __init__(
self,
name: str,
source_kind: str,
strategy: str | None = None,
summary: str = '',
assumptions: tuple[ResourceAssumption, ...] = (),
children: tuple[ResourceTraceNode, ...] = (),
active_when: sp.Basic = sp.true,
) -> NoneAttributes¶
active_when: sp.Basicassumptions: tuple[ResourceAssumption, ...]children: tuple[ResourceTraceNode, ...]name: strsource_kind: strstrategy: str | Nonesummary: str
Methods¶
mapped¶
def mapped(self, fn: Any) -> ResourceTraceNode | NoneRewrite activation guards and remove inactive trace branches.
Parameters:
| Name | Type | Description |
|---|---|---|
fn | Any | Symbolic-expression rewrite function. |
Returns:
ResourceTraceNode | None — ResourceTraceNode | None: Rewritten trace, or None when this
node resolves inactive.
render¶
def render(self, indent: int = 0, registry: SymbolRegistry | None = None) -> strRender this trace node as plain text.
Parameters:
| Name | Type | Description |
|---|---|---|
indent | int | Number of leading spaces. Defaults to 0. |
registry | SymbolRegistry | None | Shared estimate symbol registry. Defaults to a registry local to each activation condition. |
Returns:
str — Multi-line explanation text.
when¶
def when(self, condition: sp.Basic) -> ResourceTraceNodeReturn this trace guarded by an additional condition.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | sp.Basic | Branch or repetition activation guard. |
Returns:
ResourceTraceNode — Trace guarded by both conditions.
WidthResources [source]¶
class WidthResourcesTrack logical width and ancilla resources.
Parameters:
| Name | Type | Description |
|---|---|---|
input_qubits | ResourceExpr | Qubits supplied by the caller. |
allocated_qubits | ResourceExpr | Qubits allocated by the body. |
clean_ancilla_qubits | ResourceExpr | Clean ancilla qubits required at peak. Defaults to zero. |
dirty_ancilla_qubits | ResourceExpr | Dirty ancilla qubits required at peak. Defaults to zero. |
peak_qubits | ResourceExpr | Conservative peak logical width. |
Constructor¶
def __init__(
self,
input_qubits: ResourceExpr = _ZERO,
allocated_qubits: ResourceExpr = _ZERO,
clean_ancilla_qubits: ResourceExpr = _ZERO,
dirty_ancilla_qubits: ResourceExpr = _ZERO,
peak_qubits: ResourceExpr = _ZERO,
) -> NoneAttributes¶
allocated_qubits: ResourceExprcircuit_qubits: ResourceExpr Return the conservative static circuit width.clean_ancilla_qubits: ResourceExprdirty_ancilla_qubits: ResourceExprinput_qubits: ResourceExprpeak_qubits: ResourceExpr
Methods¶
simplify¶
def simplify(self) -> WidthResourcesSimplify all width expressions.
Returns:
WidthResources — Simplified copy.
zero¶
@staticmethod
def zero() -> WidthResourcesReturn a zero width estimate.
Returns:
WidthResources — Empty width resources.
qamomile.circuit.estimator.physical¶
Convert logical resource estimates into physical surface-code estimates.
Experimental. This module is intentionally not re-exported from
qamomile.circuit.estimator; import it explicitly
(from qamomile.circuit.estimator.physical import ...). It layers a
fault-tolerance model on top of the logical estimator and is kept separate so
logical estimation and physical assumptions do not blur together. The model and
its API may change.
The logical :class:ResourceEstimate produced by
:mod:qamomile.circuit.estimator.resource_estimator counts logical qubits and
logical gate families; it does not synthesize rotations or Toffoli gates into
magic-state operations. Turning those values into physical qubit counts and
wall-clock runtime therefore requires an additional modeling assumption. This
module implements the toy
surface-code / lattice-surgery back-of-the-envelope model used for high-level
resource estimates such as the RSA-2048 factoring numbers in the literature:
d ~= odd_ceiling(2 * log(alpha * N * M) / log(p_th / p))
physical_qubits ~= 4 * N * d**2
runtime ~= M * d * tauwhere N is the logical qubit count, M is the non-Clifford (magic-state)
gate count, p is the physical error rate, p_th is the surface-code
threshold, alpha is a constant prefactor, and tau is the syndrome-cycle
time. Every quantity is kept symbolic (sympy) so a symbolic logical estimate
(e.g. non_clifford = 0.3 * n**3) flows straight through to a symbolic
physical estimate.
Overview¶
| Function | Description |
|---|---|
estimate_physical_resources | Estimate physical resources heuristically from a logical estimate. |
surface_code_estimate | Estimate physical surface-code resources from logical counts. |
| Class | Description |
|---|---|
PhysicalResourceEstimate | Hold a surface-code physical-resource estimate. |
ResourceEstimate | Carry the full algorithmic resource estimate for a qkernel or block. |
Functions¶
estimate_physical_resources [source]¶
def estimate_physical_resources(
estimate: 'ResourceEstimate',
*,
logical_qubits: ResourceExpr | float | int | None = None,
non_clifford_gates: ResourceExpr | float | int | None = None,
physical_error_rate: float = 0.001,
threshold: float = 0.01,
alpha: float = 0.05,
syndrome_cycle_seconds: float = 1e-06,
) -> PhysicalResourceEstimateEstimate physical resources heuristically from a logical estimate.
Reads the logical qubit count and non-Clifford gate count from a
:class:ResourceEstimate and feeds them into :func:surface_code_estimate.
The non-Clifford count falls back to t + toffoli when the estimate does
not populate gates.non_clifford explicitly. This automatic mapping
treats each logical non-Clifford-family entry as one magic-state event; it
is not a synthesis-aware conversion and does not account for the different
costs of arbitrary rotations, T gates, and Toffoli gates. Pass an explicit
non_clifford_gates value when a separate synthesis model is available.
A logical formula simplified under an unresolved qkernel input condition
must first be specialized with ResourceEstimate.substitute(). Because
explicit values no longer depend on that logical formula, supplying both
logical_qubits and non_clifford_gates also permits conversion.
Parameters:
| Name | Type | Description |
|---|---|---|
estimate | ResourceEstimate | Logical resource estimate to convert. |
logical_qubits | ResourceExpr | float | int | None | Override for the logical qubit count N. Defaults to None, meaning estimate.qubits is used. |
non_clifford_gates | ResourceExpr | float | int | None | Override for the magic-state event count M. Defaults to None, meaning a heuristic value is read from the logical gate-family fields. |
physical_error_rate | float | Physical gate error rate p. Defaults to 1e-3. |
threshold | float | Surface-code threshold p_th. Defaults to 1e-2. |
alpha | float | Prefactor alpha. Defaults to 0.05. |
syndrome_cycle_seconds | float | Syndrome-cycle time tau in seconds. Defaults to 1e-6. |
Returns:
PhysicalResourceEstimate — Physical estimate derived from the logical
PhysicalResourceEstimate — estimate.
Raises:
TypeError— If a logical count or model coefficient is not a numeric or symbolic scalar of the declared kind.RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the logical estimate has an unresolved input-domain condition while either logical count is read from it,thresholdis not strictly greater thanphysical_error_rate, a model coefficient is not positive and finite, or either logical count is provably negative, non-real, or non-finite.
Example:
>>> import qamomile.circuit as qmc
>>> # est = kernel.estimate_resources(inputs={"n": 2048})
>>> # phys = estimate_physical_resources(est)surface_code_estimate [source]¶
def surface_code_estimate(
logical_qubits: ResourceExpr | float | int,
non_clifford_gates: ResourceExpr | float | int,
*,
physical_error_rate: float = 0.001,
threshold: float = 0.01,
alpha: float = 0.05,
syndrome_cycle_seconds: float = 1e-06,
) -> PhysicalResourceEstimateEstimate physical surface-code resources from logical counts.
Implements the Chapter-27-style toy model: choose a code distance large
enough to suppress the logical error rate below 1 / (N * M), then read
off physical qubits and runtime.
Parameters:
| Name | Type | Description |
|---|---|---|
logical_qubits | ResourceExpr | float | int | Logical qubit count N. May be symbolic. |
non_clifford_gates | ResourceExpr | float | int | Non-Clifford gate count M (magic states consumed). May be symbolic. |
physical_error_rate | float | Physical gate error rate p. Defaults to 1e-3. |
threshold | float | Surface-code threshold p_th. Defaults to 1e-2. |
alpha | float | Prefactor alpha in the distance formula. Defaults to 0.05. |
syndrome_cycle_seconds | float | Syndrome-cycle time tau in seconds. Defaults to 1e-6 (1 microsecond). |
Returns:
PhysicalResourceEstimate — Physical estimate with a possibly-symbolic
PhysicalResourceEstimate — code distance, physical qubit count, and runtime.
Raises:
TypeError— If a logical count or model coefficient is not a numeric or symbolic scalar of the declared kind.ValueError— Ifthresholdis not strictly greater thanphysical_error_rate(the code cannot suppress errors otherwise), a model coefficient is not positive and finite, or either logical count is provably negative, non-real, or non-finite.
Example:
>>> import sympy as sp
>>> n = sp.Symbol("n", positive=True)
>>> est = surface_code_estimate(3 * n, sp.Rational(3, 10) * n**3)
>>> est.physical_qubits.subs(n, 2048).evalf()
15360000.0000000Classes¶
PhysicalResourceEstimate [source]¶
class PhysicalResourceEstimateHold a surface-code physical-resource estimate.
Parameters:
| Name | Type | Description |
|---|---|---|
logical_qubits | ResourceExpr | Logical qubit count N used as input. |
non_clifford_gates | ResourceExpr | Non-Clifford (magic-state) gate count M used as input. |
code_distance | ResourceExpr | Surface-code distance d. |
physical_qubits | ResourceExpr | Estimated physical qubit count. |
runtime_seconds | ResourceExpr | Estimated wall-clock runtime in seconds. |
qubit_seconds | ResourceExpr | Spacetime volume in physical qubit-seconds (physical_qubits * runtime_seconds). |
physical_error_rate | float | Physical gate error rate p assumed. |
threshold | float | Surface-code threshold p_th assumed. |
alpha | float | Prefactor alpha in the code-distance formula. |
syndrome_cycle_seconds | float | Syndrome-cycle time tau in seconds. |
Constructor¶
def __init__(
self,
logical_qubits: ResourceExpr,
non_clifford_gates: ResourceExpr,
code_distance: ResourceExpr,
physical_qubits: ResourceExpr,
runtime_seconds: ResourceExpr,
qubit_seconds: ResourceExpr,
physical_error_rate: float,
threshold: float,
alpha: float,
syndrome_cycle_seconds: float,
) -> NoneAttributes¶
alpha: floatcode_distance: ResourceExprlogical_qubits: ResourceExprnon_clifford_gates: ResourceExprphysical_error_rate: floatphysical_qubits: ResourceExprqubit_seconds: ResourceExprruntime_hours: ResourceExpr Return the estimated runtime in hours.runtime_seconds: ResourceExprsyndrome_cycle_seconds: floatthreshold: float
ResourceEstimate [source]¶
class ResourceEstimateCarry the full algorithmic resource estimate for a qkernel or block.
Parameters:
| Name | Type | Description |
|---|---|---|
width | WidthResources | Logical width and ancilla estimate. |
gates | GateResources | Logical gate-resource estimate. |
depth | DepthResources | Logical depth-resource estimate. |
calls | CallResources | Callable/query-resource estimate. |
measurements | MeasurementResources | Per-qubit measurement resources. |
resets | ResetResources | Per-qubit reset resources. |
assumptions | tuple[ResourceAssumption, ...] | Premises needed to interpret the estimate, including modeling choices and unresolved valid-input conditions consumed by formula simplification. A domain premise does not lower EXACT quality because the formula remains exact for every valid qkernel input. Every non-exact quality fact also contributes its reason here. |
trace | ResourceTraceNode | None | Explanation tree root. Defaults to None. |
parameters | dict[str, sp.Symbol] | Symbols present in the estimate, keyed by unique public aliases. Defaults to an empty dict. |
derivation | EstimateDerivation | Whether counts are derived from visible structure or use a resource model. Defaults to STRUCTURAL. |
quality | EstimateQuality | Relationship between reported counts and the selected circuit cost. Every non-exact quality contributes an explanatory entry to assumptions. Direct construction uses the first simultaneous nonblank assumption as that reason, or a quality-specific generic reason when none is supplied. Defaults to EXACT. |
approximation | ApproximationStatus | Whether the selected circuit approximates an ideal mathematical operation. Defaults to EXACT. |
control_decomposition | ControlDecomposition | Coherent-control decomposition used for the estimate. Defaults to the clean-ancilla Toffoli model. |
_allocation_sites | dict[str, ResourceExpr] | Internal QInit-site sizes keyed by stable operation-result UUID. Concrete loop evaluation uses this identity map to count one static allocation site once even when the body is replayed across multiple iterations. |
_constraints | tuple[_ResourceConstraint, ...] | Internal structural requirements retained across symbolic substitution. |
_output_sizes | dict[str, ResourceExpr] | Internal live quantum output widths keyed by root allocation owner for nested control-flow operations. |
_input_sizes | dict[str, ResourceExpr] | Internal captured quantum input widths consumed or replaced by nested control-flow operations. |
_has_output_summary | bool | Whether _output_sizes is authoritative, including when a nested operation has no live quantum outputs. |
_dependency_keys | frozenset[WireKey] | None | Internal caller-scoped quantum wires that contribute nonzero depth. None requests the enclosing operation’s conservative ordinary footprint. |
_dependency_reads | frozenset[WireKey] | None | Internal scheduler inputs for rescheduling an already interpreted body, including immutable classical observation tokens. None means that only _dependency_keys is available. |
_dependency_writes | frozenset[WireKey] | None | Internal scheduler outputs for rescheduling an already interpreted body, including newly published observation tokens. None means that only _dependency_keys is available. |
_dependency_completion | dict[WireKey, ResourceExpr] | None | Internal caller-visible completion depth for each dependency wire. None requests conservative reconstruction from _dependency_keys or the enclosing operation footprint. |
_dependency_completion_uniform | bool | None | Whether every caller-visible wire is proven to complete at the aggregate peak of every depth field. None means that field-wise uniformity was not proven. |
_dependency_synchronized_entry_conditions | dict[WireKey, Boolean] | Conditions under which an aggregate depth formula assumes that the listed caller-visible wires enter the operation at the same dependency layer. The enclosing scheduler marks a result conservative when prior work may violate that requirement. |
_dependency_synchronized_entry_certificates | tuple[_SynchronizedEntryCertificate, ...] | Grouped synchronized-entry premises. Each certificate keeps its complete reset coverage, exact safe first-gate frontier, and activation guard together so unrelated frontiers cannot be combined. Defaults to an empty tuple. |
_global_barrier_condition | Boolean | Condition under which an opaque, nested non-unitary, or runtime-control boundary lacks enough wire-level provenance for exact dependency scheduling. |
_measurement_taint_conditions | dict[str, Boolean] | Estimator-local conditions under which classical SSA values derive from runtime quantum observations. This state is used only while recursively interpreting a body and is not a public resource metric. |
_guarded_assumptions | tuple[_GuardedAssumption, ...] | None | Internal condition-aware assumption provenance. None initializes facts from the public assumptions tuple. |
_guarded_derivations | tuple[_GuardedDerivation, ...] | None | Internal condition-aware modeled-derivation provenance. None initializes a fact from the public derivation value. |
_guarded_qualities | tuple[_GuardedQuality, ...] | None | Internal condition-aware non-exact count qualities and their mandatory reasons. None initializes a fact from the public quality value and a simultaneous or generic reason. |
_guarded_approximations | tuple[_GuardedApproximation, ...] | None | Internal condition-aware mathematical approximation provenance. None initializes a fact from the public approximation value. |
_symbol_aliases | dict[sp.Symbol, str] | Internal stable public aliases retained across expression rewrites and partial substitution. |
_domain_rewrite_policy | _DomainRewritePolicy | Whether qkernel input domain simplification is inherited, enabled, or disabled. |
_domain_rewrite_state | _DomainRewriteState | None | Original public metrics and exact consumed predicates for a conditional rewrite. |
_rendered_assumption_snapshot | tuple[ResourceAssumption, ...] | None | Identity-preserving snapshot used to distinguish derived domain assumptions from newly supplied ordinary assumptions. |
Constructor¶
def __init__(
self,
width: WidthResources = WidthResources.zero(),
gates: GateResources = GateResources.zero(),
depth: DepthResources = DepthResources.zero(),
calls: CallResources = CallResources.zero(),
assumptions: tuple[ResourceAssumption, ...] = (),
trace: ResourceTraceNode | None = None,
parameters: dict[str, sp.Symbol] = dict(),
derivation: EstimateDerivation = EstimateDerivation.STRUCTURAL,
quality: EstimateQuality = EstimateQuality.EXACT,
approximation: ApproximationStatus = ApproximationStatus.EXACT,
control_decomposition: ControlDecomposition = _DEFAULT_CONTROL_DECOMPOSITION,
measurements: MeasurementResources = MeasurementResources.zero(),
resets: ResetResources = ResetResources.zero(),
_allocation_sites: dict[str, ResourceExpr] = dict(),
_constraints: tuple[_ResourceConstraint, ...] = tuple(),
_output_sizes: dict[str, ResourceExpr] = dict(),
_input_sizes: dict[str, ResourceExpr] = dict(),
_has_output_summary: bool = False,
_dependency_keys: frozenset[WireKey] | None = None,
_dependency_reads: frozenset[WireKey] | None = None,
_dependency_writes: frozenset[WireKey] | None = None,
_dependency_completion: dict[WireKey, ResourceExpr] | None = None,
_dependency_completion_uniform: bool | None = None,
_dependency_synchronized_entry_conditions: dict[WireKey, Boolean] = dict(),
_dependency_synchronized_entry_certificates: tuple[_SynchronizedEntryCertificate, ...] = tuple(),
_global_barrier_condition: Boolean = sp.false,
_measurement_taint_conditions: dict[str, Boolean] = dict(),
_guarded_assumptions: tuple[_GuardedAssumption, ...] | None = None,
_guarded_derivations: tuple[_GuardedDerivation, ...] | None = None,
_guarded_qualities: tuple[_GuardedQuality, ...] | None = None,
_guarded_approximations: tuple[_GuardedApproximation, ...] | None = None,
_symbol_aliases: dict[sp.Symbol, str] = dict(),
_domain_rewrite_policy: _DomainRewritePolicy = _DomainRewritePolicy.INHERITED,
_domain_rewrite_state: _DomainRewriteState | None = None,
_rendered_assumption_snapshot: tuple[ResourceAssumption, ...] | None = None,
) -> NoneAttributes¶
approximation: ApproximationStatusassumptions: tuple[ResourceAssumption, ...]calls: CallResourcescircuit_qubits: ResourceExpr Return the conservative static circuit-width alias.control_decomposition: ControlDecompositiondepth: DepthResourcesderivation: EstimateDerivationgates: GateResourcesmeasurements: MeasurementResourcesparameters: dict[str, sp.Symbol]quality: EstimateQualityqubits: ResourceExpr Return the peak logical qubit alias.resets: ResetResourcestrace: ResourceTraceNode | Nonewidth: WidthResources
Methods¶
choice¶
def choice(self, other: ResourceEstimate) -> ResourceEstimateCompose a conservative branch choice.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Alternative branch estimate. |
Returns:
ResourceEstimate — Element-wise maximum of both branches.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
conditional¶
def conditional(self, other: ResourceEstimate, condition: sp.Basic) -> ResourceEstimateSelect this estimate or another with a symbolic condition.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Estimate for the false branch. |
condition | sp.Basic | SymPy Boolean selecting this estimate when true and other when false. |
Returns:
ResourceEstimate — Field-wise exact piecewise branch estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
controlled¶
def controlled(self, num_controls: ResourceExpr | int) -> ResourceEstimateEstimate controls on an aggregate cost from its known arity profile.
Under ABSTRACT, every source primitive remains one logical
operation, declared arity buckets shift by the control count, and
shared controls serialize aggregate gate depth. Under
CLEAN_ANCILLA_TOFFOLI, declared one- or two-qubit gates are
projected through a fixed aggregate-level batching model. Two or more
controls around at least two modeled operations share one body-wide
control ladder; smaller cases retain per-primitive lowering. Gate
names and scheduling are unavailable, so gate-family fields use
independent upper bounds over the supported logical primitive
families. A complete arity profile therefore produces a conservative
estimate, while a profile with unclassified or undecomposed gates
remains directionally unknown. Explicit costs are complete contracts:
their authors must include any phase-relevant work that later controls
need as a declared logical primitive, and the estimator does not add
hidden global-phase overhead. Angle-specific phase classification
requires a body-backed global-phase operation; a declared one-qubit
phase entry is an upper-bound representative for a target-free phase.
Aggregate measurement or reset costs fail closed. Body-backed qkernels
are controlled by the estimator interpreter instead.
Parameters:
| Name | Type | Description |
|---|---|---|
num_controls | ResourceExpr | int | Number of active controls. |
Returns:
ResourceEstimate — Estimate with a recorded controlled assumption.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If a concrete control count or projected gate count is negative or non-integral, or if the estimate contains measurement or reset resources.
explain¶
def explain(self, metric: str | None = None) -> strRender the resource-estimation trace.
Parameters:
| Name | Type | Description |
|---|---|---|
metric | str | None | Optional metric name to mention in the heading. Filtering is reserved for a later pass. Defaults to None. |
Returns:
str — Human-readable explanation tree.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.
inverse¶
def inverse(self) -> ResourceEstimateApply an inverse transform.
Returns:
ResourceEstimate — Estimate with identical logical resources.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimate contains measurement or reset resources and is therefore not unitary.
parallel¶
def parallel(self, other: ResourceEstimate) -> ResourceEstimateCompose this estimate in parallel with another estimate.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Estimate that runs concurrently. |
Returns:
ResourceEstimate — Parallel composition.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
primitive¶
@staticmethod
def primitive(
name: str,
gates: GateResources | None = None,
*,
width: WidthResources | None = None,
depth: DepthResources | None = None,
) -> ResourceEstimateCreate an estimate for one primitive operation.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Primitive operation name. |
gates | GateResources | None | Gate resources. Defaults to zero. |
width | WidthResources | None | Width resources. Defaults to zero. |
depth | DepthResources | None | Depth resources. Defaults to one layer when gates are non-zero, otherwise zero. |
Returns:
ResourceEstimate — Primitive estimate with a trace node.
repeat¶
def repeat(self, factor: ResourceExpr | int) -> ResourceEstimateRepeat this estimate with reusable width.
Parameters:
| Name | Type | Description |
|---|---|---|
factor | ResourceExpr | int | Iteration or power factor. |
Returns:
ResourceEstimate — Repeated estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If a concrete factor is negative or non-integral.
seq¶
def seq(self, other: ResourceEstimate) -> ResourceEstimateCompose this estimate before another estimate.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Estimate that runs after this one. |
Returns:
ResourceEstimate — Sequentially composed estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
seq_all¶
@staticmethod
def seq_all(estimates: Iterable[ResourceEstimate]) -> ResourceEstimateCompose estimates with a streaming, order-preserving reduction.
Repeated left-folding copies accumulated guarded metadata at every
step. The binary-counter reduction preserves :meth:seq semantics,
avoids quadratic copy growth, and retains only logarithmically many
intermediate estimates while consuming an iterable.
Parameters:
| Name | Type | Description |
|---|---|---|
estimates | Iterable[ResourceEstimate] | Estimates in execution order. |
Returns:
ResourceEstimate — Sequential composition, or an exact zero
ResourceEstimate — estimate for an empty sequence.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
simplify¶
def simplify(self) -> ResourceEstimateSimplify expressions using valid qkernel input-domain conditions.
Public metrics may be reduced under a structural input condition that
is exposed through :attr:assumptions. The estimate remains exact on
that stated valid domain, and invalid concrete inputs still raise.
Calling this method explicitly enables domain simplification even when
the estimate came from a :class:ResourceEstimator configured with
simplify=False.
Returns:
ResourceEstimate — Simplified estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.
substitute¶
def substitute(self, **values: object = {}) -> ResourceEstimateSubstitute concrete values for symbolic parameters.
Substitution preserves whether input-domain simplification is enabled or disabled. It validates retained qkernel requirements and removes a domain assumption once the supplied values prove it. It does not rebuild dependency scheduling decisions made during estimation.
Parameters:
| Name | Type | Description |
|---|---|---|
**values | object | Mapping from parameter name to a concrete numeric scalar. |
Returns:
ResourceEstimate — Estimate with substituted expressions.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If a name is not a parameter, or a supplied value violates an integer, nonnegative, or other retained valid-input requirement.TypeError— If a supplied value is not a concrete numeric scalar.
sum_over¶
def sum_over(
self,
loop_symbol: sp.Symbol,
start: ResourceExpr,
stop: ResourceExpr,
step: ResourceExpr = _ONE,
) -> ResourceEstimateSum loop-dependent resources over Python range semantics.
Parameters:
| Name | Type | Description |
|---|---|---|
loop_symbol | sp.Symbol | Symbol used for the loop variable. |
start | ResourceExpr | Inclusive start bound. |
stop | ResourceExpr | Exclusive stop bound. |
step | ResourceExpr | Loop step. Defaults to one. |
Returns:
ResourceEstimate — Estimate with additive metrics summed over the
ResourceEstimate — loop and width kept reusable.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the loop step or concrete iteration count is invalid.
to_dict¶
def to_dict(self) -> dict[str, Any]Convert this estimate to a JSON-friendly report snapshot.
Symbolic fields are display strings, not a round-trip expression
format. They can contain Qamomile-specific symbolic nodes and must not
be evaluated with :func:sympy.sympify. To produce a concrete report,
specialize the original estimate with :meth:substitute before
calling this method.
Returns:
dict[str, Any] — dict[str, Any]: Report fields with stringified resource
expressions.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.
zero¶
@staticmethod
def zero(trace_name: str | None = None) -> ResourceEstimateReturn an empty resource estimate.
Parameters:
| Name | Type | Description |
|---|---|---|
trace_name | str | None | Optional trace-node name for the empty estimate. Defaults to None. |
Returns:
ResourceEstimate — Zero-valued estimate.
qamomile.circuit.estimator.resource_estimator¶
Expose the public resource-estimation API.
Overview¶
| Function | Description |
|---|---|
estimate_resources | Estimate algorithmic resources using the default estimator facade. |
| Class | Description |
|---|---|
ApproximationStatus | Describe whether the selected circuit approximates an ideal operation. |
ArrayValue | An array of typed IR values. |
Block | Unified block representation for all pipeline stages. |
CallResources | Track opaque callable and oracle query resources. |
ControlDecomposition | Select how coherent controls are represented in resource estimates. |
DepthResources | Track logical depth resources. |
EstimateDerivation | Describe how the estimator obtained the reported resource counts. |
EstimateQuality | Describe the directional quality of reported resource counts. |
ExprResolver | Single source of truth for converting IR Values to SymPy expressions. |
GateResources | Track logical gate resources. |
MeasurementResources | Track logical measurement resources. |
OpaqueCostContext | Describe the base Oracle definition requested from a cost callback. |
Operation | |
QKernel | Decorator class for Qamomile quantum kernels. |
ResetResources | Track logical reset resources. |
ResourceAssumption | Record a premise needed to interpret a resource estimate. |
ResourceEstimate | Carry the full algorithmic resource estimate for a qkernel or block. |
ResourceEstimator | Estimate algorithmic resources for qkernels and IR blocks. |
ResourceInterpreter | Abstractly interpret IR operations into resource algebra values. |
ResourceTraceNode | Represent one node in the resource-estimation explanation tree. |
UnknownResourcePolicy | Control how the estimator handles bodyless unknown callables. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
WidthResources | Track logical width and ancilla resources. |
Functions¶
estimate_resources [source]¶
def estimate_resources(
kernel: 'QKernel[Any, Any] | Block | Sequence[Operation]',
*,
inputs: dict[str, Any] | None = None,
strategies: dict[str, str] | None = None,
trace: bool = False,
unknown_policy: str | UnknownResourcePolicy = UnknownResourcePolicy.ERROR,
control_decomposition: str | ControlDecomposition = _DEFAULT_CONTROL_DECOMPOSITION,
) -> ResourceEstimateEstimate algorithmic resources using the default estimator facade.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernel[Any, Any] | Block | Sequence[Operation] | QKernel, block, or operation sequence to estimate. |
inputs | dict[str, Any] | None | QKernel input values used to specialize the symbolic estimate without building a problem-sized circuit. Exact one-dimensional root quantum-port widths declared by callable resource metadata are inferred when omitted. Defaults to None. |
strategies | dict[str, str] | None | Strategy overrides by callable name. Defaults to None. |
trace | bool | Whether to retain the explanation tree. Defaults to False. |
unknown_policy | str | UnknownResourcePolicy | Unknown callable handling. Defaults to ERROR. |
control_decomposition | str | ControlDecomposition | Coherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI. |
Returns:
ResourceEstimate — Algorithmic resource estimate.
Raises:
RuntimeError— If a fixed or callback-provided opaque cost contains public metrics or metadata that disagree with retained canonical provenance.ValueError— If the input specialization, estimator configuration, callable resource contract, or structural requirements are invalid.TypeError— Ifkernelis not a supported estimator input.NotImplementedError— If the input IR contains a construct not supported by resource estimation.
Example:
>>> import qamomile.circuit as qmc
>>> @qmc.qkernel
... def repeated_h(n: qmc.UInt) -> qmc.Qubit:
... q = qmc.qubit("q")
... for _ in qmc.range(n):
... q = qmc.h(q)
... return q
>>> symbolic = estimate_resources(repeated_h)
>>> str(symbolic.gates.total)
'n'
>>> estimate_resources(repeated_h, inputs={"n": 8}).gates.total
8Classes¶
ApproximationStatus [source]¶
class ApproximationStatus(enum.StrEnum)Describe whether the selected circuit approximates an ideal operation.
Values:
EXACT: No mathematical approximation is known to the estimator. APPROXIMATE: At least one selected circuit construction approximates its ideal mathematical operation.
Attributes¶
APPROXIMATEEXACT
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
CallResources [source]¶
class CallResourcesTrack opaque callable and oracle query resources.
Body-backed qkernel calls are recursively expanded into their primitive resources and therefore do not appear here. These maps retain only calls whose body is intentionally opaque under the selected policy or model.
Parameters:
| Name | Type | Description |
|---|---|---|
calls_by_name | dict[str, ResourceExpr] | Opaque invocation count by callable name. |
queries_by_name | dict[str, ResourceExpr] | Opaque query complexity by callable name. |
Constructor¶
def __init__(
self,
calls_by_name: dict[str, ResourceExpr] = dict(),
queries_by_name: dict[str, ResourceExpr] = dict(),
) -> NoneAttributes¶
calls_by_name: dict[str, ResourceExpr]oracle_calls: dict[str, ResourceExpr] Return oracle-call compatible aliases.oracle_queries: dict[str, ResourceExpr] Return oracle-query compatible aliases.queries_by_name: dict[str, ResourceExpr]
Methods¶
simplify¶
def simplify(self) -> CallResourcesSimplify all call expressions.
Returns:
CallResources — Simplified copy.
zero¶
@staticmethod
def zero() -> CallResourcesReturn a zero call estimate.
Returns:
CallResources — Empty call resources.
ControlDecomposition [source]¶
class ControlDecomposition(enum.StrEnum)Select how coherent controls are represented in resource estimates.
Values:
ABSTRACT: Keep each controlled primitive as one abstract logical operation, independently of its control arity. CLEAN_ANCILLA_TOFFOLI: Use the fixed clean-ancilla Toffoli-ladder resource model, including its body-wide sharing rule. This algorithmic model is independent of any engine’s native or fallback emission policy.
Attributes¶
ABSTRACTCLEAN_ANCILLA_TOFFOLI
DepthResources [source]¶
class DepthResourcesTrack logical depth resources.
Parameters:
| Name | Type | Description |
|---|---|---|
depth | ResourceExpr | Total logical depth. |
clifford_depth | ResourceExpr | Clifford-layer depth. |
rotation_depth | ResourceExpr | Rotation-layer depth. |
t_depth | ResourceExpr | T-layer depth. |
toffoli_depth | ResourceExpr | Toffoli-layer depth. |
non_clifford_depth | ResourceExpr | Non-Clifford-layer depth. |
measurement_depth | ResourceExpr | Measurement-layer depth. |
gate_depth | ResourceExpr | Gate-only logical depth. |
reset_depth | ResourceExpr | Reset-layer depth. |
Constructor¶
def __init__(
self,
depth: ResourceExpr = _ZERO,
clifford_depth: ResourceExpr = _ZERO,
rotation_depth: ResourceExpr = _ZERO,
t_depth: ResourceExpr = _ZERO,
toffoli_depth: ResourceExpr = _ZERO,
non_clifford_depth: ResourceExpr = _ZERO,
measurement_depth: ResourceExpr = _ZERO,
gate_depth: ResourceExpr = _ZERO,
reset_depth: ResourceExpr = _ZERO,
) -> NoneAttributes¶
clifford_depth: ResourceExprdepth: ResourceExprgate_depth: ResourceExprmeasurement_depth: ResourceExprnon_clifford_depth: ResourceExprreset_depth: ResourceExprrotation_depth: ResourceExprt_depth: ResourceExprtoffoli_depth: ResourceExpr
Methods¶
simplify¶
def simplify(self) -> DepthResourcesSimplify all depth expressions.
Returns:
DepthResources — Simplified copy.
zero¶
@staticmethod
def zero() -> DepthResourcesReturn a zero depth estimate.
Returns:
DepthResources — Empty depth resources.
EstimateDerivation [source]¶
class EstimateDerivation(enum.StrEnum)Describe how the estimator obtained the reported resource counts.
Values:
STRUCTURAL: Derive counts recursively from visible IR and the selected estimator decomposition rules. MODELED: Use a declared, callback-provided, or fallback resource model for at least one part of the estimate.
Attributes¶
MODELEDSTRUCTURAL
EstimateQuality [source]¶
class EstimateQuality(enum.StrEnum)Describe the directional quality of reported resource counts.
This axis is independent of both count derivation and mathematical
approximation. A modeled estimate can therefore be exact, conservative,
or unknown with respect to the selected resource model. Every active
non-exact quality contributes its explanation to the estimate’s public
assumptions; unrelated assumptions may also accompany exact quality.
Values:
EXACT: Reported counts exactly follow the selected circuit model. CONSERVATIVE: Reported counts may overestimate but do not underestimate the selected circuit model. UNKNOWN: No exact or conservative relation is available.
Attributes¶
CONSERVATIVEEXACTUNKNOWN
ExprResolver [source]¶
class ExprResolverSingle source of truth for converting IR Values to SymPy expressions.
Resolution strategy (deterministic, single path):
Already sp.Basic → return as-is
Not a Value (int, float, bool) → direct conversion
UUID in context (call context / expression) → return mapped expression
Constant value → sp.Integer / sp.Float
Unbound parameter → sp.Symbol (symbolic) or raise (concrete)
Arithmetic/comparison result → trace in block operations
Search parent blocks → trace in ancestors
Fallback → identity-qualified symbol or raise
Constructor¶
def __init__(
self,
block: Any = None,
context: dict[str, sp.Expr] | None = None,
loop_var_names: dict[str, sp.Expr] | None = None,
parent_blocks: list[Any] | None = None,
block_index: _ResolverBlockIndex | None = None,
structural_scope: tuple[tuple[int, int], ...] | None = None,
array_context: dict[str, _ArrayState] | None = None,
classical_fact_context: dict[str, _ResolvedClassicalFact] | None = None,
)Initialise an ExprResolver.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Any | The current block (Block or _LocalBlock) whose operations are searched for classical expression traces. |
context | dict[str, sp.Expr] | None | UUID → resolved expression mapping for values passed across scope boundaries (e.g. call arguments, composite-gate operands). |
loop_var_names | dict[str, sp.Expr] | None | Value name → SymPy expression mapping for loop variables in scope. |
parent_blocks | list[Any] | None | Ancestor blocks to search when tracing fails in the current block. |
block_index | _ResolverBlockIndex | None | Shared immutable-block index for producer and input-shape lookups. Child resolvers reuse one owner so every block is indexed at most once. Defaults to None, which creates a new index owner. |
structural_scope | tuple[tuple[int, int], ...] | None | Stable call-site path used by structural resource symbols. Each item contains the invocation and selected-body identities. Defaults to None for a root scope. |
array_context | dict[str, _ArrayState] | None | Array-result UUID to immutable element-wise state. Ordinary child regions share the mapping, while callable scopes copy and explicitly publish output snapshots. Defaults to None. |
classical_fact_context | dict[str, _ResolvedClassicalFact] | None | Scalar or whole-array UUID to its resolved value and guarded scheduler dependencies. Defaults to None. |
Attributes¶
block: Any Return the current block being resolved against.context: dict[str, sp.Expr] Return a copy of the UUID-to-expression context mapping.loop_var_names: dict[str, sp.Expr] Return a copy of the loop-variable expression mapping.structural_scope: tuple[tuple[int, int], ...] Return the nested callable path for structural resource symbols.
Methods¶
array_state_dependencies¶
def array_state_dependencies(self, array: ArrayValue) -> dict[str, Boolean]Delegate whole-array dependency summarization to the array owner.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Array whose immutable state is summarized. |
Returns:
dict[str, Boolean] — dict[str, Boolean]: Retained source tokens and activation guards.
bind¶
def bind(self, value: Value, expression: sp.Expr) -> NoneBind an IR value to an expression in this resolver scope.
This is used for SSA results whose value is established while walking operations in program order, notably the final results of loop region arguments. Child scopes still receive a copy, so a binding cannot leak backwards into an already-created sibling scope.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | IR value whose UUID identifies the binding. |
expression | sp.Expr | Symbolic or concrete expression represented by the value. |
bind_array_selection¶
def bind_array_selection(
self,
result: ArrayValue,
when_true: ArrayValue,
when_false: ArrayValue,
condition: sp.Basic | _ResolvedClassicalFact,
) -> NoneDelegate a branch-selected array binding to the array owner.
Parameters:
| Name | Type | Description |
|---|---|---|
result | ArrayValue | Array SSA version visible after selection. |
when_true | ArrayValue | Source array selected when condition is true. |
when_false | ArrayValue | Source array selected when condition is false. |
condition | sp.Basic | _ResolvedClassicalFact | Predicate selecting the source array, optionally with source-token provenance. |
bind_array_state¶
def bind_array_state(self, result: ArrayValue, state: _ArrayState) -> NoneDelegate an immutable array-state binding to the array owner.
Parameters:
| Name | Type | Description |
|---|---|---|
result | ArrayValue | Array SSA value receiving the snapshot. |
state | _ArrayState | Frozen state resolved in the producing scope. |
bind_array_state_selection¶
def bind_array_state_selection(
self,
result: ArrayValue,
when_true: _ArrayState,
when_false: _ArrayState,
selector: _ResolvedClassicalFact,
) -> NoneDelegate detached branch snapshots to the array owner.
Parameters:
| Name | Type | Description |
|---|---|---|
result | ArrayValue | Array SSA result receiving the selected state. |
when_true | _ArrayState | Detached true-branch snapshot. |
when_false | _ArrayState | Detached false-branch snapshot. |
selector | _ResolvedClassicalFact | Branch selector and its source dependencies. |
bind_call_array_input¶
def bind_call_array_input(self, block: Block, formal: ArrayValue, state: _ArrayState) -> NoneDelegate callable-entry array aliasing to the array owner.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Selected callable body. |
formal | ArrayValue | Array value paired with the call operand. |
state | _ArrayState | Caller state captured at invocation time. |
bind_classical_fact¶
def bind_classical_fact(self, value: Value, fact: _ResolvedClassicalFact) -> NoneBind one scalar or whole-array provenance fact by SSA identity.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | IR value receiving the fact. |
fact | _ResolvedClassicalFact | Resolved value and dependencies. |
bind_classical_selection¶
def bind_classical_selection(
self,
result: Value,
when_true: _ResolvedClassicalFact,
when_false: _ResolvedClassicalFact,
selector: _ResolvedClassicalFact,
value_override: sp.Basic | int | float | bool | None = None,
) -> NoneBind a branch-selected scalar fact to one SSA result.
Branch dependencies use the same guarded choice semantics as array element projection. A caller may supply a separately derived value expression without changing those dependency guards.
Parameters:
| Name | Type | Description |
|---|---|---|
result | Value | Scalar SSA result receiving the selected fact. |
when_true | _ResolvedClassicalFact | True-branch value and sources. |
when_false | _ResolvedClassicalFact | False-branch value and sources. |
selector | _ResolvedClassicalFact | Branch selector and its source dependencies. |
value_override | sp.Basic | int | float | bool | None | Optional result expression to use instead of the selected Piecewise value. Defaults to None. |
bind_loop_array_input¶
def bind_loop_array_input(
self,
operations: Sequence[Operation],
entry: ArrayValue,
state: _ArrayState,
) -> NoneDelegate loop-entry array aliasing to the array owner.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | Sequence[Operation] | Loop-body operations. |
entry | ArrayValue | Pre-loop array value naming the carried lineage. |
state | _ArrayState | Snapshot produced by the previous iteration. |
call_child_scope¶
def call_child_scope(
self,
call_op: Any,
*,
called_block: Block | None = None,
body_implements_transform: bool = False,
actual_operands: Sequence[Any] | None = None,
) -> ExprResolverCreate a child resolver for an inline callable invocation.
Maps formal parameter UUIDs → resolved actual arguments,
including array shape dimension UUIDs (critical for
resolving e.g. kernel.shape[0] inside the callee).
Parent blocks are intentionally reset — the callee only sees
its own scope plus values propagated through call_context.
Parameters:
| Name | Type | Description |
|---|---|---|
call_op | Any | An invocation carrying either a legacy block field, an InvokeOperation.effective_body() method, or an InvokeOperation.body field, plus operands containing actual arguments. |
called_block | Block | None | Already-selected callable body. Pass this when another resolver has selected a backend- or strategy-specific implementation. Defaults to None. |
body_implements_transform | bool | Whether called_block is a transform-specific implementation whose formal inputs include control operands. Defaults to False for a direct body that the compiler transforms structurally. |
actual_operands | Sequence[Any] | None | Call-site operands already aligned to called_block. When omitted, the resolver derives the alignment from the invocation metadata. Defaults to None. |
Returns:
ExprResolver — A new resolver scoped to the callee block with
formal→actual bindings in context and empty parent blocks.
call_structural_scope¶
def call_structural_scope(self, call_op: Any, called_block: Block) -> tuple[tuple[int, int], ...]Return the structural scope of one selected callable body.
Parameters:
| Name | Type | Description |
|---|---|---|
call_op | Any | Invocation-like operation defining the call site. |
called_block | Block | Selected body entered at that call site. |
Returns:
tuple[tuple[int, int], ...] — tuple[tuple[int, int], ...]: Parent path extended by this call
site and selected body.
child_scope¶
def child_scope(
self,
inner_block: Any,
extra_context: dict[str, sp.Expr] | None = None,
extra_loop_vars: dict[str, sp.Expr] | None = None,
) -> ExprResolverCreate a child resolver for an inner scope (loop body, branch).
Propagates parent_blocks so values from outer scopes remain
traceable. For callee invocation scopes, use
:meth:call_child_scope instead — callees get a fresh scope.
Parameters:
| Name | Type | Description |
|---|---|---|
inner_block | Any | The block for the child scope. |
extra_context | dict[str, sp.Expr] | None | Additional UUID → expression mappings to merge into the child context. |
extra_loop_vars | dict[str, sp.Expr] | None | Additional loop variable name → expression mappings. |
Returns:
ExprResolver — A new resolver scoped to inner_block with
parent blocks propagated from the current resolver.
copy_array_context¶
def copy_array_context(self) -> NoneDetach this resolver from a shared mutable array-context mapping.
export_array_context¶
def export_array_context(self, arrays: Sequence[ArrayValue] | None = None) -> dict[str, _ArrayState]Export all or selected persistent array-state bindings.
Parameters:
| Name | Type | Description |
|---|---|---|
arrays | Sequence[ArrayValue] | None | Optional array SSA values to export. Defaults to None, which exports every binding. |
Returns:
dict[str, _ArrayState] — dict[str, _ArrayState]: Detached mapping safe to import elsewhere.
fork_array_context¶
def fork_array_context(self) -> dict[str, _ArrayState]Return a detached shallow copy for a child resolver scope.
The state nodes are immutable, so copying only the UUID map is enough to isolate later bindings while retaining structural sharing.
Returns:
dict[str, _ArrayState] — dict[str, _ArrayState]: Detached array-state mapping.
guard_array_update¶
def guard_array_update(
self,
result: ArrayValue,
previous: ArrayValue,
condition: sp.Basic | _ResolvedClassicalFact,
) -> NoneDelegate one execution-guarded update to the array owner.
Parameters:
| Name | Type | Description |
|---|---|---|
result | ArrayValue | Array SSA version produced by the store. |
previous | ArrayValue | Array version read by the store. |
condition | sp.Basic | _ResolvedClassicalFact | Predicate that the enclosing region executes, optionally with provenance. |
import_array_context¶
def import_array_context(self, context: Mapping[str, _ArrayState], *, replace: bool = False) -> NoneImport persistent array-state bindings into this resolver.
Parameters:
| Name | Type | Description |
|---|---|---|
context | Mapping[str, _ArrayState] | Exported UUID-to-state map. |
replace | bool | Whether to replace every existing binding before importing. Defaults to False, which overlays the supplied bindings. |
isolated_scope¶
def isolated_scope(
self,
inner_block: Any,
extra_context: dict[str, sp.Expr] | None = None,
structural_scope: tuple[tuple[int, int], ...] | None = None,
) -> ExprResolverCreate a resolver scope isolated from caller block visibility.
Callable bodies receive only values mapped explicitly through their operands, but immutable block indexes remain safe to share across the resolver tree.
Parameters:
| Name | Type | Description |
|---|---|---|
inner_block | Any | Callable block for the isolated scope. |
extra_context | dict[str, sp.Expr] | None | Additional UUID to expression mappings for formal inputs. Defaults to None. |
structural_scope | tuple[tuple[int, int], ...] | None | Explicit call-site path for the isolated scope. Defaults to the current path. |
Returns:
ExprResolver — Resolver with no parent blocks and shared block
indexes.
record_array_store¶
def record_array_store(self, operation: StoreArrayElementOperation) -> NoneDelegate one sequential store record to the array owner.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | StoreArrayElementOperation | Store just encountered by the estimator’s sequential interpreter. |
resolve¶
def resolve(self, v: Any) -> sp.ExprConvert IR Value to SymPy expression (symbolic mode).
Unbound parameters become sp.Symbol. Never raises for valid IR.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Any | IR Value, primitive Python type, or sp.Basic. |
Returns:
sp.Expr — sp.Expr: Resolved SymPy expression.
resolve_classical_fact¶
def resolve_classical_fact(self, value: Any) -> _ResolvedClassicalFactResolve a classical value together with scheduler dependencies.
Precise array-element state takes precedence over a conservative whole-array fact. The whole-array dependency is used only when the persistent state cannot project the requested element.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Any | IR value, primitive Python value, or SymPy value to resolve. |
Returns:
_ResolvedClassicalFact — Resolved value and guarded source tokens.
resolve_concrete¶
def resolve_concrete(self, v: Any) -> intConvert IR Value to concrete int.
Parameters:
| Name | Type | Description |
|---|---|---|
v | Any | IR Value, primitive Python type, or sp.Basic. |
Returns:
int — The resolved concrete integer.
Raises:
UnresolvedValueError— If the value is symbolic.
snapshot_array_state¶
def snapshot_array_state(
self,
array: ArrayValue,
*,
ignore_binding: str | None = None,
visited: set[str] | None = None,
) -> _ArrayStateDelegate immutable array-state capture to the array owner.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Array whose current state is captured. |
ignore_binding | str | None | Array binding bypassed for one raw producer lookup. Defaults to None. |
visited | set[str] | None | Array UUIDs already visited on this capture path. Defaults to None. |
Returns:
_ArrayState — Immutable state tree rooted at array.
unresolved_fallback_symbol¶
def unresolved_fallback_symbol(self, value: Value) -> sp.Symbol | NoneReturn the private fallback symbol used for an unresolved value.
A resolved expression can contain both runtime-derived state and
ordinary public inputs. Callers that classify the former must not
infer provenance from every free symbol in the expression. This
method distinguishes the one identity-qualified symbol introduced by
the resolver itself when no binding, constant, parameter, supported
producer, or public input-shape alias can explain value.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | IR scalar value to classify. |
Returns:
sp.Symbol | None — sp.Symbol | None: The resolver-owned fallback symbol, or None
when value has an ordinary symbolic resolution.
GateResources [source]¶
class GateResourcesTrack logical gate resources.
Parameters:
| Name | Type | Description |
|---|---|---|
total | ResourceExpr | Total logical gate count. |
single_qubit | ResourceExpr | Single-qubit gate count. |
two_qubit | ResourceExpr | Two-qubit gate count. |
multi_qubit | ResourceExpr | Three-or-more-qubit gate count. |
clifford | ResourceExpr | Clifford gate count. |
rotation | ResourceExpr | Parametric rotation gate count. |
t | ResourceExpr | T/T-dagger gate count. |
toffoli | ResourceExpr | Toffoli gate count. |
non_clifford | ResourceExpr | Non-Clifford gate count. |
Constructor¶
def __init__(
self,
total: ResourceExpr = _ZERO,
single_qubit: ResourceExpr = _ZERO,
two_qubit: ResourceExpr = _ZERO,
multi_qubit: ResourceExpr = _ZERO,
clifford: ResourceExpr = _ZERO,
rotation: ResourceExpr = _ZERO,
t: ResourceExpr = _ZERO,
toffoli: ResourceExpr = _ZERO,
non_clifford: ResourceExpr = _ZERO,
) -> NoneAttributes¶
clifford: ResourceExprclifford_gates: ResourceExpr Return the Clifford-gate count alias.multi_qubit: ResourceExprnon_clifford: ResourceExprrotation: ResourceExprrotation_gates: ResourceExpr Return the rotation-gate count alias.single_qubit: ResourceExprt: ResourceExprt_gates: ResourceExpr Return the T-gate count alias.toffoli: ResourceExprtotal: ResourceExprtwo_qubit: ResourceExpr
Methods¶
simplify¶
def simplify(self) -> GateResourcesSimplify all gate expressions.
Returns:
GateResources — Simplified copy.
zero¶
@staticmethod
def zero() -> GateResourcesReturn a zero gate estimate.
Returns:
GateResources — Empty gate resources.
MeasurementResources [source]¶
class MeasurementResourcesTrack logical measurement resources.
Parameters:
| Name | Type | Description |
|---|---|---|
total | ResourceExpr | Number of per-qubit measurement events. Measuring an N-qubit vector contributes N, independently of how many source-level or IR operations express the measurement. |
Raises:
ValueError— Iftotalis a concrete value that is not a nonnegative integer.
Constructor¶
def __init__(self, total: ResourceExpr = _ZERO) -> NoneAttributes¶
total: ResourceExpr
Methods¶
simplify¶
def simplify(self) -> MeasurementResourcesSimplify all measurement expressions.
Returns:
MeasurementResources — Simplified copy.
zero¶
@staticmethod
def zero() -> MeasurementResourcesReturn a zero measurement estimate.
Returns:
MeasurementResources — Empty measurement resources.
OpaqueCostContext [source]¶
class OpaqueCostContextDescribe the base Oracle definition requested from a cost callback.
The callback models one ordinary application of the definition. Its
result therefore includes definition_control_qubits but never controls
added by a later qmc.control call or inherited from an enclosing
controlled qkernel. The estimator applies those call-site transforms after
the callback returns. The callback result is a complete definition-level
contract and must include any phase-relevant work that those later
coherent controls need to transform.
Parameters:
| Name | Type | Description |
|---|---|---|
callable_name | str | Human-readable callable name. |
target_shapes | Mapping[str, tuple[ResourceExpr, ...]] | Definition target shapes keyed by formal operand name. A scalar qubit has an empty shape tuple. |
definition_control_qubits | int | Controls declared by the Oracle definition and already included in the callback’s base cost. |
strategy | str | None | Selected base resource strategy. Defaults to None. |
control_decomposition | ControlDecomposition | Requested coherent control model. Defaults to CLEAN_ANCILLA_TOFFOLI. |
Constructor¶
def __init__(
self,
callable_name: str,
target_shapes: Mapping[str, tuple[ResourceExpr, ...]],
definition_control_qubits: int,
strategy: str | None = None,
control_decomposition: ControlDecomposition = _DEFAULT_CONTROL_DECOMPOSITION,
) -> NoneAttributes¶
callable_name: strcontrol_decomposition: ControlDecompositiondefinition_control_qubits: intstrategy: str | Nonetarget_qubits: ResourceExpr Return the flattened width of all definition targets.target_shapes: Mapping[str, tuple[ResourceExpr, ...]]
Operation [source]¶
class Operation(abc.ABC)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operands: list[Value]operation_kind: OperationKind Return the kind of this operation for classical/quantum classification.results: list[Value]signature: Signature
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]Return all input Values including subclass-specific fields.
Generic passes should use this instead of accessing operands
directly to ensure no Value is missed. Subclasses override this
to include extra Value fields (e.g. ControlledUOperation.power).
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationReturn a copy with all Values substituted via mapping.
Handles operands, results, and subclass-specific Value
fields. Subclasses override to handle their extra fields.
QKernel [source]¶
class QKernel(QKernelBuildMixin, QKernelVisualizationMixin, Generic[P, R])Decorator class for Qamomile quantum kernels.
Constructor¶
def __init__(self, func: Callable[P, R]) -> NoneAttributes¶
block: Block Compile the function to a hierarchical Block if not already compiled.effects: KernelEffect Return cached semantic effects of this qkernel.funcinput_types: dict[str, Any] Return resolved and frozen frontend input annotations.nameoutput_types: list[Any] Return the resolved frontend annotation for every output slot.raw_funcreturn_type: Any Return the resolved and frozen complete return annotation.signature
ResetResources [source]¶
class ResetResourcesTrack logical reset resources.
Parameters:
| Name | Type | Description |
|---|---|---|
total | ResourceExpr | Number of per-qubit reset events. |
Raises:
ValueError— Iftotalis a concrete value that is not a nonnegative integer.
Constructor¶
def __init__(self, total: ResourceExpr = _ZERO) -> NoneAttributes¶
total: ResourceExpr
Methods¶
simplify¶
def simplify(self) -> ResetResourcesSimplify all reset expressions.
Returns:
ResetResources — Simplified copy.
zero¶
@staticmethod
def zero() -> ResetResourcesReturn a zero reset estimate.
Returns:
ResetResources — Empty reset resources.
ResourceAssumption [source]¶
class ResourceAssumptionRecord a premise needed to interpret a resource estimate.
Assumptions disclose modeling choices, recognized approximations, and any
still-symbolic valid-input condition consumed while simplifying a resource
formula. A valid-input premise limits where the formula applies; by itself
it does not make an otherwise exact count conservative. Every active
CONSERVATIVE or UNKNOWN quality fact also contributes its reason
as an assumption, while exact estimates may still have other assumptions.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable premise or qualification. |
source | str | None | Optional callable or operation that caused the premise. Domain-derived entries use "qkernel input domain". Defaults to None. |
Constructor¶
def __init__(self, message: str, source: str | None = None) -> NoneAttributes¶
message: strsource: str | None
ResourceEstimate [source]¶
class ResourceEstimateCarry the full algorithmic resource estimate for a qkernel or block.
Parameters:
| Name | Type | Description |
|---|---|---|
width | WidthResources | Logical width and ancilla estimate. |
gates | GateResources | Logical gate-resource estimate. |
depth | DepthResources | Logical depth-resource estimate. |
calls | CallResources | Callable/query-resource estimate. |
measurements | MeasurementResources | Per-qubit measurement resources. |
resets | ResetResources | Per-qubit reset resources. |
assumptions | tuple[ResourceAssumption, ...] | Premises needed to interpret the estimate, including modeling choices and unresolved valid-input conditions consumed by formula simplification. A domain premise does not lower EXACT quality because the formula remains exact for every valid qkernel input. Every non-exact quality fact also contributes its reason here. |
trace | ResourceTraceNode | None | Explanation tree root. Defaults to None. |
parameters | dict[str, sp.Symbol] | Symbols present in the estimate, keyed by unique public aliases. Defaults to an empty dict. |
derivation | EstimateDerivation | Whether counts are derived from visible structure or use a resource model. Defaults to STRUCTURAL. |
quality | EstimateQuality | Relationship between reported counts and the selected circuit cost. Every non-exact quality contributes an explanatory entry to assumptions. Direct construction uses the first simultaneous nonblank assumption as that reason, or a quality-specific generic reason when none is supplied. Defaults to EXACT. |
approximation | ApproximationStatus | Whether the selected circuit approximates an ideal mathematical operation. Defaults to EXACT. |
control_decomposition | ControlDecomposition | Coherent-control decomposition used for the estimate. Defaults to the clean-ancilla Toffoli model. |
_allocation_sites | dict[str, ResourceExpr] | Internal QInit-site sizes keyed by stable operation-result UUID. Concrete loop evaluation uses this identity map to count one static allocation site once even when the body is replayed across multiple iterations. |
_constraints | tuple[_ResourceConstraint, ...] | Internal structural requirements retained across symbolic substitution. |
_output_sizes | dict[str, ResourceExpr] | Internal live quantum output widths keyed by root allocation owner for nested control-flow operations. |
_input_sizes | dict[str, ResourceExpr] | Internal captured quantum input widths consumed or replaced by nested control-flow operations. |
_has_output_summary | bool | Whether _output_sizes is authoritative, including when a nested operation has no live quantum outputs. |
_dependency_keys | frozenset[WireKey] | None | Internal caller-scoped quantum wires that contribute nonzero depth. None requests the enclosing operation’s conservative ordinary footprint. |
_dependency_reads | frozenset[WireKey] | None | Internal scheduler inputs for rescheduling an already interpreted body, including immutable classical observation tokens. None means that only _dependency_keys is available. |
_dependency_writes | frozenset[WireKey] | None | Internal scheduler outputs for rescheduling an already interpreted body, including newly published observation tokens. None means that only _dependency_keys is available. |
_dependency_completion | dict[WireKey, ResourceExpr] | None | Internal caller-visible completion depth for each dependency wire. None requests conservative reconstruction from _dependency_keys or the enclosing operation footprint. |
_dependency_completion_uniform | bool | None | Whether every caller-visible wire is proven to complete at the aggregate peak of every depth field. None means that field-wise uniformity was not proven. |
_dependency_synchronized_entry_conditions | dict[WireKey, Boolean] | Conditions under which an aggregate depth formula assumes that the listed caller-visible wires enter the operation at the same dependency layer. The enclosing scheduler marks a result conservative when prior work may violate that requirement. |
_dependency_synchronized_entry_certificates | tuple[_SynchronizedEntryCertificate, ...] | Grouped synchronized-entry premises. Each certificate keeps its complete reset coverage, exact safe first-gate frontier, and activation guard together so unrelated frontiers cannot be combined. Defaults to an empty tuple. |
_global_barrier_condition | Boolean | Condition under which an opaque, nested non-unitary, or runtime-control boundary lacks enough wire-level provenance for exact dependency scheduling. |
_measurement_taint_conditions | dict[str, Boolean] | Estimator-local conditions under which classical SSA values derive from runtime quantum observations. This state is used only while recursively interpreting a body and is not a public resource metric. |
_guarded_assumptions | tuple[_GuardedAssumption, ...] | None | Internal condition-aware assumption provenance. None initializes facts from the public assumptions tuple. |
_guarded_derivations | tuple[_GuardedDerivation, ...] | None | Internal condition-aware modeled-derivation provenance. None initializes a fact from the public derivation value. |
_guarded_qualities | tuple[_GuardedQuality, ...] | None | Internal condition-aware non-exact count qualities and their mandatory reasons. None initializes a fact from the public quality value and a simultaneous or generic reason. |
_guarded_approximations | tuple[_GuardedApproximation, ...] | None | Internal condition-aware mathematical approximation provenance. None initializes a fact from the public approximation value. |
_symbol_aliases | dict[sp.Symbol, str] | Internal stable public aliases retained across expression rewrites and partial substitution. |
_domain_rewrite_policy | _DomainRewritePolicy | Whether qkernel input domain simplification is inherited, enabled, or disabled. |
_domain_rewrite_state | _DomainRewriteState | None | Original public metrics and exact consumed predicates for a conditional rewrite. |
_rendered_assumption_snapshot | tuple[ResourceAssumption, ...] | None | Identity-preserving snapshot used to distinguish derived domain assumptions from newly supplied ordinary assumptions. |
Constructor¶
def __init__(
self,
width: WidthResources = WidthResources.zero(),
gates: GateResources = GateResources.zero(),
depth: DepthResources = DepthResources.zero(),
calls: CallResources = CallResources.zero(),
assumptions: tuple[ResourceAssumption, ...] = (),
trace: ResourceTraceNode | None = None,
parameters: dict[str, sp.Symbol] = dict(),
derivation: EstimateDerivation = EstimateDerivation.STRUCTURAL,
quality: EstimateQuality = EstimateQuality.EXACT,
approximation: ApproximationStatus = ApproximationStatus.EXACT,
control_decomposition: ControlDecomposition = _DEFAULT_CONTROL_DECOMPOSITION,
measurements: MeasurementResources = MeasurementResources.zero(),
resets: ResetResources = ResetResources.zero(),
_allocation_sites: dict[str, ResourceExpr] = dict(),
_constraints: tuple[_ResourceConstraint, ...] = tuple(),
_output_sizes: dict[str, ResourceExpr] = dict(),
_input_sizes: dict[str, ResourceExpr] = dict(),
_has_output_summary: bool = False,
_dependency_keys: frozenset[WireKey] | None = None,
_dependency_reads: frozenset[WireKey] | None = None,
_dependency_writes: frozenset[WireKey] | None = None,
_dependency_completion: dict[WireKey, ResourceExpr] | None = None,
_dependency_completion_uniform: bool | None = None,
_dependency_synchronized_entry_conditions: dict[WireKey, Boolean] = dict(),
_dependency_synchronized_entry_certificates: tuple[_SynchronizedEntryCertificate, ...] = tuple(),
_global_barrier_condition: Boolean = sp.false,
_measurement_taint_conditions: dict[str, Boolean] = dict(),
_guarded_assumptions: tuple[_GuardedAssumption, ...] | None = None,
_guarded_derivations: tuple[_GuardedDerivation, ...] | None = None,
_guarded_qualities: tuple[_GuardedQuality, ...] | None = None,
_guarded_approximations: tuple[_GuardedApproximation, ...] | None = None,
_symbol_aliases: dict[sp.Symbol, str] = dict(),
_domain_rewrite_policy: _DomainRewritePolicy = _DomainRewritePolicy.INHERITED,
_domain_rewrite_state: _DomainRewriteState | None = None,
_rendered_assumption_snapshot: tuple[ResourceAssumption, ...] | None = None,
) -> NoneAttributes¶
approximation: ApproximationStatusassumptions: tuple[ResourceAssumption, ...]calls: CallResourcescircuit_qubits: ResourceExpr Return the conservative static circuit-width alias.control_decomposition: ControlDecompositiondepth: DepthResourcesderivation: EstimateDerivationgates: GateResourcesmeasurements: MeasurementResourcesparameters: dict[str, sp.Symbol]quality: EstimateQualityqubits: ResourceExpr Return the peak logical qubit alias.resets: ResetResourcestrace: ResourceTraceNode | Nonewidth: WidthResources
Methods¶
choice¶
def choice(self, other: ResourceEstimate) -> ResourceEstimateCompose a conservative branch choice.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Alternative branch estimate. |
Returns:
ResourceEstimate — Element-wise maximum of both branches.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
conditional¶
def conditional(self, other: ResourceEstimate, condition: sp.Basic) -> ResourceEstimateSelect this estimate or another with a symbolic condition.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Estimate for the false branch. |
condition | sp.Basic | SymPy Boolean selecting this estimate when true and other when false. |
Returns:
ResourceEstimate — Field-wise exact piecewise branch estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
controlled¶
def controlled(self, num_controls: ResourceExpr | int) -> ResourceEstimateEstimate controls on an aggregate cost from its known arity profile.
Under ABSTRACT, every source primitive remains one logical
operation, declared arity buckets shift by the control count, and
shared controls serialize aggregate gate depth. Under
CLEAN_ANCILLA_TOFFOLI, declared one- or two-qubit gates are
projected through a fixed aggregate-level batching model. Two or more
controls around at least two modeled operations share one body-wide
control ladder; smaller cases retain per-primitive lowering. Gate
names and scheduling are unavailable, so gate-family fields use
independent upper bounds over the supported logical primitive
families. A complete arity profile therefore produces a conservative
estimate, while a profile with unclassified or undecomposed gates
remains directionally unknown. Explicit costs are complete contracts:
their authors must include any phase-relevant work that later controls
need as a declared logical primitive, and the estimator does not add
hidden global-phase overhead. Angle-specific phase classification
requires a body-backed global-phase operation; a declared one-qubit
phase entry is an upper-bound representative for a target-free phase.
Aggregate measurement or reset costs fail closed. Body-backed qkernels
are controlled by the estimator interpreter instead.
Parameters:
| Name | Type | Description |
|---|---|---|
num_controls | ResourceExpr | int | Number of active controls. |
Returns:
ResourceEstimate — Estimate with a recorded controlled assumption.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If a concrete control count or projected gate count is negative or non-integral, or if the estimate contains measurement or reset resources.
explain¶
def explain(self, metric: str | None = None) -> strRender the resource-estimation trace.
Parameters:
| Name | Type | Description |
|---|---|---|
metric | str | None | Optional metric name to mention in the heading. Filtering is reserved for a later pass. Defaults to None. |
Returns:
str — Human-readable explanation tree.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.
inverse¶
def inverse(self) -> ResourceEstimateApply an inverse transform.
Returns:
ResourceEstimate — Estimate with identical logical resources.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimate contains measurement or reset resources and is therefore not unitary.
parallel¶
def parallel(self, other: ResourceEstimate) -> ResourceEstimateCompose this estimate in parallel with another estimate.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Estimate that runs concurrently. |
Returns:
ResourceEstimate — Parallel composition.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
primitive¶
@staticmethod
def primitive(
name: str,
gates: GateResources | None = None,
*,
width: WidthResources | None = None,
depth: DepthResources | None = None,
) -> ResourceEstimateCreate an estimate for one primitive operation.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Primitive operation name. |
gates | GateResources | None | Gate resources. Defaults to zero. |
width | WidthResources | None | Width resources. Defaults to zero. |
depth | DepthResources | None | Depth resources. Defaults to one layer when gates are non-zero, otherwise zero. |
Returns:
ResourceEstimate — Primitive estimate with a trace node.
repeat¶
def repeat(self, factor: ResourceExpr | int) -> ResourceEstimateRepeat this estimate with reusable width.
Parameters:
| Name | Type | Description |
|---|---|---|
factor | ResourceExpr | int | Iteration or power factor. |
Returns:
ResourceEstimate — Repeated estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If a concrete factor is negative or non-integral.
seq¶
def seq(self, other: ResourceEstimate) -> ResourceEstimateCompose this estimate before another estimate.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Estimate that runs after this one. |
Returns:
ResourceEstimate — Sequentially composed estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
seq_all¶
@staticmethod
def seq_all(estimates: Iterable[ResourceEstimate]) -> ResourceEstimateCompose estimates with a streaming, order-preserving reduction.
Repeated left-folding copies accumulated guarded metadata at every
step. The binary-counter reduction preserves :meth:seq semantics,
avoids quadratic copy growth, and retains only logarithmically many
intermediate estimates while consuming an iterable.
Parameters:
| Name | Type | Description |
|---|---|---|
estimates | Iterable[ResourceEstimate] | Estimates in execution order. |
Returns:
ResourceEstimate — Sequential composition, or an exact zero
ResourceEstimate — estimate for an empty sequence.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
simplify¶
def simplify(self) -> ResourceEstimateSimplify expressions using valid qkernel input-domain conditions.
Public metrics may be reduced under a structural input condition that
is exposed through :attr:assumptions. The estimate remains exact on
that stated valid domain, and invalid concrete inputs still raise.
Calling this method explicitly enables domain simplification even when
the estimate came from a :class:ResourceEstimator configured with
simplify=False.
Returns:
ResourceEstimate — Simplified estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.
substitute¶
def substitute(self, **values: object = {}) -> ResourceEstimateSubstitute concrete values for symbolic parameters.
Substitution preserves whether input-domain simplification is enabled or disabled. It validates retained qkernel requirements and removes a domain assumption once the supplied values prove it. It does not rebuild dependency scheduling decisions made during estimation.
Parameters:
| Name | Type | Description |
|---|---|---|
**values | object | Mapping from parameter name to a concrete numeric scalar. |
Returns:
ResourceEstimate — Estimate with substituted expressions.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If a name is not a parameter, or a supplied value violates an integer, nonnegative, or other retained valid-input requirement.TypeError— If a supplied value is not a concrete numeric scalar.
sum_over¶
def sum_over(
self,
loop_symbol: sp.Symbol,
start: ResourceExpr,
stop: ResourceExpr,
step: ResourceExpr = _ONE,
) -> ResourceEstimateSum loop-dependent resources over Python range semantics.
Parameters:
| Name | Type | Description |
|---|---|---|
loop_symbol | sp.Symbol | Symbol used for the loop variable. |
start | ResourceExpr | Inclusive start bound. |
stop | ResourceExpr | Exclusive stop bound. |
step | ResourceExpr | Loop step. Defaults to one. |
Returns:
ResourceEstimate — Estimate with additive metrics summed over the
ResourceEstimate — loop and width kept reusable.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the loop step or concrete iteration count is invalid.
to_dict¶
def to_dict(self) -> dict[str, Any]Convert this estimate to a JSON-friendly report snapshot.
Symbolic fields are display strings, not a round-trip expression
format. They can contain Qamomile-specific symbolic nodes and must not
be evaluated with :func:sympy.sympify. To produce a concrete report,
specialize the original estimate with :meth:substitute before
calling this method.
Returns:
dict[str, Any] — dict[str, Any]: Report fields with stringified resource
expressions.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.
zero¶
@staticmethod
def zero(trace_name: str | None = None) -> ResourceEstimateReturn an empty resource estimate.
Parameters:
| Name | Type | Description |
|---|---|---|
trace_name | str | None | Optional trace-node name for the empty estimate. Defaults to None. |
Returns:
ResourceEstimate — Zero-valued estimate.
ResourceEstimator [source]¶
class ResourceEstimatorEstimate algorithmic resources for qkernels and IR blocks.
Parameters:
| Name | Type | Description |
|---|---|---|
strategies | dict[str, str] | None | Strategy overrides by callable name. Defaults to None. |
trace | bool | Whether to keep explanation traces. Defaults to False. |
simplify | bool | Whether to simplify final expressions, including simplification over valid qkernel input conditions. Defaults to True. |
unknown_policy | str | UnknownResourcePolicy | Handling for unknown bodyless callables. Defaults to ERROR. |
control_decomposition | str | ControlDecomposition | Coherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI. |
Raises:
ValueError— Ifunknown_policyorcontrol_decompositionis unknown.
Constructor¶
def __init__(
self,
*,
strategies: dict[str, str] | None = None,
trace: bool = False,
simplify: bool = True,
unknown_policy: str | UnknownResourcePolicy = UnknownResourcePolicy.ERROR,
control_decomposition: str | ControlDecomposition = _DEFAULT_CONTROL_DECOMPOSITION,
) -> NoneInitialize a resource estimator.
Parameters:
| Name | Type | Description |
|---|---|---|
strategies | dict[str, str] | None | Strategy overrides by callable name. Defaults to None. |
trace | bool | Whether to keep explanation traces. Defaults to False. |
simplify | bool | Whether to simplify the final estimate, including simplification under valid qkernel input conditions. Consumed conditions remain visible in ResourceEstimate.assumptions. Set to False to preserve the unconditional symbolic formulas; calling ResourceEstimate.simplify() later explicitly enables the domain-aware pass. Defaults to True. |
unknown_policy | str | UnknownResourcePolicy | Handling for unknown bodyless callables. Defaults to ERROR. |
control_decomposition | str | ControlDecomposition | Coherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI. |
Raises:
ValueError— Ifunknown_policyorcontrol_decompositionis unknown.
Attributes¶
config
Methods¶
estimate¶
def estimate(
self,
kernel: 'QKernel[Any, Any] | Block | Sequence[Operation]',
*,
inputs: dict[str, Any] | None = None,
strategies: dict[str, str] | None = None,
) -> ResourceEstimateEstimate algorithmic resources for a qkernel, block, or operations.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernel[Any, Any] | Block | Sequence[Operation] | Object to estimate. QKernel-like objects are built before traversal. |
inputs | dict[str, Any] | None | QKernel input values used to specialize the symbolic estimate without constructing a problem-sized circuit. Exact one-dimensional root quantum-port widths declared by callable resource metadata are inferred when omitted. Defaults to None. |
strategies | dict[str, str] | None | Per-call override merged over estimator-level strategies. Defaults to None. |
Returns:
ResourceEstimate — Algorithmic resource estimate.
Raises:
RuntimeError— If a fixed or callback-provided opaque cost contains public metrics or metadata that disagree with retained canonical provenance.ValueError— If an input name is unknown, a callable resource contract is malformed or violated, or a structural resource requirement fails.TypeError— Ifkernelis not a supported estimator input.NotImplementedError— If the input IR contains a construct not supported by resource estimation.
ResourceInterpreter [source]¶
class ResourceInterpreter(_TransformedCallInterpreter)Abstractly interpret IR operations into resource algebra values.
Methods¶
eval_pauli_evolve¶
def eval_pauli_evolve(
self,
operation: PauliEvolveOp,
resolver: ExprResolver,
*,
controls: ResourceExpr | int = 0,
) -> ResourceEstimateEvaluate a Pauli-gadget decomposition for a bound Hamiltonian.
Basis changes and parity ladders stay uncontrolled under an enclosing controlled evolution; only the axial rotation is controlled. A Hamiltonian constant contributes a controlled relative global phase.
Parameters:
| Name | Type | Description |
|---|---|---|
operation | PauliEvolveOp | Pauli evolution operation. |
resolver | ExprResolver | Resolver for observable and time operands. |
controls | ResourceExpr | int | Surrounding coherent controls. Defaults to zero. |
Returns:
ResourceEstimate — Clean-ancilla Pauli-gadget resources, or a modeled
ResourceEstimate — opaque/zero estimate when the configured unknown policy permits
ResourceEstimate — an unbound Hamiltonian.
Raises:
ValueError— If the Hamiltonian is unbound underERRORpolicy, is non-Hermitian, or requires more qubits than its target register provides.
ResourceTraceNode [source]¶
class ResourceTraceNodeRepresent one node in the resource-estimation explanation tree.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Operation or callable name. |
source_kind | str | Source type such as "primitive", "body", "opaque_cost", or "opaque". |
strategy | str | None | Selected resource strategy. Defaults to None. |
summary | str | Short expression summary. Defaults to an empty string. |
assumptions | tuple[ResourceAssumption, ...] | Assumptions local to the node. Defaults to an empty tuple. |
children | tuple[ResourceTraceNode, ...] | Nested trace nodes. Defaults to an empty tuple. |
active_when | sp.Basic | Symbolic activation condition. Defaults to true. |
Constructor¶
def __init__(
self,
name: str,
source_kind: str,
strategy: str | None = None,
summary: str = '',
assumptions: tuple[ResourceAssumption, ...] = (),
children: tuple[ResourceTraceNode, ...] = (),
active_when: sp.Basic = sp.true,
) -> NoneAttributes¶
active_when: sp.Basicassumptions: tuple[ResourceAssumption, ...]children: tuple[ResourceTraceNode, ...]name: strsource_kind: strstrategy: str | Nonesummary: str
Methods¶
mapped¶
def mapped(self, fn: Any) -> ResourceTraceNode | NoneRewrite activation guards and remove inactive trace branches.
Parameters:
| Name | Type | Description |
|---|---|---|
fn | Any | Symbolic-expression rewrite function. |
Returns:
ResourceTraceNode | None — ResourceTraceNode | None: Rewritten trace, or None when this
node resolves inactive.
render¶
def render(self, indent: int = 0, registry: SymbolRegistry | None = None) -> strRender this trace node as plain text.
Parameters:
| Name | Type | Description |
|---|---|---|
indent | int | Number of leading spaces. Defaults to 0. |
registry | SymbolRegistry | None | Shared estimate symbol registry. Defaults to a registry local to each activation condition. |
Returns:
str — Multi-line explanation text.
when¶
def when(self, condition: sp.Basic) -> ResourceTraceNodeReturn this trace guarded by an additional condition.
Parameters:
| Name | Type | Description |
|---|---|---|
condition | sp.Basic | Branch or repetition activation guard. |
Returns:
ResourceTraceNode — Trace guarded by both conditions.
UnknownResourcePolicy [source]¶
class UnknownResourcePolicy(enum.StrEnum)Control how the estimator handles bodyless unknown callables.
Values:
ERROR: Raise when a callable has neither a body nor an opaque cost. OPAQUE_CALL: Count one opaque call/query and continue. ZERO_WITH_WARNING: Record an assumption and continue with zero cost.
Attributes¶
ERROROPAQUE_CALLZERO_WITH_WARNING
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of backend resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
WidthResources [source]¶
class WidthResourcesTrack logical width and ancilla resources.
Parameters:
| Name | Type | Description |
|---|---|---|
input_qubits | ResourceExpr | Qubits supplied by the caller. |
allocated_qubits | ResourceExpr | Qubits allocated by the body. |
clean_ancilla_qubits | ResourceExpr | Clean ancilla qubits required at peak. Defaults to zero. |
dirty_ancilla_qubits | ResourceExpr | Dirty ancilla qubits required at peak. Defaults to zero. |
peak_qubits | ResourceExpr | Conservative peak logical width. |
Constructor¶
def __init__(
self,
input_qubits: ResourceExpr = _ZERO,
allocated_qubits: ResourceExpr = _ZERO,
clean_ancilla_qubits: ResourceExpr = _ZERO,
dirty_ancilla_qubits: ResourceExpr = _ZERO,
peak_qubits: ResourceExpr = _ZERO,
) -> NoneAttributes¶
allocated_qubits: ResourceExprcircuit_qubits: ResourceExpr Return the conservative static circuit width.clean_ancilla_qubits: ResourceExprdirty_ancilla_qubits: ResourceExprinput_qubits: ResourceExprpeak_qubits: ResourceExpr
Methods¶
simplify¶
def simplify(self) -> WidthResourcesSimplify all width expressions.
Returns:
WidthResources — Simplified copy.
zero¶
@staticmethod
def zero() -> WidthResourcesReturn a zero width estimate.
Returns:
WidthResources — Empty width resources.
qamomile.circuit.estimator.wire¶
Stable stateful codecs for fixed resource-estimate wire payloads.
Overview¶
| Function | Description |
|---|---|
resource_estimate_from_wire | Decode one fixed resource estimate from semantic IR data. |
resource_estimate_to_wire | Encode one fixed resource estimate as serializer-friendly data. |
| Class | Description |
|---|---|
ResourceEstimate | Carry the full algorithmic resource estimate for a qkernel or block. |
ResourceEstimateWireDecoder | Decode one payload stream while preserving shared Dummy identities. |
ResourceEstimateWireEncoder | Encode one payload stream while preserving shared Dummy identities. |
Functions¶
resource_estimate_from_wire [source]¶
def resource_estimate_from_wire(
payload: Any,
*,
decoder: _WireExpressionDecoder | None = None,
) -> ResourceEstimateDecode one fixed resource estimate from semantic IR data.
Parameters:
| Name | Type | Description |
|---|---|---|
payload | Any | Payload produced by :func:resource_estimate_to_wire. |
decoder | _WireExpressionDecoder | None | Optional payload-wide expression decoder shared by every opaque cost in one serialized qkernel. Defaults to None. |
Returns:
ResourceEstimate — Reconstructed fixed resource estimate.
Raises:
ValueError— If the payload, an enum, a symbolic expression, or provenance metadata is malformed.
resource_estimate_to_wire [source]¶
def resource_estimate_to_wire(
estimate: ResourceEstimate,
*,
dummy_slots: dict[sp.Dummy, int] | None = None,
) -> dict[str, Any]Encode one fixed resource estimate as serializer-friendly data.
Parameters:
| Name | Type | Description |
|---|---|---|
estimate | ResourceEstimate | Fixed resource estimate to encode. |
dummy_slots | dict[sp.Dummy, int] | None | Optional payload-wide Dummy slot mapping shared by every opaque cost in one serialized qkernel. Defaults to None. |
Returns:
dict[str, Any] — dict[str, Any]: Closed payload containing metrics, requirements,
guarded provenance, and symbolic expressions.
Raises:
TypeError— Ifestimateis not aResourceEstimate.ValueError— If its expression language or explanation trace exceeds the supported wire contract, or if it carries caller-scoped liveness state that has no meaning for an opaque definition.RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.
Classes¶
ResourceEstimate [source]¶
class ResourceEstimateCarry the full algorithmic resource estimate for a qkernel or block.
Parameters:
| Name | Type | Description |
|---|---|---|
width | WidthResources | Logical width and ancilla estimate. |
gates | GateResources | Logical gate-resource estimate. |
depth | DepthResources | Logical depth-resource estimate. |
calls | CallResources | Callable/query-resource estimate. |
measurements | MeasurementResources | Per-qubit measurement resources. |
resets | ResetResources | Per-qubit reset resources. |
assumptions | tuple[ResourceAssumption, ...] | Premises needed to interpret the estimate, including modeling choices and unresolved valid-input conditions consumed by formula simplification. A domain premise does not lower EXACT quality because the formula remains exact for every valid qkernel input. Every non-exact quality fact also contributes its reason here. |
trace | ResourceTraceNode | None | Explanation tree root. Defaults to None. |
parameters | dict[str, sp.Symbol] | Symbols present in the estimate, keyed by unique public aliases. Defaults to an empty dict. |
derivation | EstimateDerivation | Whether counts are derived from visible structure or use a resource model. Defaults to STRUCTURAL. |
quality | EstimateQuality | Relationship between reported counts and the selected circuit cost. Every non-exact quality contributes an explanatory entry to assumptions. Direct construction uses the first simultaneous nonblank assumption as that reason, or a quality-specific generic reason when none is supplied. Defaults to EXACT. |
approximation | ApproximationStatus | Whether the selected circuit approximates an ideal mathematical operation. Defaults to EXACT. |
control_decomposition | ControlDecomposition | Coherent-control decomposition used for the estimate. Defaults to the clean-ancilla Toffoli model. |
_allocation_sites | dict[str, ResourceExpr] | Internal QInit-site sizes keyed by stable operation-result UUID. Concrete loop evaluation uses this identity map to count one static allocation site once even when the body is replayed across multiple iterations. |
_constraints | tuple[_ResourceConstraint, ...] | Internal structural requirements retained across symbolic substitution. |
_output_sizes | dict[str, ResourceExpr] | Internal live quantum output widths keyed by root allocation owner for nested control-flow operations. |
_input_sizes | dict[str, ResourceExpr] | Internal captured quantum input widths consumed or replaced by nested control-flow operations. |
_has_output_summary | bool | Whether _output_sizes is authoritative, including when a nested operation has no live quantum outputs. |
_dependency_keys | frozenset[WireKey] | None | Internal caller-scoped quantum wires that contribute nonzero depth. None requests the enclosing operation’s conservative ordinary footprint. |
_dependency_reads | frozenset[WireKey] | None | Internal scheduler inputs for rescheduling an already interpreted body, including immutable classical observation tokens. None means that only _dependency_keys is available. |
_dependency_writes | frozenset[WireKey] | None | Internal scheduler outputs for rescheduling an already interpreted body, including newly published observation tokens. None means that only _dependency_keys is available. |
_dependency_completion | dict[WireKey, ResourceExpr] | None | Internal caller-visible completion depth for each dependency wire. None requests conservative reconstruction from _dependency_keys or the enclosing operation footprint. |
_dependency_completion_uniform | bool | None | Whether every caller-visible wire is proven to complete at the aggregate peak of every depth field. None means that field-wise uniformity was not proven. |
_dependency_synchronized_entry_conditions | dict[WireKey, Boolean] | Conditions under which an aggregate depth formula assumes that the listed caller-visible wires enter the operation at the same dependency layer. The enclosing scheduler marks a result conservative when prior work may violate that requirement. |
_dependency_synchronized_entry_certificates | tuple[_SynchronizedEntryCertificate, ...] | Grouped synchronized-entry premises. Each certificate keeps its complete reset coverage, exact safe first-gate frontier, and activation guard together so unrelated frontiers cannot be combined. Defaults to an empty tuple. |
_global_barrier_condition | Boolean | Condition under which an opaque, nested non-unitary, or runtime-control boundary lacks enough wire-level provenance for exact dependency scheduling. |
_measurement_taint_conditions | dict[str, Boolean] | Estimator-local conditions under which classical SSA values derive from runtime quantum observations. This state is used only while recursively interpreting a body and is not a public resource metric. |
_guarded_assumptions | tuple[_GuardedAssumption, ...] | None | Internal condition-aware assumption provenance. None initializes facts from the public assumptions tuple. |
_guarded_derivations | tuple[_GuardedDerivation, ...] | None | Internal condition-aware modeled-derivation provenance. None initializes a fact from the public derivation value. |
_guarded_qualities | tuple[_GuardedQuality, ...] | None | Internal condition-aware non-exact count qualities and their mandatory reasons. None initializes a fact from the public quality value and a simultaneous or generic reason. |
_guarded_approximations | tuple[_GuardedApproximation, ...] | None | Internal condition-aware mathematical approximation provenance. None initializes a fact from the public approximation value. |
_symbol_aliases | dict[sp.Symbol, str] | Internal stable public aliases retained across expression rewrites and partial substitution. |
_domain_rewrite_policy | _DomainRewritePolicy | Whether qkernel input domain simplification is inherited, enabled, or disabled. |
_domain_rewrite_state | _DomainRewriteState | None | Original public metrics and exact consumed predicates for a conditional rewrite. |
_rendered_assumption_snapshot | tuple[ResourceAssumption, ...] | None | Identity-preserving snapshot used to distinguish derived domain assumptions from newly supplied ordinary assumptions. |
Constructor¶
def __init__(
self,
width: WidthResources = WidthResources.zero(),
gates: GateResources = GateResources.zero(),
depth: DepthResources = DepthResources.zero(),
calls: CallResources = CallResources.zero(),
assumptions: tuple[ResourceAssumption, ...] = (),
trace: ResourceTraceNode | None = None,
parameters: dict[str, sp.Symbol] = dict(),
derivation: EstimateDerivation = EstimateDerivation.STRUCTURAL,
quality: EstimateQuality = EstimateQuality.EXACT,
approximation: ApproximationStatus = ApproximationStatus.EXACT,
control_decomposition: ControlDecomposition = _DEFAULT_CONTROL_DECOMPOSITION,
measurements: MeasurementResources = MeasurementResources.zero(),
resets: ResetResources = ResetResources.zero(),
_allocation_sites: dict[str, ResourceExpr] = dict(),
_constraints: tuple[_ResourceConstraint, ...] = tuple(),
_output_sizes: dict[str, ResourceExpr] = dict(),
_input_sizes: dict[str, ResourceExpr] = dict(),
_has_output_summary: bool = False,
_dependency_keys: frozenset[WireKey] | None = None,
_dependency_reads: frozenset[WireKey] | None = None,
_dependency_writes: frozenset[WireKey] | None = None,
_dependency_completion: dict[WireKey, ResourceExpr] | None = None,
_dependency_completion_uniform: bool | None = None,
_dependency_synchronized_entry_conditions: dict[WireKey, Boolean] = dict(),
_dependency_synchronized_entry_certificates: tuple[_SynchronizedEntryCertificate, ...] = tuple(),
_global_barrier_condition: Boolean = sp.false,
_measurement_taint_conditions: dict[str, Boolean] = dict(),
_guarded_assumptions: tuple[_GuardedAssumption, ...] | None = None,
_guarded_derivations: tuple[_GuardedDerivation, ...] | None = None,
_guarded_qualities: tuple[_GuardedQuality, ...] | None = None,
_guarded_approximations: tuple[_GuardedApproximation, ...] | None = None,
_symbol_aliases: dict[sp.Symbol, str] = dict(),
_domain_rewrite_policy: _DomainRewritePolicy = _DomainRewritePolicy.INHERITED,
_domain_rewrite_state: _DomainRewriteState | None = None,
_rendered_assumption_snapshot: tuple[ResourceAssumption, ...] | None = None,
) -> NoneAttributes¶
approximation: ApproximationStatusassumptions: tuple[ResourceAssumption, ...]calls: CallResourcescircuit_qubits: ResourceExpr Return the conservative static circuit-width alias.control_decomposition: ControlDecompositiondepth: DepthResourcesderivation: EstimateDerivationgates: GateResourcesmeasurements: MeasurementResourcesparameters: dict[str, sp.Symbol]quality: EstimateQualityqubits: ResourceExpr Return the peak logical qubit alias.resets: ResetResourcestrace: ResourceTraceNode | Nonewidth: WidthResources
Methods¶
choice¶
def choice(self, other: ResourceEstimate) -> ResourceEstimateCompose a conservative branch choice.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Alternative branch estimate. |
Returns:
ResourceEstimate — Element-wise maximum of both branches.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
conditional¶
def conditional(self, other: ResourceEstimate, condition: sp.Basic) -> ResourceEstimateSelect this estimate or another with a symbolic condition.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Estimate for the false branch. |
condition | sp.Basic | SymPy Boolean selecting this estimate when true and other when false. |
Returns:
ResourceEstimate — Field-wise exact piecewise branch estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
controlled¶
def controlled(self, num_controls: ResourceExpr | int) -> ResourceEstimateEstimate controls on an aggregate cost from its known arity profile.
Under ABSTRACT, every source primitive remains one logical
operation, declared arity buckets shift by the control count, and
shared controls serialize aggregate gate depth. Under
CLEAN_ANCILLA_TOFFOLI, declared one- or two-qubit gates are
projected through a fixed aggregate-level batching model. Two or more
controls around at least two modeled operations share one body-wide
control ladder; smaller cases retain per-primitive lowering. Gate
names and scheduling are unavailable, so gate-family fields use
independent upper bounds over the supported logical primitive
families. A complete arity profile therefore produces a conservative
estimate, while a profile with unclassified or undecomposed gates
remains directionally unknown. Explicit costs are complete contracts:
their authors must include any phase-relevant work that later controls
need as a declared logical primitive, and the estimator does not add
hidden global-phase overhead. Angle-specific phase classification
requires a body-backed global-phase operation; a declared one-qubit
phase entry is an upper-bound representative for a target-free phase.
Aggregate measurement or reset costs fail closed. Body-backed qkernels
are controlled by the estimator interpreter instead.
Parameters:
| Name | Type | Description |
|---|---|---|
num_controls | ResourceExpr | int | Number of active controls. |
Returns:
ResourceEstimate — Estimate with a recorded controlled assumption.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If a concrete control count or projected gate count is negative or non-integral, or if the estimate contains measurement or reset resources.
explain¶
def explain(self, metric: str | None = None) -> strRender the resource-estimation trace.
Parameters:
| Name | Type | Description |
|---|---|---|
metric | str | None | Optional metric name to mention in the heading. Filtering is reserved for a later pass. Defaults to None. |
Returns:
str — Human-readable explanation tree.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.
inverse¶
def inverse(self) -> ResourceEstimateApply an inverse transform.
Returns:
ResourceEstimate — Estimate with identical logical resources.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimate contains measurement or reset resources and is therefore not unitary.
parallel¶
def parallel(self, other: ResourceEstimate) -> ResourceEstimateCompose this estimate in parallel with another estimate.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Estimate that runs concurrently. |
Returns:
ResourceEstimate — Parallel composition.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
primitive¶
@staticmethod
def primitive(
name: str,
gates: GateResources | None = None,
*,
width: WidthResources | None = None,
depth: DepthResources | None = None,
) -> ResourceEstimateCreate an estimate for one primitive operation.
Parameters:
| Name | Type | Description |
|---|---|---|
name | str | Primitive operation name. |
gates | GateResources | None | Gate resources. Defaults to zero. |
width | WidthResources | None | Width resources. Defaults to zero. |
depth | DepthResources | None | Depth resources. Defaults to one layer when gates are non-zero, otherwise zero. |
Returns:
ResourceEstimate — Primitive estimate with a trace node.
repeat¶
def repeat(self, factor: ResourceExpr | int) -> ResourceEstimateRepeat this estimate with reusable width.
Parameters:
| Name | Type | Description |
|---|---|---|
factor | ResourceExpr | int | Iteration or power factor. |
Returns:
ResourceEstimate — Repeated estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If a concrete factor is negative or non-integral.
seq¶
def seq(self, other: ResourceEstimate) -> ResourceEstimateCompose this estimate before another estimate.
Parameters:
| Name | Type | Description |
|---|---|---|
other | ResourceEstimate | Estimate that runs after this one. |
Returns:
ResourceEstimate — Sequentially composed estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
seq_all¶
@staticmethod
def seq_all(estimates: Iterable[ResourceEstimate]) -> ResourceEstimateCompose estimates with a streaming, order-preserving reduction.
Repeated left-folding copies accumulated guarded metadata at every
step. The binary-counter reduction preserves :meth:seq semantics,
avoids quadratic copy growth, and retains only logarithmically many
intermediate estimates while consuming an iterable.
Parameters:
| Name | Type | Description |
|---|---|---|
estimates | Iterable[ResourceEstimate] | Estimates in execution order. |
Returns:
ResourceEstimate — Sequential composition, or an exact zero
ResourceEstimate — estimate for an empty sequence.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the estimates use incompatible control-decomposition provenance.
simplify¶
def simplify(self) -> ResourceEstimateSimplify expressions using valid qkernel input-domain conditions.
Public metrics may be reduced under a structural input condition that
is exposed through :attr:assumptions. The estimate remains exact on
that stated valid domain, and invalid concrete inputs still raise.
Calling this method explicitly enables domain simplification even when
the estimate came from a :class:ResourceEstimator configured with
simplify=False.
Returns:
ResourceEstimate — Simplified estimate.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.
substitute¶
def substitute(self, **values: object = {}) -> ResourceEstimateSubstitute concrete values for symbolic parameters.
Substitution preserves whether input-domain simplification is enabled or disabled. It validates retained qkernel requirements and removes a domain assumption once the supplied values prove it. It does not rebuild dependency scheduling decisions made during estimation.
Parameters:
| Name | Type | Description |
|---|---|---|
**values | object | Mapping from parameter name to a concrete numeric scalar. |
Returns:
ResourceEstimate — Estimate with substituted expressions.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If a name is not a parameter, or a supplied value violates an integer, nonnegative, or other retained valid-input requirement.TypeError— If a supplied value is not a concrete numeric scalar.
sum_over¶
def sum_over(
self,
loop_symbol: sp.Symbol,
start: ResourceExpr,
stop: ResourceExpr,
step: ResourceExpr = _ONE,
) -> ResourceEstimateSum loop-dependent resources over Python range semantics.
Parameters:
| Name | Type | Description |
|---|---|---|
loop_symbol | sp.Symbol | Symbol used for the loop variable. |
start | ResourceExpr | Inclusive start bound. |
stop | ResourceExpr | Exclusive stop bound. |
step | ResourceExpr | Loop step. Defaults to one. |
Returns:
ResourceEstimate — Estimate with additive metrics summed over the
ResourceEstimate — loop and width kept reusable.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.ValueError— If the loop step or concrete iteration count is invalid.
to_dict¶
def to_dict(self) -> dict[str, Any]Convert this estimate to a JSON-friendly report snapshot.
Symbolic fields are display strings, not a round-trip expression
format. They can contain Qamomile-specific symbolic nodes and must not
be evaluated with :func:sympy.sympify. To produce a concrete report,
specialize the original estimate with :meth:substitute before
calling this method.
Returns:
dict[str, Any] — dict[str, Any]: Report fields with stringified resource
expressions.
Raises:
RuntimeError— If public resource metrics or metadata disagree with retained canonical provenance.
zero¶
@staticmethod
def zero(trace_name: str | None = None) -> ResourceEstimateReturn an empty resource estimate.
Parameters:
| Name | Type | Description |
|---|---|---|
trace_name | str | None | Optional trace-node name for the empty estimate. Defaults to None. |
Returns:
ResourceEstimate — Zero-valued estimate.
ResourceEstimateWireDecoder [source]¶
class ResourceEstimateWireDecoderDecode one payload stream while preserving shared Dummy identities.
Constructor¶
def __init__(self) -> NoneInitialize one payload-wide symbolic-expression decoder.
ResourceEstimateWireEncoder [source]¶
class ResourceEstimateWireEncoderEncode one payload stream while preserving shared Dummy identities.
Constructor¶
def __init__(self) -> NoneInitialize an empty payload-wide Dummy slot mapping.