Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

qamomile.circuit.estimator

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

FunctionDescription
estimate_resourcesEstimate algorithmic resources using the default estimator facade.
ClassDescription
ApproximationStatusDescribe whether the selected circuit approximates an ideal operation.
CallResourcesTrack opaque callable and oracle query resources.
ControlDecompositionSelect how coherent controls are represented in resource estimates.
DepthResourcesTrack logical depth resources.
EstimateDerivationDescribe how the estimator obtained the reported resource counts.
EstimateQualityDescribe the directional quality of reported resource counts.
GateResourcesTrack logical gate resources.
MeasurementResourcesTrack logical measurement resources.
ResetResourcesTrack logical reset resources.
ResourceAssumptionRecord a premise needed to interpret a resource estimate.
ResourceEstimatorEstimate algorithmic resources for qkernels and IR blocks.
ResourceTraceNodeRepresent one node in the resource-estimation explanation tree.
WidthResourcesTrack 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,
) -> ResourceEstimate

Estimate algorithmic resources using the default estimator facade.

Parameters:

NameTypeDescription
kernelQKernel[Any, Any] | Block | Sequence[Operation]QKernel, block, or operation sequence to estimate.
inputsdict[str, Any] | NoneQKernel 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.
strategiesdict[str, str] | NoneStrategy overrides by callable name. Defaults to None.
traceboolWhether to retain the explanation tree. Defaults to False.
unknown_policystr | UnknownResourcePolicyUnknown callable handling. Defaults to ERROR.
control_decompositionstr | ControlDecompositionCoherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI.

Returns:

ResourceEstimate — Algorithmic resource estimate.

Raises:

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
8

Classes

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


CallResources [source]

class CallResources

Track 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:

NameTypeDescription
calls_by_namedict[str, ResourceExpr]Opaque invocation count by callable name.
queries_by_namedict[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(),
) -> None

Attributes

Methods

simplify
def simplify(self) -> CallResources

Simplify all call expressions.

Returns:

CallResources — Simplified copy.

zero
@staticmethod
def zero() -> CallResources

Return 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


DepthResources [source]

class DepthResources

Track logical depth resources.

Parameters:

NameTypeDescription
depthResourceExprTotal logical depth.
clifford_depthResourceExprClifford-layer depth.
rotation_depthResourceExprRotation-layer depth.
t_depthResourceExprT-layer depth.
toffoli_depthResourceExprToffoli-layer depth.
non_clifford_depthResourceExprNon-Clifford-layer depth.
measurement_depthResourceExprMeasurement-layer depth.
gate_depthResourceExprGate-only logical depth.
reset_depthResourceExprReset-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,
) -> None

Attributes

Methods

simplify
def simplify(self) -> DepthResources

Simplify all depth expressions.

Returns:

DepthResources — Simplified copy.

zero
@staticmethod
def zero() -> DepthResources

Return 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


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


GateResources [source]

class GateResources

Track logical gate resources.

Parameters:

NameTypeDescription
totalResourceExprTotal logical gate count.
single_qubitResourceExprSingle-qubit gate count.
two_qubitResourceExprTwo-qubit gate count.
multi_qubitResourceExprThree-or-more-qubit gate count.
cliffordResourceExprClifford gate count.
rotationResourceExprParametric rotation gate count.
tResourceExprT/T-dagger gate count.
toffoliResourceExprToffoli gate count.
non_cliffordResourceExprNon-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,
) -> None

Attributes

Methods

simplify
def simplify(self) -> GateResources

Simplify all gate expressions.

Returns:

GateResources — Simplified copy.

zero
@staticmethod
def zero() -> GateResources

Return a zero gate estimate.

Returns:

GateResources — Empty gate resources.


MeasurementResources [source]

class MeasurementResources

Track logical measurement resources.

Parameters:

NameTypeDescription
totalResourceExprNumber 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:

Constructor

def __init__(self, total: ResourceExpr = _ZERO) -> None

Attributes

Methods

simplify
def simplify(self) -> MeasurementResources

Simplify all measurement expressions.

Returns:

MeasurementResources — Simplified copy.

zero
@staticmethod
def zero() -> MeasurementResources

Return a zero measurement estimate.

Returns:

MeasurementResources — Empty measurement resources.


ResetResources [source]

class ResetResources

Track logical reset resources.

Parameters:

NameTypeDescription
totalResourceExprNumber of per-qubit reset events.

Raises:

Constructor

def __init__(self, total: ResourceExpr = _ZERO) -> None

Attributes

Methods

simplify
def simplify(self) -> ResetResources

Simplify all reset expressions.

Returns:

ResetResources — Simplified copy.

zero
@staticmethod
def zero() -> ResetResources

Return a zero reset estimate.

Returns:

ResetResources — Empty reset resources.


ResourceAssumption [source]

class ResourceAssumption

Record 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:

NameTypeDescription
messagestrHuman-readable premise or qualification.
sourcestr | NoneOptional 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) -> None

Attributes


ResourceEstimator [source]

class ResourceEstimator

Estimate algorithmic resources for qkernels and IR blocks.

Parameters:

NameTypeDescription
strategiesdict[str, str] | NoneStrategy overrides by callable name. Defaults to None.
traceboolWhether to keep explanation traces. Defaults to False.
simplifyboolWhether to simplify final expressions, including simplification over valid qkernel input conditions. Defaults to True.
unknown_policystr | UnknownResourcePolicyHandling for unknown bodyless callables. Defaults to ERROR.
control_decompositionstr | ControlDecompositionCoherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI.

Raises:

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,
) -> None

Initialize a resource estimator.

Parameters:

NameTypeDescription
strategiesdict[str, str] | NoneStrategy overrides by callable name. Defaults to None.
traceboolWhether to keep explanation traces. Defaults to False.
simplifyboolWhether 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_policystr | UnknownResourcePolicyHandling for unknown bodyless callables. Defaults to ERROR.
control_decompositionstr | ControlDecompositionCoherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI.

Raises:

Attributes

Methods

estimate
def estimate(
    self,
    kernel: 'QKernel[Any, Any] | Block | Sequence[Operation]',
    *,
    inputs: dict[str, Any] | None = None,
    strategies: dict[str, str] | None = None,
) -> ResourceEstimate

Estimate algorithmic resources for a qkernel, block, or operations.

Parameters:

NameTypeDescription
kernelQKernel[Any, Any] | Block | Sequence[Operation]Object to estimate. QKernel-like objects are built before traversal.
inputsdict[str, Any] | NoneQKernel 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.
strategiesdict[str, str] | NonePer-call override merged over estimator-level strategies. Defaults to None.

Returns:

ResourceEstimate — Algorithmic resource estimate.

Raises:


ResourceTraceNode [source]

class ResourceTraceNode

Represent one node in the resource-estimation explanation tree.

Parameters:

NameTypeDescription
namestrOperation or callable name.
source_kindstrSource type such as "primitive", "body", "opaque_cost", or "opaque".
strategystr | NoneSelected resource strategy. Defaults to None.
summarystrShort expression summary. Defaults to an empty string.
assumptionstuple[ResourceAssumption, ...]Assumptions local to the node. Defaults to an empty tuple.
childrentuple[ResourceTraceNode, ...]Nested trace nodes. Defaults to an empty tuple.
active_whensp.BasicSymbolic 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,
) -> None

Attributes

Methods

mapped
def mapped(self, fn: Any) -> ResourceTraceNode | None

Rewrite activation guards and remove inactive trace branches.

Parameters:

NameTypeDescription
fnAnySymbolic-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) -> str

Render this trace node as plain text.

Parameters:

NameTypeDescription
indentintNumber of leading spaces. Defaults to 0.
registrySymbolRegistry | NoneShared 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) -> ResourceTraceNode

Return this trace guarded by an additional condition.

Parameters:

NameTypeDescription
conditionsp.BasicBranch or repetition activation guard.

Returns:

ResourceTraceNode — Trace guarded by both conditions.


WidthResources [source]

class WidthResources

Track logical width and ancilla resources.

Parameters:

NameTypeDescription
input_qubitsResourceExprQubits supplied by the caller.
allocated_qubitsResourceExprQubits allocated by the body.
clean_ancilla_qubitsResourceExprClean ancilla qubits required at peak. Defaults to zero.
dirty_ancilla_qubitsResourceExprDirty ancilla qubits required at peak. Defaults to zero.
peak_qubitsResourceExprConservative 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,
) -> None

Attributes

Methods

simplify
def simplify(self) -> WidthResources

Simplify all width expressions.

Returns:

WidthResources — Simplified copy.

zero
@staticmethod
def zero() -> WidthResources

Return 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 * tau

where 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

FunctionDescription
estimate_physical_resourcesEstimate physical resources heuristically from a logical estimate.
surface_code_estimateEstimate physical surface-code resources from logical counts.
ClassDescription
PhysicalResourceEstimateHold a surface-code physical-resource estimate.
ResourceEstimateCarry 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,
) -> PhysicalResourceEstimate

Estimate 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:

NameTypeDescription
estimateResourceEstimateLogical resource estimate to convert.
logical_qubitsResourceExpr | float | int | NoneOverride for the logical qubit count N. Defaults to None, meaning estimate.qubits is used.
non_clifford_gatesResourceExpr | float | int | NoneOverride for the magic-state event count M. Defaults to None, meaning a heuristic value is read from the logical gate-family fields.
physical_error_ratefloatPhysical gate error rate p. Defaults to 1e-3.
thresholdfloatSurface-code threshold p_th. Defaults to 1e-2.
alphafloatPrefactor alpha. Defaults to 0.05.
syndrome_cycle_secondsfloatSyndrome-cycle time tau in seconds. Defaults to 1e-6.

Returns:

PhysicalResourceEstimate — Physical estimate derived from the logical PhysicalResourceEstimate — estimate.

Raises:

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,
) -> PhysicalResourceEstimate

Estimate 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:

NameTypeDescription
logical_qubitsResourceExpr | float | intLogical qubit count N. May be symbolic.
non_clifford_gatesResourceExpr | float | intNon-Clifford gate count M (magic states consumed). May be symbolic.
physical_error_ratefloatPhysical gate error rate p. Defaults to 1e-3.
thresholdfloatSurface-code threshold p_th. Defaults to 1e-2.
alphafloatPrefactor alpha in the distance formula. Defaults to 0.05.
syndrome_cycle_secondsfloatSyndrome-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:

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.0000000

Classes

PhysicalResourceEstimate [source]

class PhysicalResourceEstimate

Hold a surface-code physical-resource estimate.

Parameters:

NameTypeDescription
logical_qubitsResourceExprLogical qubit count N used as input.
non_clifford_gatesResourceExprNon-Clifford (magic-state) gate count M used as input.
code_distanceResourceExprSurface-code distance d.
physical_qubitsResourceExprEstimated physical qubit count.
runtime_secondsResourceExprEstimated wall-clock runtime in seconds.
qubit_secondsResourceExprSpacetime volume in physical qubit-seconds (physical_qubits * runtime_seconds).
physical_error_ratefloatPhysical gate error rate p assumed.
thresholdfloatSurface-code threshold p_th assumed.
alphafloatPrefactor alpha in the code-distance formula.
syndrome_cycle_secondsfloatSyndrome-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,
) -> None
Attributes

ResourceEstimate [source]

class ResourceEstimate

Carry the full algorithmic resource estimate for a qkernel or block.

Parameters:

NameTypeDescription
widthWidthResourcesLogical width and ancilla estimate.
gatesGateResourcesLogical gate-resource estimate.
depthDepthResourcesLogical depth-resource estimate.
callsCallResourcesCallable/query-resource estimate.
measurementsMeasurementResourcesPer-qubit measurement resources.
resetsResetResourcesPer-qubit reset resources.
assumptionstuple[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.
traceResourceTraceNode | NoneExplanation tree root. Defaults to None.
parametersdict[str, sp.Symbol]Symbols present in the estimate, keyed by unique public aliases. Defaults to an empty dict.
derivationEstimateDerivationWhether counts are derived from visible structure or use a resource model. Defaults to STRUCTURAL.
qualityEstimateQualityRelationship 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.
approximationApproximationStatusWhether the selected circuit approximates an ideal mathematical operation. Defaults to EXACT.
control_decompositionControlDecompositionCoherent-control decomposition used for the estimate. Defaults to the clean-ancilla Toffoli model.
_allocation_sitesdict[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.
_constraintstuple[_ResourceConstraint, ...]Internal structural requirements retained across symbolic substitution.
_output_sizesdict[str, ResourceExpr]Internal live quantum output widths keyed by root allocation owner for nested control-flow operations.
_input_sizesdict[str, ResourceExpr]Internal captured quantum input widths consumed or replaced by nested control-flow operations.
_has_output_summaryboolWhether _output_sizes is authoritative, including when a nested operation has no live quantum outputs.
_dependency_keysfrozenset[WireKey] | NoneInternal caller-scoped quantum wires that contribute nonzero depth. None requests the enclosing operation’s conservative ordinary footprint.
_dependency_readsfrozenset[WireKey] | NoneInternal scheduler inputs for rescheduling an already interpreted body, including immutable classical observation tokens. None means that only _dependency_keys is available.
_dependency_writesfrozenset[WireKey] | NoneInternal scheduler outputs for rescheduling an already interpreted body, including newly published observation tokens. None means that only _dependency_keys is available.
_dependency_completiondict[WireKey, ResourceExpr] | NoneInternal caller-visible completion depth for each dependency wire. None requests conservative reconstruction from _dependency_keys or the enclosing operation footprint.
_dependency_completion_uniformbool | NoneWhether 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_conditionsdict[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_certificatestuple[_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_conditionBooleanCondition under which an opaque, nested non-unitary, or runtime-control boundary lacks enough wire-level provenance for exact dependency scheduling.
_measurement_taint_conditionsdict[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_assumptionstuple[_GuardedAssumption, ...] | NoneInternal condition-aware assumption provenance. None initializes facts from the public assumptions tuple.
_guarded_derivationstuple[_GuardedDerivation, ...] | NoneInternal condition-aware modeled-derivation provenance. None initializes a fact from the public derivation value.
_guarded_qualitiestuple[_GuardedQuality, ...] | NoneInternal 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_approximationstuple[_GuardedApproximation, ...] | NoneInternal condition-aware mathematical approximation provenance. None initializes a fact from the public approximation value.
_symbol_aliasesdict[sp.Symbol, str]Internal stable public aliases retained across expression rewrites and partial substitution.
_domain_rewrite_policy_DomainRewritePolicyWhether qkernel input domain simplification is inherited, enabled, or disabled.
_domain_rewrite_state_DomainRewriteState | NoneOriginal public metrics and exact consumed predicates for a conditional rewrite.
_rendered_assumption_snapshottuple[ResourceAssumption, ...] | NoneIdentity-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,
) -> None
Attributes
Methods
choice
def choice(self, other: ResourceEstimate) -> ResourceEstimate

Compose a conservative branch choice.

Parameters:

NameTypeDescription
otherResourceEstimateAlternative branch estimate.

Returns:

ResourceEstimate — Element-wise maximum of both branches.

Raises:

conditional
def conditional(self, other: ResourceEstimate, condition: sp.Basic) -> ResourceEstimate

Select this estimate or another with a symbolic condition.

Parameters:

NameTypeDescription
otherResourceEstimateEstimate for the false branch.
conditionsp.BasicSymPy Boolean selecting this estimate when true and other when false.

Returns:

ResourceEstimate — Field-wise exact piecewise branch estimate.

Raises:

controlled
def controlled(self, num_controls: ResourceExpr | int) -> ResourceEstimate

Estimate 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:

NameTypeDescription
num_controlsResourceExpr | intNumber of active controls.

Returns:

ResourceEstimate — Estimate with a recorded controlled assumption.

Raises:

explain
def explain(self, metric: str | None = None) -> str

Render the resource-estimation trace.

Parameters:

NameTypeDescription
metricstr | NoneOptional metric name to mention in the heading. Filtering is reserved for a later pass. Defaults to None.

Returns:

str — Human-readable explanation tree.

Raises:

inverse
def inverse(self) -> ResourceEstimate

Apply an inverse transform.

Returns:

ResourceEstimate — Estimate with identical logical resources.

Raises:

parallel
def parallel(self, other: ResourceEstimate) -> ResourceEstimate

Compose this estimate in parallel with another estimate.

Parameters:

NameTypeDescription
otherResourceEstimateEstimate that runs concurrently.

Returns:

ResourceEstimate — Parallel composition.

Raises:

primitive
@staticmethod
def primitive(
    name: str,
    gates: GateResources | None = None,
    *,
    width: WidthResources | None = None,
    depth: DepthResources | None = None,
) -> ResourceEstimate

Create an estimate for one primitive operation.

Parameters:

NameTypeDescription
namestrPrimitive operation name.
gatesGateResources | NoneGate resources. Defaults to zero.
widthWidthResources | NoneWidth resources. Defaults to zero.
depthDepthResources | NoneDepth 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) -> ResourceEstimate

Repeat this estimate with reusable width.

Parameters:

NameTypeDescription
factorResourceExpr | intIteration or power factor.

Returns:

ResourceEstimate — Repeated estimate.

Raises:

seq
def seq(self, other: ResourceEstimate) -> ResourceEstimate

Compose this estimate before another estimate.

Parameters:

NameTypeDescription
otherResourceEstimateEstimate that runs after this one.

Returns:

ResourceEstimate — Sequentially composed estimate.

Raises:

seq_all
@staticmethod
def seq_all(estimates: Iterable[ResourceEstimate]) -> ResourceEstimate

Compose 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:

NameTypeDescription
estimatesIterable[ResourceEstimate]Estimates in execution order.

Returns:

ResourceEstimate — Sequential composition, or an exact zero ResourceEstimate — estimate for an empty sequence.

Raises:

simplify
def simplify(self) -> ResourceEstimate

Simplify 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:

substitute
def substitute(self, **values: object = {}) -> ResourceEstimate

Substitute 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:

NameTypeDescription
**valuesobjectMapping from parameter name to a concrete numeric scalar.

Returns:

ResourceEstimate — Estimate with substituted expressions.

Raises:

sum_over
def sum_over(
    self,
    loop_symbol: sp.Symbol,
    start: ResourceExpr,
    stop: ResourceExpr,
    step: ResourceExpr = _ONE,
) -> ResourceEstimate

Sum loop-dependent resources over Python range semantics.

Parameters:

NameTypeDescription
loop_symbolsp.SymbolSymbol used for the loop variable.
startResourceExprInclusive start bound.
stopResourceExprExclusive stop bound.
stepResourceExprLoop step. Defaults to one.

Returns:

ResourceEstimate — Estimate with additive metrics summed over the ResourceEstimate — loop and width kept reusable.

Raises:

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:

zero
@staticmethod
def zero(trace_name: str | None = None) -> ResourceEstimate

Return an empty resource estimate.

Parameters:

NameTypeDescription
trace_namestr | NoneOptional 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

FunctionDescription
estimate_resourcesEstimate algorithmic resources using the default estimator facade.
ClassDescription
ApproximationStatusDescribe whether the selected circuit approximates an ideal operation.
ArrayValueAn array of typed IR values.
BlockUnified block representation for all pipeline stages.
CallResourcesTrack opaque callable and oracle query resources.
ControlDecompositionSelect how coherent controls are represented in resource estimates.
DepthResourcesTrack logical depth resources.
EstimateDerivationDescribe how the estimator obtained the reported resource counts.
EstimateQualityDescribe the directional quality of reported resource counts.
ExprResolverSingle source of truth for converting IR Values to SymPy expressions.
GateResourcesTrack logical gate resources.
MeasurementResourcesTrack logical measurement resources.
OpaqueCostContextDescribe the base Oracle definition requested from a cost callback.
Operation
QKernelDecorator class for Qamomile quantum kernels.
ResetResourcesTrack logical reset resources.
ResourceAssumptionRecord a premise needed to interpret a resource estimate.
ResourceEstimateCarry the full algorithmic resource estimate for a qkernel or block.
ResourceEstimatorEstimate algorithmic resources for qkernels and IR blocks.
ResourceInterpreterAbstractly interpret IR operations into resource algebra values.
ResourceTraceNodeRepresent one node in the resource-estimation explanation tree.
UnknownResourcePolicyControl how the estimator handles bodyless unknown callables.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
WidthResourcesTrack 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,
) -> ResourceEstimate

Estimate algorithmic resources using the default estimator facade.

Parameters:

NameTypeDescription
kernelQKernel[Any, Any] | Block | Sequence[Operation]QKernel, block, or operation sequence to estimate.
inputsdict[str, Any] | NoneQKernel 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.
strategiesdict[str, str] | NoneStrategy overrides by callable name. Defaults to None.
traceboolWhether to retain the explanation tree. Defaults to False.
unknown_policystr | UnknownResourcePolicyUnknown callable handling. Defaults to ERROR.
control_decompositionstr | ControlDecompositionCoherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI.

Returns:

ResourceEstimate — Algorithmic resource estimate.

Raises:

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
8

Classes

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

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,
) -> None
Attributes
Methods
is_slice
def is_slice(self) -> bool

Return True if this array is a strided view of another array.

Returns:

boolTrue iff slice_of is non-None.

next_version
def next_version(self) -> ArrayValue[T]

Block [source]

class Block

Unified 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(),
) -> None
Attributes
Methods
call
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'

Create an inline callable invocation against this block.

Parameters:

NameTypeDescription
**kwargsValueLikeActual argument values keyed by self.label_args.

Returns:

'InvokeOperation' — Inline-policy invocation whose callable definition points at this block.

Raises:

is_affine
def is_affine(self) -> bool

Return 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 CallResources

Track 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:

NameTypeDescription
calls_by_namedict[str, ResourceExpr]Opaque invocation count by callable name.
queries_by_namedict[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(),
) -> None
Attributes
Methods
simplify
def simplify(self) -> CallResources

Simplify all call expressions.

Returns:

CallResources — Simplified copy.

zero
@staticmethod
def zero() -> CallResources

Return 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

DepthResources [source]

class DepthResources

Track logical depth resources.

Parameters:

NameTypeDescription
depthResourceExprTotal logical depth.
clifford_depthResourceExprClifford-layer depth.
rotation_depthResourceExprRotation-layer depth.
t_depthResourceExprT-layer depth.
toffoli_depthResourceExprToffoli-layer depth.
non_clifford_depthResourceExprNon-Clifford-layer depth.
measurement_depthResourceExprMeasurement-layer depth.
gate_depthResourceExprGate-only logical depth.
reset_depthResourceExprReset-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,
) -> None
Attributes
Methods
simplify
def simplify(self) -> DepthResources

Simplify all depth expressions.

Returns:

DepthResources — Simplified copy.

zero
@staticmethod
def zero() -> DepthResources

Return 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

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

ExprResolver [source]

class ExprResolver

Single source of truth for converting IR Values to SymPy expressions.

Resolution strategy (deterministic, single path):

  1. Already sp.Basic → return as-is

  2. Not a Value (int, float, bool) → direct conversion

  3. UUID in context (call context / expression) → return mapped expression

  4. Constant value → sp.Integer / sp.Float

  5. Unbound parameter → sp.Symbol (symbolic) or raise (concrete)

  6. Arithmetic/comparison result → trace in block operations

  7. Search parent blocks → trace in ancestors

  8. 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:

NameTypeDescription
blockAnyThe current block (Block or _LocalBlock) whose operations are searched for classical expression traces.
contextdict[str, sp.Expr] | NoneUUID → resolved expression mapping for values passed across scope boundaries (e.g. call arguments, composite-gate operands).
loop_var_namesdict[str, sp.Expr] | NoneValue name → SymPy expression mapping for loop variables in scope.
parent_blockslist[Any] | NoneAncestor blocks to search when tracing fails in the current block.
block_index_ResolverBlockIndex | NoneShared 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_scopetuple[tuple[int, int], ...] | NoneStable 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_contextdict[str, _ArrayState] | NoneArray-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_contextdict[str, _ResolvedClassicalFact] | NoneScalar or whole-array UUID to its resolved value and guarded scheduler dependencies. Defaults to None.
Attributes
Methods
array_state_dependencies
def array_state_dependencies(self, array: ArrayValue) -> dict[str, Boolean]

Delegate whole-array dependency summarization to the array owner.

Parameters:

NameTypeDescription
arrayArrayValueArray 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) -> None

Bind 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:

NameTypeDescription
valueValueIR value whose UUID identifies the binding.
expressionsp.ExprSymbolic 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,
) -> None

Delegate a branch-selected array binding to the array owner.

Parameters:

NameTypeDescription
resultArrayValueArray SSA version visible after selection.
when_trueArrayValueSource array selected when condition is true.
when_falseArrayValueSource array selected when condition is false.
conditionsp.Basic | _ResolvedClassicalFactPredicate selecting the source array, optionally with source-token provenance.
bind_array_state
def bind_array_state(self, result: ArrayValue, state: _ArrayState) -> None

Delegate an immutable array-state binding to the array owner.

Parameters:

NameTypeDescription
resultArrayValueArray SSA value receiving the snapshot.
state_ArrayStateFrozen 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,
) -> None

Delegate detached branch snapshots to the array owner.

Parameters:

NameTypeDescription
resultArrayValueArray SSA result receiving the selected state.
when_true_ArrayStateDetached true-branch snapshot.
when_false_ArrayStateDetached false-branch snapshot.
selector_ResolvedClassicalFactBranch selector and its source dependencies.
bind_call_array_input
def bind_call_array_input(self, block: Block, formal: ArrayValue, state: _ArrayState) -> None

Delegate callable-entry array aliasing to the array owner.

Parameters:

NameTypeDescription
blockBlockSelected callable body.
formalArrayValueArray value paired with the call operand.
state_ArrayStateCaller state captured at invocation time.
bind_classical_fact
def bind_classical_fact(self, value: Value, fact: _ResolvedClassicalFact) -> None

Bind one scalar or whole-array provenance fact by SSA identity.

Parameters:

NameTypeDescription
valueValueIR value receiving the fact.
fact_ResolvedClassicalFactResolved 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,
) -> None

Bind 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:

NameTypeDescription
resultValueScalar SSA result receiving the selected fact.
when_true_ResolvedClassicalFactTrue-branch value and sources.
when_false_ResolvedClassicalFactFalse-branch value and sources.
selector_ResolvedClassicalFactBranch selector and its source dependencies.
value_overridesp.Basic | int | float | bool | NoneOptional 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,
) -> None

Delegate loop-entry array aliasing to the array owner.

Parameters:

NameTypeDescription
operationsSequence[Operation]Loop-body operations.
entryArrayValuePre-loop array value naming the carried lineage.
state_ArrayStateSnapshot 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,
) -> ExprResolver

Create 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:

NameTypeDescription
call_opAnyAn invocation carrying either a legacy block field, an InvokeOperation.effective_body() method, or an InvokeOperation.body field, plus operands containing actual arguments.
called_blockBlock | NoneAlready-selected callable body. Pass this when another resolver has selected a backend- or strategy-specific implementation. Defaults to None.
body_implements_transformboolWhether 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_operandsSequence[Any] | NoneCall-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:

NameTypeDescription
call_opAnyInvocation-like operation defining the call site.
called_blockBlockSelected 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,
) -> ExprResolver

Create 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:

NameTypeDescription
inner_blockAnyThe block for the child scope.
extra_contextdict[str, sp.Expr] | NoneAdditional UUID → expression mappings to merge into the child context.
extra_loop_varsdict[str, sp.Expr] | NoneAdditional 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) -> None

Detach 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:

NameTypeDescription
arraysSequence[ArrayValue] | NoneOptional 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,
) -> None

Delegate one execution-guarded update to the array owner.

Parameters:

NameTypeDescription
resultArrayValueArray SSA version produced by the store.
previousArrayValueArray version read by the store.
conditionsp.Basic | _ResolvedClassicalFactPredicate that the enclosing region executes, optionally with provenance.
import_array_context
def import_array_context(self, context: Mapping[str, _ArrayState], *, replace: bool = False) -> None

Import persistent array-state bindings into this resolver.

Parameters:

NameTypeDescription
contextMapping[str, _ArrayState]Exported UUID-to-state map.
replaceboolWhether 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,
) -> ExprResolver

Create 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:

NameTypeDescription
inner_blockAnyCallable block for the isolated scope.
extra_contextdict[str, sp.Expr] | NoneAdditional UUID to expression mappings for formal inputs. Defaults to None.
structural_scopetuple[tuple[int, int], ...] | NoneExplicit 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) -> None

Delegate one sequential store record to the array owner.

Parameters:

NameTypeDescription
operationStoreArrayElementOperationStore just encountered by the estimator’s sequential interpreter.
resolve
def resolve(self, v: Any) -> sp.Expr

Convert IR Value to SymPy expression (symbolic mode).

Unbound parameters become sp.Symbol. Never raises for valid IR.

Parameters:

NameTypeDescription
vAnyIR 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) -> _ResolvedClassicalFact

Resolve 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:

NameTypeDescription
valueAnyIR 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) -> int

Convert IR Value to concrete int.

Parameters:

NameTypeDescription
vAnyIR Value, primitive Python type, or sp.Basic.

Returns:

int — The resolved concrete integer.

Raises:

snapshot_array_state
def snapshot_array_state(
    self,
    array: ArrayValue,
    *,
    ignore_binding: str | None = None,
    visited: set[str] | None = None,
) -> _ArrayState

Delegate immutable array-state capture to the array owner.

Parameters:

NameTypeDescription
arrayArrayValueArray whose current state is captured.
ignore_bindingstr | NoneArray binding bypassed for one raw producer lookup. Defaults to None.
visitedset[str] | NoneArray 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 | None

Return 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:

NameTypeDescription
valueValueIR 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 GateResources

Track logical gate resources.

Parameters:

NameTypeDescription
totalResourceExprTotal logical gate count.
single_qubitResourceExprSingle-qubit gate count.
two_qubitResourceExprTwo-qubit gate count.
multi_qubitResourceExprThree-or-more-qubit gate count.
cliffordResourceExprClifford gate count.
rotationResourceExprParametric rotation gate count.
tResourceExprT/T-dagger gate count.
toffoliResourceExprToffoli gate count.
non_cliffordResourceExprNon-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,
) -> None
Attributes
Methods
simplify
def simplify(self) -> GateResources

Simplify all gate expressions.

Returns:

GateResources — Simplified copy.

zero
@staticmethod
def zero() -> GateResources

Return a zero gate estimate.

Returns:

GateResources — Empty gate resources.


MeasurementResources [source]

class MeasurementResources

Track logical measurement resources.

Parameters:

NameTypeDescription
totalResourceExprNumber 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:

Constructor
def __init__(self, total: ResourceExpr = _ZERO) -> None
Attributes
Methods
simplify
def simplify(self) -> MeasurementResources

Simplify all measurement expressions.

Returns:

MeasurementResources — Simplified copy.

zero
@staticmethod
def zero() -> MeasurementResources

Return a zero measurement estimate.

Returns:

MeasurementResources — Empty measurement resources.


OpaqueCostContext [source]

class OpaqueCostContext

Describe 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:

NameTypeDescription
callable_namestrHuman-readable callable name.
target_shapesMapping[str, tuple[ResourceExpr, ...]]Definition target shapes keyed by formal operand name. A scalar qubit has an empty shape tuple.
definition_control_qubitsintControls declared by the Oracle definition and already included in the callback’s base cost.
strategystr | NoneSelected base resource strategy. Defaults to None.
control_decompositionControlDecompositionRequested 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,
) -> None
Attributes

Operation [source]

class Operation(abc.ABC)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes
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]) -> Operation

Return 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]) -> None
Attributes

ResetResources [source]

class ResetResources

Track logical reset resources.

Parameters:

NameTypeDescription
totalResourceExprNumber of per-qubit reset events.

Raises:

Constructor
def __init__(self, total: ResourceExpr = _ZERO) -> None
Attributes
Methods
simplify
def simplify(self) -> ResetResources

Simplify all reset expressions.

Returns:

ResetResources — Simplified copy.

zero
@staticmethod
def zero() -> ResetResources

Return a zero reset estimate.

Returns:

ResetResources — Empty reset resources.


ResourceAssumption [source]

class ResourceAssumption

Record 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:

NameTypeDescription
messagestrHuman-readable premise or qualification.
sourcestr | NoneOptional 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) -> None
Attributes

ResourceEstimate [source]

class ResourceEstimate

Carry the full algorithmic resource estimate for a qkernel or block.

Parameters:

NameTypeDescription
widthWidthResourcesLogical width and ancilla estimate.
gatesGateResourcesLogical gate-resource estimate.
depthDepthResourcesLogical depth-resource estimate.
callsCallResourcesCallable/query-resource estimate.
measurementsMeasurementResourcesPer-qubit measurement resources.
resetsResetResourcesPer-qubit reset resources.
assumptionstuple[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.
traceResourceTraceNode | NoneExplanation tree root. Defaults to None.
parametersdict[str, sp.Symbol]Symbols present in the estimate, keyed by unique public aliases. Defaults to an empty dict.
derivationEstimateDerivationWhether counts are derived from visible structure or use a resource model. Defaults to STRUCTURAL.
qualityEstimateQualityRelationship 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.
approximationApproximationStatusWhether the selected circuit approximates an ideal mathematical operation. Defaults to EXACT.
control_decompositionControlDecompositionCoherent-control decomposition used for the estimate. Defaults to the clean-ancilla Toffoli model.
_allocation_sitesdict[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.
_constraintstuple[_ResourceConstraint, ...]Internal structural requirements retained across symbolic substitution.
_output_sizesdict[str, ResourceExpr]Internal live quantum output widths keyed by root allocation owner for nested control-flow operations.
_input_sizesdict[str, ResourceExpr]Internal captured quantum input widths consumed or replaced by nested control-flow operations.
_has_output_summaryboolWhether _output_sizes is authoritative, including when a nested operation has no live quantum outputs.
_dependency_keysfrozenset[WireKey] | NoneInternal caller-scoped quantum wires that contribute nonzero depth. None requests the enclosing operation’s conservative ordinary footprint.
_dependency_readsfrozenset[WireKey] | NoneInternal scheduler inputs for rescheduling an already interpreted body, including immutable classical observation tokens. None means that only _dependency_keys is available.
_dependency_writesfrozenset[WireKey] | NoneInternal scheduler outputs for rescheduling an already interpreted body, including newly published observation tokens. None means that only _dependency_keys is available.
_dependency_completiondict[WireKey, ResourceExpr] | NoneInternal caller-visible completion depth for each dependency wire. None requests conservative reconstruction from _dependency_keys or the enclosing operation footprint.
_dependency_completion_uniformbool | NoneWhether 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_conditionsdict[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_certificatestuple[_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_conditionBooleanCondition under which an opaque, nested non-unitary, or runtime-control boundary lacks enough wire-level provenance for exact dependency scheduling.
_measurement_taint_conditionsdict[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_assumptionstuple[_GuardedAssumption, ...] | NoneInternal condition-aware assumption provenance. None initializes facts from the public assumptions tuple.
_guarded_derivationstuple[_GuardedDerivation, ...] | NoneInternal condition-aware modeled-derivation provenance. None initializes a fact from the public derivation value.
_guarded_qualitiestuple[_GuardedQuality, ...] | NoneInternal 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_approximationstuple[_GuardedApproximation, ...] | NoneInternal condition-aware mathematical approximation provenance. None initializes a fact from the public approximation value.
_symbol_aliasesdict[sp.Symbol, str]Internal stable public aliases retained across expression rewrites and partial substitution.
_domain_rewrite_policy_DomainRewritePolicyWhether qkernel input domain simplification is inherited, enabled, or disabled.
_domain_rewrite_state_DomainRewriteState | NoneOriginal public metrics and exact consumed predicates for a conditional rewrite.
_rendered_assumption_snapshottuple[ResourceAssumption, ...] | NoneIdentity-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,
) -> None
Attributes
Methods
choice
def choice(self, other: ResourceEstimate) -> ResourceEstimate

Compose a conservative branch choice.

Parameters:

NameTypeDescription
otherResourceEstimateAlternative branch estimate.

Returns:

ResourceEstimate — Element-wise maximum of both branches.

Raises:

conditional
def conditional(self, other: ResourceEstimate, condition: sp.Basic) -> ResourceEstimate

Select this estimate or another with a symbolic condition.

Parameters:

NameTypeDescription
otherResourceEstimateEstimate for the false branch.
conditionsp.BasicSymPy Boolean selecting this estimate when true and other when false.

Returns:

ResourceEstimate — Field-wise exact piecewise branch estimate.

Raises:

controlled
def controlled(self, num_controls: ResourceExpr | int) -> ResourceEstimate

Estimate 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:

NameTypeDescription
num_controlsResourceExpr | intNumber of active controls.

Returns:

ResourceEstimate — Estimate with a recorded controlled assumption.

Raises:

explain
def explain(self, metric: str | None = None) -> str

Render the resource-estimation trace.

Parameters:

NameTypeDescription
metricstr | NoneOptional metric name to mention in the heading. Filtering is reserved for a later pass. Defaults to None.

Returns:

str — Human-readable explanation tree.

Raises:

inverse
def inverse(self) -> ResourceEstimate

Apply an inverse transform.

Returns:

ResourceEstimate — Estimate with identical logical resources.

Raises:

parallel
def parallel(self, other: ResourceEstimate) -> ResourceEstimate

Compose this estimate in parallel with another estimate.

Parameters:

NameTypeDescription
otherResourceEstimateEstimate that runs concurrently.

Returns:

ResourceEstimate — Parallel composition.

Raises:

primitive
@staticmethod
def primitive(
    name: str,
    gates: GateResources | None = None,
    *,
    width: WidthResources | None = None,
    depth: DepthResources | None = None,
) -> ResourceEstimate

Create an estimate for one primitive operation.

Parameters:

NameTypeDescription
namestrPrimitive operation name.
gatesGateResources | NoneGate resources. Defaults to zero.
widthWidthResources | NoneWidth resources. Defaults to zero.
depthDepthResources | NoneDepth 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) -> ResourceEstimate

Repeat this estimate with reusable width.

Parameters:

NameTypeDescription
factorResourceExpr | intIteration or power factor.

Returns:

ResourceEstimate — Repeated estimate.

Raises:

seq
def seq(self, other: ResourceEstimate) -> ResourceEstimate

Compose this estimate before another estimate.

Parameters:

NameTypeDescription
otherResourceEstimateEstimate that runs after this one.

Returns:

ResourceEstimate — Sequentially composed estimate.

Raises:

seq_all
@staticmethod
def seq_all(estimates: Iterable[ResourceEstimate]) -> ResourceEstimate

Compose 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:

NameTypeDescription
estimatesIterable[ResourceEstimate]Estimates in execution order.

Returns:

ResourceEstimate — Sequential composition, or an exact zero ResourceEstimate — estimate for an empty sequence.

Raises:

simplify
def simplify(self) -> ResourceEstimate

Simplify 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:

substitute
def substitute(self, **values: object = {}) -> ResourceEstimate

Substitute 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:

NameTypeDescription
**valuesobjectMapping from parameter name to a concrete numeric scalar.

Returns:

ResourceEstimate — Estimate with substituted expressions.

Raises:

sum_over
def sum_over(
    self,
    loop_symbol: sp.Symbol,
    start: ResourceExpr,
    stop: ResourceExpr,
    step: ResourceExpr = _ONE,
) -> ResourceEstimate

Sum loop-dependent resources over Python range semantics.

Parameters:

NameTypeDescription
loop_symbolsp.SymbolSymbol used for the loop variable.
startResourceExprInclusive start bound.
stopResourceExprExclusive stop bound.
stepResourceExprLoop step. Defaults to one.

Returns:

ResourceEstimate — Estimate with additive metrics summed over the ResourceEstimate — loop and width kept reusable.

Raises:

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:

zero
@staticmethod
def zero(trace_name: str | None = None) -> ResourceEstimate

Return an empty resource estimate.

Parameters:

NameTypeDescription
trace_namestr | NoneOptional trace-node name for the empty estimate. Defaults to None.

Returns:

ResourceEstimate — Zero-valued estimate.


ResourceEstimator [source]

class ResourceEstimator

Estimate algorithmic resources for qkernels and IR blocks.

Parameters:

NameTypeDescription
strategiesdict[str, str] | NoneStrategy overrides by callable name. Defaults to None.
traceboolWhether to keep explanation traces. Defaults to False.
simplifyboolWhether to simplify final expressions, including simplification over valid qkernel input conditions. Defaults to True.
unknown_policystr | UnknownResourcePolicyHandling for unknown bodyless callables. Defaults to ERROR.
control_decompositionstr | ControlDecompositionCoherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI.

Raises:

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,
) -> None

Initialize a resource estimator.

Parameters:

NameTypeDescription
strategiesdict[str, str] | NoneStrategy overrides by callable name. Defaults to None.
traceboolWhether to keep explanation traces. Defaults to False.
simplifyboolWhether 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_policystr | UnknownResourcePolicyHandling for unknown bodyless callables. Defaults to ERROR.
control_decompositionstr | ControlDecompositionCoherent-control decomposition. Defaults to CLEAN_ANCILLA_TOFFOLI.

Raises:

Attributes
Methods
estimate
def estimate(
    self,
    kernel: 'QKernel[Any, Any] | Block | Sequence[Operation]',
    *,
    inputs: dict[str, Any] | None = None,
    strategies: dict[str, str] | None = None,
) -> ResourceEstimate

Estimate algorithmic resources for a qkernel, block, or operations.

Parameters:

NameTypeDescription
kernelQKernel[Any, Any] | Block | Sequence[Operation]Object to estimate. QKernel-like objects are built before traversal.
inputsdict[str, Any] | NoneQKernel 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.
strategiesdict[str, str] | NonePer-call override merged over estimator-level strategies. Defaults to None.

Returns:

ResourceEstimate — Algorithmic resource estimate.

Raises:


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,
) -> ResourceEstimate

Evaluate 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:

NameTypeDescription
operationPauliEvolveOpPauli evolution operation.
resolverExprResolverResolver for observable and time operands.
controlsResourceExpr | intSurrounding 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:


ResourceTraceNode [source]

class ResourceTraceNode

Represent one node in the resource-estimation explanation tree.

Parameters:

NameTypeDescription
namestrOperation or callable name.
source_kindstrSource type such as "primitive", "body", "opaque_cost", or "opaque".
strategystr | NoneSelected resource strategy. Defaults to None.
summarystrShort expression summary. Defaults to an empty string.
assumptionstuple[ResourceAssumption, ...]Assumptions local to the node. Defaults to an empty tuple.
childrentuple[ResourceTraceNode, ...]Nested trace nodes. Defaults to an empty tuple.
active_whensp.BasicSymbolic 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,
) -> None
Attributes
Methods
mapped
def mapped(self, fn: Any) -> ResourceTraceNode | None

Rewrite activation guards and remove inactive trace branches.

Parameters:

NameTypeDescription
fnAnySymbolic-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) -> str

Render this trace node as plain text.

Parameters:

NameTypeDescription
indentintNumber of leading spaces. Defaults to 0.
registrySymbolRegistry | NoneShared 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) -> ResourceTraceNode

Return this trace guarded by an additional condition.

Parameters:

NameTypeDescription
conditionsp.BasicBranch 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

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, ...] = (),
) -> None
Attributes
Methods
is_array_element
def is_array_element(self) -> bool
next_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 ValueBase

Nominal 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
Methods
get_const
def get_const(self) -> int | float | bool | None

Return 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) -> bool

Return whether this value carries a scalar constant.

Returns:

bool — Whether scalar constant metadata is present.

is_parameter
def is_parameter(self) -> bool

Return whether this value represents a runtime parameter.

Returns:

bool — Whether parameter metadata is present.

next_version
def next_version(self) -> ValueBase

Create 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 | None

Return 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 WidthResources

Track logical width and ancilla resources.

Parameters:

NameTypeDescription
input_qubitsResourceExprQubits supplied by the caller.
allocated_qubitsResourceExprQubits allocated by the body.
clean_ancilla_qubitsResourceExprClean ancilla qubits required at peak. Defaults to zero.
dirty_ancilla_qubitsResourceExprDirty ancilla qubits required at peak. Defaults to zero.
peak_qubitsResourceExprConservative 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,
) -> None
Attributes
Methods
simplify
def simplify(self) -> WidthResources

Simplify all width expressions.

Returns:

WidthResources — Simplified copy.

zero
@staticmethod
def zero() -> WidthResources

Return a zero width estimate.

Returns:

WidthResources — Empty width resources.


qamomile.circuit.estimator.wire

Stable stateful codecs for fixed resource-estimate wire payloads.

Overview

FunctionDescription
resource_estimate_from_wireDecode one fixed resource estimate from semantic IR data.
resource_estimate_to_wireEncode one fixed resource estimate as serializer-friendly data.
ClassDescription
ResourceEstimateCarry the full algorithmic resource estimate for a qkernel or block.
ResourceEstimateWireDecoderDecode one payload stream while preserving shared Dummy identities.
ResourceEstimateWireEncoderEncode 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,
) -> ResourceEstimate

Decode one fixed resource estimate from semantic IR data.

Parameters:

NameTypeDescription
payloadAnyPayload produced by :func:resource_estimate_to_wire.
decoder_WireExpressionDecoder | NoneOptional payload-wide expression decoder shared by every opaque cost in one serialized qkernel. Defaults to None.

Returns:

ResourceEstimate — Reconstructed fixed resource estimate.

Raises:


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:

NameTypeDescription
estimateResourceEstimateFixed resource estimate to encode.
dummy_slotsdict[sp.Dummy, int] | NoneOptional 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:

Classes

ResourceEstimate [source]

class ResourceEstimate

Carry the full algorithmic resource estimate for a qkernel or block.

Parameters:

NameTypeDescription
widthWidthResourcesLogical width and ancilla estimate.
gatesGateResourcesLogical gate-resource estimate.
depthDepthResourcesLogical depth-resource estimate.
callsCallResourcesCallable/query-resource estimate.
measurementsMeasurementResourcesPer-qubit measurement resources.
resetsResetResourcesPer-qubit reset resources.
assumptionstuple[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.
traceResourceTraceNode | NoneExplanation tree root. Defaults to None.
parametersdict[str, sp.Symbol]Symbols present in the estimate, keyed by unique public aliases. Defaults to an empty dict.
derivationEstimateDerivationWhether counts are derived from visible structure or use a resource model. Defaults to STRUCTURAL.
qualityEstimateQualityRelationship 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.
approximationApproximationStatusWhether the selected circuit approximates an ideal mathematical operation. Defaults to EXACT.
control_decompositionControlDecompositionCoherent-control decomposition used for the estimate. Defaults to the clean-ancilla Toffoli model.
_allocation_sitesdict[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.
_constraintstuple[_ResourceConstraint, ...]Internal structural requirements retained across symbolic substitution.
_output_sizesdict[str, ResourceExpr]Internal live quantum output widths keyed by root allocation owner for nested control-flow operations.
_input_sizesdict[str, ResourceExpr]Internal captured quantum input widths consumed or replaced by nested control-flow operations.
_has_output_summaryboolWhether _output_sizes is authoritative, including when a nested operation has no live quantum outputs.
_dependency_keysfrozenset[WireKey] | NoneInternal caller-scoped quantum wires that contribute nonzero depth. None requests the enclosing operation’s conservative ordinary footprint.
_dependency_readsfrozenset[WireKey] | NoneInternal scheduler inputs for rescheduling an already interpreted body, including immutable classical observation tokens. None means that only _dependency_keys is available.
_dependency_writesfrozenset[WireKey] | NoneInternal scheduler outputs for rescheduling an already interpreted body, including newly published observation tokens. None means that only _dependency_keys is available.
_dependency_completiondict[WireKey, ResourceExpr] | NoneInternal caller-visible completion depth for each dependency wire. None requests conservative reconstruction from _dependency_keys or the enclosing operation footprint.
_dependency_completion_uniformbool | NoneWhether 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_conditionsdict[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_certificatestuple[_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_conditionBooleanCondition under which an opaque, nested non-unitary, or runtime-control boundary lacks enough wire-level provenance for exact dependency scheduling.
_measurement_taint_conditionsdict[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_assumptionstuple[_GuardedAssumption, ...] | NoneInternal condition-aware assumption provenance. None initializes facts from the public assumptions tuple.
_guarded_derivationstuple[_GuardedDerivation, ...] | NoneInternal condition-aware modeled-derivation provenance. None initializes a fact from the public derivation value.
_guarded_qualitiestuple[_GuardedQuality, ...] | NoneInternal 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_approximationstuple[_GuardedApproximation, ...] | NoneInternal condition-aware mathematical approximation provenance. None initializes a fact from the public approximation value.
_symbol_aliasesdict[sp.Symbol, str]Internal stable public aliases retained across expression rewrites and partial substitution.
_domain_rewrite_policy_DomainRewritePolicyWhether qkernel input domain simplification is inherited, enabled, or disabled.
_domain_rewrite_state_DomainRewriteState | NoneOriginal public metrics and exact consumed predicates for a conditional rewrite.
_rendered_assumption_snapshottuple[ResourceAssumption, ...] | NoneIdentity-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,
) -> None
Attributes
Methods
choice
def choice(self, other: ResourceEstimate) -> ResourceEstimate

Compose a conservative branch choice.

Parameters:

NameTypeDescription
otherResourceEstimateAlternative branch estimate.

Returns:

ResourceEstimate — Element-wise maximum of both branches.

Raises:

conditional
def conditional(self, other: ResourceEstimate, condition: sp.Basic) -> ResourceEstimate

Select this estimate or another with a symbolic condition.

Parameters:

NameTypeDescription
otherResourceEstimateEstimate for the false branch.
conditionsp.BasicSymPy Boolean selecting this estimate when true and other when false.

Returns:

ResourceEstimate — Field-wise exact piecewise branch estimate.

Raises:

controlled
def controlled(self, num_controls: ResourceExpr | int) -> ResourceEstimate

Estimate 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:

NameTypeDescription
num_controlsResourceExpr | intNumber of active controls.

Returns:

ResourceEstimate — Estimate with a recorded controlled assumption.

Raises:

explain
def explain(self, metric: str | None = None) -> str

Render the resource-estimation trace.

Parameters:

NameTypeDescription
metricstr | NoneOptional metric name to mention in the heading. Filtering is reserved for a later pass. Defaults to None.

Returns:

str — Human-readable explanation tree.

Raises:

inverse
def inverse(self) -> ResourceEstimate

Apply an inverse transform.

Returns:

ResourceEstimate — Estimate with identical logical resources.

Raises:

parallel
def parallel(self, other: ResourceEstimate) -> ResourceEstimate

Compose this estimate in parallel with another estimate.

Parameters:

NameTypeDescription
otherResourceEstimateEstimate that runs concurrently.

Returns:

ResourceEstimate — Parallel composition.

Raises:

primitive
@staticmethod
def primitive(
    name: str,
    gates: GateResources | None = None,
    *,
    width: WidthResources | None = None,
    depth: DepthResources | None = None,
) -> ResourceEstimate

Create an estimate for one primitive operation.

Parameters:

NameTypeDescription
namestrPrimitive operation name.
gatesGateResources | NoneGate resources. Defaults to zero.
widthWidthResources | NoneWidth resources. Defaults to zero.
depthDepthResources | NoneDepth 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) -> ResourceEstimate

Repeat this estimate with reusable width.

Parameters:

NameTypeDescription
factorResourceExpr | intIteration or power factor.

Returns:

ResourceEstimate — Repeated estimate.

Raises:

seq
def seq(self, other: ResourceEstimate) -> ResourceEstimate

Compose this estimate before another estimate.

Parameters:

NameTypeDescription
otherResourceEstimateEstimate that runs after this one.

Returns:

ResourceEstimate — Sequentially composed estimate.

Raises:

seq_all
@staticmethod
def seq_all(estimates: Iterable[ResourceEstimate]) -> ResourceEstimate

Compose 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:

NameTypeDescription
estimatesIterable[ResourceEstimate]Estimates in execution order.

Returns:

ResourceEstimate — Sequential composition, or an exact zero ResourceEstimate — estimate for an empty sequence.

Raises:

simplify
def simplify(self) -> ResourceEstimate

Simplify 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:

substitute
def substitute(self, **values: object = {}) -> ResourceEstimate

Substitute 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:

NameTypeDescription
**valuesobjectMapping from parameter name to a concrete numeric scalar.

Returns:

ResourceEstimate — Estimate with substituted expressions.

Raises:

sum_over
def sum_over(
    self,
    loop_symbol: sp.Symbol,
    start: ResourceExpr,
    stop: ResourceExpr,
    step: ResourceExpr = _ONE,
) -> ResourceEstimate

Sum loop-dependent resources over Python range semantics.

Parameters:

NameTypeDescription
loop_symbolsp.SymbolSymbol used for the loop variable.
startResourceExprInclusive start bound.
stopResourceExprExclusive stop bound.
stepResourceExprLoop step. Defaults to one.

Returns:

ResourceEstimate — Estimate with additive metrics summed over the ResourceEstimate — loop and width kept reusable.

Raises:

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:

zero
@staticmethod
def zero(trace_name: str | None = None) -> ResourceEstimate

Return an empty resource estimate.

Parameters:

NameTypeDescription
trace_namestr | NoneOptional trace-node name for the empty estimate. Defaults to None.

Returns:

ResourceEstimate — Zero-valued estimate.


ResourceEstimateWireDecoder [source]

class ResourceEstimateWireDecoder

Decode one payload stream while preserving shared Dummy identities.

Constructor
def __init__(self) -> None

Initialize one payload-wide symbolic-expression decoder.


ResourceEstimateWireEncoder [source]

class ResourceEstimateWireEncoder

Encode one payload stream while preserving shared Dummy identities.

Constructor
def __init__(self) -> None

Initialize an empty payload-wide Dummy slot mapping.